Merge branch 'master' into feature_rollouts_credentials

Conflicts:
	hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityAutoConfiguration.java
	hawkbit-repository/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java
	hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ArtifactManagement.java
	hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DeploymentManagement.java
	hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java
	hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ReportManagement.java
	hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutGroupManagement.java
	hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutManagement.java
	hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareManagement.java
	hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SystemManagement.java
	hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TagManagement.java
	hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagement.java
	hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetManagement.java
	hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantConfigurationManagement.java
	hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantStatsManagement.java


Signed-off-by: SirWayne <dennis.melzer@bosch-si.com>
This commit is contained in:
SirWayne
2016-06-06 10:35:02 +02:00
468 changed files with 18936 additions and 12963 deletions

2
.gitignore vendored
View File

@@ -53,3 +53,5 @@ local.properties
# Maven
maven.properties
/*/maven.properties
hawkbit-repository/hawkbit-repository-jpa/.springBeans

View File

@@ -79,6 +79,11 @@
<artifactId>hawkbit-http-security</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-repository-jpa</artifactId>
<version>${project.version}</version>
</dependency>
<!-- Spring -->
<dependency>

View File

@@ -8,11 +8,10 @@ package org.eclipse.hawkbit.app;
* http://www.eclipse.org/legal/epl-v10.html
*/
import org.eclipse.hawkbit.RepositoryApplicationConfiguration;
import org.eclipse.hawkbit.EnableJpaRepository;
import org.eclipse.hawkbit.autoconfigure.security.EnableHawkbitManagedSecurityConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;
/**
* A {@link SpringBootApplication} annotated class with a main method to start.
@@ -20,10 +19,10 @@ import org.springframework.context.annotation.Import;
*
*/
@SpringBootApplication
@Import({ RepositoryApplicationConfiguration.class })
@EnableHawkbitManagedSecurityConfiguration
// Exception squid:S1118 - Spring boot standard behavior
@SuppressWarnings({ "squid:S1118" })
@EnableJpaRepository
public class Start {
/**
* Main method to start the spring-boot application.

View File

@@ -116,10 +116,6 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
@@ -127,12 +123,10 @@
<dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-jackson</artifactId>
<version>8.14.1</version>
</dependency>
<dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-core</artifactId>
<version>8.12.1</version>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>

View File

@@ -236,6 +236,10 @@ public class DeviceSimulatorUpdater {
}
final File tempFile = File.createTempFile("uploadFile", null);
// Exception squid:S2070 - not used for hashing sensitive
// data
@SuppressWarnings("squid:S2070")
final MessageDigest md = MessageDigest.getInstance("SHA-1");
try (final DigestOutputStream dos = new DigestOutputStream(new FileOutputStream(tempFile), md)) {

View File

@@ -92,6 +92,11 @@
<artifactId>hawkbit-http-security</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-repository-jpa</artifactId>
<version>${project.version}</version>
</dependency>
<!-- Spring -->
<dependency>

View File

@@ -8,13 +8,12 @@
*/
package org.eclipse.hawkbit.app;
import org.eclipse.hawkbit.RepositoryApplicationConfiguration;
import org.eclipse.hawkbit.EnableJpaRepository;
import org.eclipse.hawkbit.autoconfigure.security.EnableHawkbitManagedSecurityConfiguration;
import org.eclipse.hawkbit.ddi.EnableDdiApi;
import org.eclipse.hawkbit.mgmt.EnableMgmtApi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;
/**
* A {@link SpringBootApplication} annotated class with a main method to start.
@@ -22,10 +21,10 @@ import org.springframework.context.annotation.Import;
*
*/
@SpringBootApplication
@Import({ RepositoryApplicationConfiguration.class })
@EnableHawkbitManagedSecurityConfiguration
@EnableMgmtApi
@EnableDdiApi
@EnableJpaRepository
// Exception squid:S1118 - Spring boot standard behavior
@SuppressWarnings({ "squid:S1118" })
public class Start {

View File

@@ -1,3 +1,4 @@
/target/
/bin/
/.apt_generated/
/.springBeans

View File

@@ -124,11 +124,9 @@ public class ArtifactStore implements ArtifactRepository {
try {
LOGGER.debug("storing file {} of content {}", filename, contentType);
tempFile = File.createTempFile("uploadFile", null);
try (final FileOutputStream os = new FileOutputStream(tempFile)) {
try (BufferedOutputStream bos = new BufferedOutputStream(os)) {
try (BufferedInputStream bis = new BufferedInputStream(content)) {
return store(content, contentType, bos, tempFile, hash);
}
try (final BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tempFile))) {
try (BufferedInputStream bis = new BufferedInputStream(content)) {
return store(bis, contentType, bos, tempFile, hash);
}
}
} catch (final IOException | MongoException e1) {
@@ -207,6 +205,9 @@ public class ArtifactStore implements ArtifactRepository {
throws NoSuchAlgorithmException, IOException {
String sha1Hash;
// compute digest
// Exception squid:S2070 - not used for hashing sensitive
// data
@SuppressWarnings("squid:S2070")
final MessageDigest md = MessageDigest.getInstance("SHA-1");
try (final DigestOutputStream dos = new DigestOutputStream(os, md)) {
ByteStreams.copy(stream, dos);

View File

@@ -46,7 +46,7 @@
</dependency>
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-repository</artifactId>
<artifactId>hawkbit-repository-jpa</artifactId>
<version>${project.version}</version>
<optional>true</optional>
</dependency>

View File

@@ -12,7 +12,7 @@ import java.util.concurrent.Executor;
import org.eclipse.hawkbit.eventbus.EventBusSubscriberProcessor;
import org.eclipse.hawkbit.eventbus.EventSubscriber;
import org.eclipse.hawkbit.repository.model.helper.EventBusHolder;
import org.eclipse.hawkbit.repository.jpa.model.helper.EventBusHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;

View File

@@ -0,0 +1,25 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.autoconfigure.repository;
import org.eclipse.hawkbit.EnableJpaRepository;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* Auto-Configuration for enabling the REST-Resources.
*
*/
@Configuration
@ConditionalOnClass({ EnableJpaRepository.class })
@Import({ EnableJpaRepository.class })
public class JpaRepositoryAutoConfiguration {
}

View File

@@ -10,6 +10,7 @@ package org.eclipse.hawkbit.autoconfigure.security;
import org.eclipse.hawkbit.im.authentication.PermissionService;
import org.eclipse.hawkbit.security.DdiSecurityProperties;
import org.eclipse.hawkbit.security.DdiSecurityProperties;
import org.eclipse.hawkbit.security.SecurityContextTenantAware;
import org.eclipse.hawkbit.security.SpringSecurityAuditorAware;
import org.eclipse.hawkbit.tenancy.TenantAware;

View File

@@ -30,60 +30,45 @@ public enum TenantConfigurationKey {
/**
* boolean value {@code true} {@code false}.
*/
AUTHENTICATION_MODE_HEADER_ENABLED("authentication.header.enabled",
"hawkbit.server.ddi.security.authentication.header.enabled", Boolean.class, Boolean.FALSE.toString(),
TenantConfigurationBooleanValidator.class),
AUTHENTICATION_MODE_HEADER_ENABLED("authentication.header.enabled", "hawkbit.server.ddi.security.authentication.header.enabled", Boolean.class, Boolean.FALSE.toString(), TenantConfigurationBooleanValidator.class),
/**
*
*/
AUTHENTICATION_MODE_HEADER_AUTHORITY_NAME("authentication.header.authority",
"hawkbit.server.ddi.security.authentication.header.authority", String.class, Boolean.FALSE.toString(),
TenantConfigurationStringValidator.class),
AUTHENTICATION_MODE_HEADER_AUTHORITY_NAME("authentication.header.authority", "hawkbit.server.ddi.security.authentication.header.authority", String.class, Boolean.FALSE.toString(), TenantConfigurationStringValidator.class),
/**
* boolean value {@code true} {@code false}.
*/
AUTHENTICATION_MODE_TARGET_SECURITY_TOKEN_ENABLED("authentication.targettoken.enabled",
"hawkbit.server.ddi.security.authentication.targettoken.enabled", Boolean.class, Boolean.FALSE.toString(),
TenantConfigurationBooleanValidator.class),
AUTHENTICATION_MODE_TARGET_SECURITY_TOKEN_ENABLED("authentication.targettoken.enabled", "hawkbit.server.ddi.security.authentication.targettoken.enabled", Boolean.class, Boolean.FALSE.toString(), TenantConfigurationBooleanValidator.class),
/**
* boolean value {@code true} {@code false}.
*/
AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_ENABLED("authentication.gatewaytoken.enabled",
"hawkbit.server.ddi.security.authentication.gatewaytoken.enabled", Boolean.class, Boolean.FALSE.toString(),
TenantConfigurationBooleanValidator.class),
AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_ENABLED("authentication.gatewaytoken.enabled", "hawkbit.server.ddi.security.authentication.gatewaytoken.enabled", Boolean.class, Boolean.FALSE.toString(), TenantConfigurationBooleanValidator.class),
/**
* string value which holds the name of the security token key.
*/
AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_NAME("authentication.gatewaytoken.name",
"hawkbit.server.ddi.security.authentication.gatewaytoken.name", String.class, null,
TenantConfigurationStringValidator.class),
AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_NAME("authentication.gatewaytoken.name", "hawkbit.server.ddi.security.authentication.gatewaytoken.name", String.class, null, TenantConfigurationStringValidator.class),
/**
* string value which holds the actual security-key of the gateway security
* token.
*/
AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY("authentication.gatewaytoken.key",
"hawkbit.server.ddi.security.authentication.gatewaytoken.key", String.class, null,
TenantConfigurationStringValidator.class),
AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY("authentication.gatewaytoken.key", "hawkbit.server.ddi.security.authentication.gatewaytoken.key", String.class, null, TenantConfigurationStringValidator.class),
/**
* string value which holds the polling time interval in the format HH:mm:ss
*/
POLLING_TIME_INTERVAL("pollingTime", "hawkbit.controller.pollingTime", String.class, null,
TenantConfigurationPollingDurationValidator.class),
POLLING_TIME_INTERVAL("pollingTime", "hawkbit.controller.pollingTime", String.class, null, TenantConfigurationPollingDurationValidator.class),
/**
* string value which holds the polling time interval in the format HH:mm:ss
*/
POLLING_OVERDUE_TIME_INTERVAL("pollingOverdueTime", "hawkbit.controller.pollingOverdueTime", String.class, null,
TenantConfigurationPollingDurationValidator.class),
POLLING_OVERDUE_TIME_INTERVAL("pollingOverdueTime", "hawkbit.controller.pollingOverdueTime", String.class, null, TenantConfigurationPollingDurationValidator.class),
/**
* boolean value {@code true} {@code false}.
*/
ANONYMOUS_DOWNLOAD_MODE_ENABLED("anonymous.download.enabled", "hawkbit.server.download.anonymous.enabled",
Boolean.class, Boolean.FALSE.toString(), TenantConfigurationBooleanValidator.class);
ANONYMOUS_DOWNLOAD_MODE_ENABLED("anonymous.download.enabled", "hawkbit.server.download.anonymous.enabled", Boolean.class, Boolean.FALSE.toString(), TenantConfigurationBooleanValidator.class);
private final String keyName;
private final String defaultKeyName;
@@ -140,8 +125,9 @@ public enum TenantConfigurationKey {
* @return the data type of the tenant configuration value. (e.g.
* Integer.class, String.class)
*/
public Class<?> getDataType() {
return dataType;
@SuppressWarnings("unchecked")
public <T> Class<T> getDataType() {
return (Class<T>) dataType;
}
/**

View File

@@ -38,7 +38,7 @@
</dependency>
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-repository</artifactId>
<artifactId>hawkbit-repository-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
@@ -48,6 +48,18 @@
<!-- Test -->
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-repository-test</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-repository-jpa</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-rest-core</artifactId>
@@ -93,7 +105,7 @@
</dependency>
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-repository</artifactId>
<artifactId>hawkbit-repository-jpa</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
<scope>test</scope>

View File

@@ -15,10 +15,11 @@ import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
import org.eclipse.hawkbit.cache.CacheWriteNotify;
import org.eclipse.hawkbit.ddi.dl.rest.api.DdiDlArtifactStoreControllerRestApi;
import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.ControllerManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.RepositoryConstants;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.ActionStatus;
@@ -58,15 +59,15 @@ public class DdiArtifactStoreController implements DdiDlArtifactStoreControllerR
@Autowired
private ControllerManagement controllerManagement;
@Autowired
private CacheWriteNotify cacheWriteNotify;
@Autowired
private HawkbitSecurityProperties securityProperties;
@Autowired
private RequestResponseContextHolder requestResponseContextHolder;
@Autowired
private EntityFactory entityFactory;
@Override
public ResponseEntity<InputStream> downloadArtifactByFilename(@PathVariable("fileName") final String fileName,
@AuthenticationPrincipal final String targetid) {
@@ -96,7 +97,8 @@ public class DdiArtifactStoreController implements DdiDlArtifactStoreControllerR
requestResponseContextHolder.getHttpServletRequest(), targetid, artifact);
result = RestResourceConversionHelper.writeFileResponse(artifact,
requestResponseContextHolder.getHttpServletResponse(),
requestResponseContextHolder.getHttpServletRequest(), file, cacheWriteNotify, action.getId());
requestResponseContextHolder.getHttpServletRequest(), file, controllerManagement,
action.getId());
} else {
result = RestResourceConversionHelper.writeFileResponse(artifact,
requestResponseContextHolder.getHttpServletResponse(),
@@ -138,19 +140,19 @@ public class DdiArtifactStoreController implements DdiDlArtifactStoreControllerR
.getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(), artifact.getSoftwareModule());
final String range = request.getHeader("Range");
final ActionStatus actionStatus = new ActionStatus();
final ActionStatus actionStatus = entityFactory.generateActionStatus();
actionStatus.setAction(action);
actionStatus.setOccurredAt(System.currentTimeMillis());
actionStatus.setStatus(Status.DOWNLOAD);
if (range != null) {
actionStatus.addMessage(ControllerManagement.SERVER_MESSAGE_PREFIX + "Target downloads range " + range
actionStatus.addMessage(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads range " + range
+ " of: " + request.getRequestURI());
} else {
actionStatus.addMessage(
ControllerManagement.SERVER_MESSAGE_PREFIX + "Target downloads: " + request.getRequestURI());
RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads: " + request.getRequestURI());
}
controllerManagement.addActionStatusMessage(actionStatus);
controllerManagement.addInformationalActionStatus(actionStatus);
return action;
}

View File

@@ -17,7 +17,6 @@ import javax.validation.Valid;
import org.eclipse.hawkbit.api.ArtifactUrlHandler;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
import org.eclipse.hawkbit.cache.CacheWriteNotify;
import org.eclipse.hawkbit.ddi.json.model.DdiActionFeedback;
import org.eclipse.hawkbit.ddi.json.model.DdiCancel;
import org.eclipse.hawkbit.ddi.json.model.DdiCancelActionToStop;
@@ -31,6 +30,8 @@ import org.eclipse.hawkbit.ddi.json.model.DdiResult.FinalResult;
import org.eclipse.hawkbit.ddi.rest.api.DdiRootControllerRestApi;
import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.ControllerManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.RepositoryConstants;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Action;
@@ -81,9 +82,6 @@ public class DdiRootController implements DdiRootControllerRestApi {
@Autowired
private ArtifactManagement artifactManagement;
@Autowired
private CacheWriteNotify cacheWriteNotify;
@Autowired
private HawkbitSecurityProperties securityProperties;
@@ -96,6 +94,9 @@ public class DdiRootController implements DdiRootControllerRestApi {
@Autowired
private RequestResponseContextHolder requestResponseContextHolder;
@Autowired
private EntityFactory entityFactory;
@Override
public ResponseEntity<List<org.eclipse.hawkbit.ddi.json.model.DdiArtifact>> getSoftwareModulesArtifacts(
@PathVariable("targetid") final String targetid,
@@ -132,7 +133,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
return new ResponseEntity<>(
DataConversionHelper.fromTarget(target, controllerManagement.findActionByTargetAndActive(target),
controllerManagement.findPollingTime(), tenantAware),
controllerManagement.getPollingTime(), tenantAware),
HttpStatus.OK);
}
@@ -162,7 +163,8 @@ public class DdiRootController implements DdiRootControllerRestApi {
module);
result = RestResourceConversionHelper.writeFileResponse(artifact,
requestResponseContextHolder.getHttpServletResponse(),
requestResponseContextHolder.getHttpServletRequest(), file, cacheWriteNotify, action.getId());
requestResponseContextHolder.getHttpServletRequest(), file, controllerManagement,
action.getId());
}
}
return result;
@@ -174,19 +176,19 @@ public class DdiRootController implements DdiRootControllerRestApi {
.getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(), module);
final String range = request.getHeader("Range");
final ActionStatus statusMessage = new ActionStatus();
final ActionStatus statusMessage = entityFactory.generateActionStatus();
statusMessage.setAction(action);
statusMessage.setOccurredAt(System.currentTimeMillis());
statusMessage.setStatus(Status.DOWNLOAD);
if (range != null) {
statusMessage.addMessage(ControllerManagement.SERVER_MESSAGE_PREFIX + "Target downloads range " + range
statusMessage.addMessage(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads range " + range
+ " of: " + request.getRequestURI());
} else {
statusMessage.addMessage(
ControllerManagement.SERVER_MESSAGE_PREFIX + "Target downloads " + request.getRequestURI());
RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads " + request.getRequestURI());
}
controllerManagement.addActionStatusMessage(statusMessage);
controllerManagement.addInformationalActionStatus(statusMessage);
return action;
}
@@ -247,8 +249,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
LOG.debug("Found an active UpdateAction for target {}. returning deyploment: {}", targetid, base);
controllerManagement.registerRetrieved(action,
ControllerManagement.SERVER_MESSAGE_PREFIX
controllerManagement.registerRetrieved(action, RepositoryConstants.SERVER_MESSAGE_PREFIX
+ "Target retrieved update action and should start now the download.");
return new ResponseEntity<>(base, HttpStatus.OK);
@@ -285,8 +286,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
return new ResponseEntity<>(HttpStatus.GONE);
}
controllerManagement.addUpdateActionStatus(
generateUpdateStatus(feedback, targetid, feedback.getId(), action), action);
controllerManagement.addUpdateActionStatus(generateUpdateStatus(feedback, targetid, feedback.getId(), action));
return new ResponseEntity<>(HttpStatus.OK);
@@ -295,7 +295,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
private ActionStatus generateUpdateStatus(final DdiActionFeedback feedback, final String targetid,
final Long actionid, final Action action) {
final ActionStatus actionStatus = new ActionStatus();
final ActionStatus actionStatus = entityFactory.generateActionStatus();
actionStatus.setAction(action);
actionStatus.setOccurredAt(System.currentTimeMillis());
@@ -304,13 +304,13 @@ public class DdiRootController implements DdiRootControllerRestApi {
LOG.debug("Controller confirmed cancel (actionid: {}, targetid: {}) as we got {} report.", actionid,
targetid, feedback.getStatus().getExecution());
actionStatus.setStatus(Status.CANCELED);
actionStatus.addMessage(ControllerManagement.SERVER_MESSAGE_PREFIX + "Target confirmed cancelation.");
actionStatus.addMessage(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target confirmed cancelation.");
break;
case REJECTED:
LOG.info("Controller reported internal error (actionid: {}, targetid: {}) as we got {} report.", actionid,
targetid, feedback.getStatus().getExecution());
actionStatus.setStatus(Status.WARNING);
actionStatus.addMessage(ControllerManagement.SERVER_MESSAGE_PREFIX + "Target REJECTED update.");
actionStatus.addMessage(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target REJECTED update.");
break;
case CLOSED:
handleClosedUpdateStatus(feedback, targetid, actionid, actionStatus);
@@ -338,7 +338,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
targetid, feedback.getStatus().getExecution());
actionStatus.setStatus(Status.RUNNING);
actionStatus.addMessage(
ControllerManagement.SERVER_MESSAGE_PREFIX + "Target reported " + feedback.getStatus().getExecution());
RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target reported " + feedback.getStatus().getExecution());
}
private static void handleClosedUpdateStatus(final DdiActionFeedback feedback, final String targetid,
@@ -347,10 +347,10 @@ public class DdiRootController implements DdiRootControllerRestApi {
feedback.getStatus().getExecution());
if (feedback.getStatus().getResult().getFinished() == FinalResult.FAILURE) {
actionStatus.setStatus(Status.ERROR);
actionStatus.addMessage(ControllerManagement.SERVER_MESSAGE_PREFIX + "Target reported CLOSED with ERROR!");
actionStatus.addMessage(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target reported CLOSED with ERROR!");
} else {
actionStatus.setStatus(Status.FINISHED);
actionStatus.addMessage(ControllerManagement.SERVER_MESSAGE_PREFIX + "Target reported CLOSED with OK!");
actionStatus.addMessage(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target reported CLOSED with OK!");
}
}
@@ -388,7 +388,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
LOG.debug("Found an active CancelAction for target {}. returning cancel: {}", targetid, cancel);
controllerManagement.registerRetrieved(action, ControllerManagement.SERVER_MESSAGE_PREFIX
controllerManagement.registerRetrieved(action, RepositoryConstants.SERVER_MESSAGE_PREFIX
+ "Target retrieved cancel action and should start now the cancelation.");
return new ResponseEntity<>(cancel, HttpStatus.OK);
@@ -420,15 +420,15 @@ public class DdiRootController implements DdiRootControllerRestApi {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
controllerManagement
.addCancelActionStatus(generateActionCancelStatus(feedback, target, feedback.getId(), action), action);
controllerManagement.addCancelActionStatus(
generateActionCancelStatus(feedback, target, feedback.getId(), action, entityFactory));
return new ResponseEntity<>(HttpStatus.OK);
}
private static ActionStatus generateActionCancelStatus(final DdiActionFeedback feedback, final Target target,
final Long actionid, final Action action) {
final Long actionid, final Action action, final EntityFactory entityFactory) {
final ActionStatus actionStatus = new ActionStatus();
final ActionStatus actionStatus = entityFactory.generateActionStatus();
actionStatus.setAction(action);
actionStatus.setOccurredAt(System.currentTimeMillis());

View File

@@ -26,8 +26,6 @@ import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.RandomUtils;
import org.eclipse.hawkbit.TestDataUtil;
import org.eclipse.hawkbit.WithUser;
import org.eclipse.hawkbit.eventbus.event.DownloadProgressEvent;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status;
@@ -35,6 +33,7 @@ import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.LocalArtifact;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.util.WithUser;
import org.eclipse.hawkbit.rest.AbstractRestIntegrationTestWithMongoDB;
import org.junit.Test;
import org.slf4j.LoggerFactory;
@@ -73,14 +72,13 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTestWithMong
@Description("Tests non allowed requests on the artifact ressource, e.g. invalid URI, wrong if-match, wrong command.")
public void invalidRequestsOnArtifactResource() throws Exception {
// create target
Target target = new Target("4712");
Target target = entityFactory.generateTarget("4712");
target = targetManagement.createTarget(target);
final List<Target> targets = new ArrayList<>();
targets.add(target);
// create ds
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet ds = testdataFactory.createDistributionSet("");
deploymentManagement.assignDistributionSet(ds, targets);
// create artifact
@@ -158,14 +156,13 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTestWithMong
@Description("Tests non allowed requests on the artifact ressource, e.g. invalid URI, wrong if-match, wrong command.")
public void invalidRequestsOnArtifactResourceByName() throws Exception {
// create target
Target target = new Target("4712");
Target target = entityFactory.generateTarget("4712");
target = targetManagement.createTarget(target);
final List<Target> targets = new ArrayList<>();
targets.add(target);
// create ds
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet ds = testdataFactory.createDistributionSet("");
deploymentManagement.assignDistributionSet(ds, targets);
// create artifact
@@ -241,17 +238,15 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTestWithMong
downLoadProgress = 1;
eventBus.register(this);
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
assertThat(artifactRepository.findAll()).hasSize(0);
// create target
Target target = new Target("4712");
Target target = entityFactory.generateTarget("4712");
target = targetManagement.createTarget(target);
final List<Target> targets = new ArrayList<Target>();
targets.add(target);
// create ds
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet ds = testdataFactory.createDistributionSet("");
// create artifact
final byte random[] = RandomUtils.nextBytes(5 * 1024 * 1024);
@@ -287,12 +282,11 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTestWithMong
@Description("Tests valid MD5SUm file downloads through the artifact resource by identifying the artifact by ID.")
public void downloadMd5sumThroughControllerApi() throws Exception {
// create target
Target target = new Target("4712");
Target target = entityFactory.generateTarget("4712");
target = targetManagement.createTarget(target);
// create ds
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet ds = testdataFactory.createDistributionSet("");
// create artifact
final byte random[] = RandomUtils.nextBytes(5 * 1024);
@@ -322,17 +316,15 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTestWithMong
eventBus.register(this);
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
assertThat(artifactRepository.findAll()).hasSize(0);
// create target
Target target = new Target("4712");
Target target = entityFactory.generateTarget("4712");
target = targetManagement.createTarget(target);
final List<Target> targets = new ArrayList();
targets.add(target);
// create ds
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet ds = testdataFactory.createDistributionSet("");
// create artifact
final byte random[] = RandomUtils.nextBytes(5 * 1024);
@@ -353,17 +345,15 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTestWithMong
eventBus.register(this);
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
assertThat(artifactRepository.findAll()).hasSize(0);
// create target
Target target = new Target("4712");
Target target = entityFactory.generateTarget("4712");
target = targetManagement.createTarget(target);
final List<Target> targets = new ArrayList<>();
targets.add(target);
// create ds
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet ds = testdataFactory.createDistributionSet("");
// create artifact
final byte random[] = RandomUtils.nextBytes(5 * 1024 * 1024);
@@ -389,13 +379,12 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTestWithMong
Arrays.equals(result.getResponse().getContentAsByteArray(), random));
// one (update) action
assertThat(actionRepository.findByTargetAndDistributionSet(pageReq, target, ds).getContent()).hasSize(1);
final Action action = actionRepository.findByTargetAndDistributionSet(pageReq, target, ds).getContent().get(0);
assertThat(deploymentManagement.findActionsByTarget(target)).hasSize(1);
final Action action = deploymentManagement.findActionsByTarget(target).get(0);
// one status - download
assertThat(actionStatusRepository.findAll()).hasSize(2);
assertThat(actionStatusRepository.findByAction(pageReq, action).getContent()).hasSize(2);
assertThat(actionStatusRepository.findByAction(new PageRequest(0, 400, Direction.DESC, "id"), action)
assertThat(action.getActionStatus()).hasSize(2);
assertThat(deploymentManagement.findActionStatusByAction(new PageRequest(0, 400, Direction.DESC, "id"), action)
.getContent().get(0).getStatus()).isEqualTo(Status.DOWNLOAD);
// download complete
@@ -407,14 +396,13 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTestWithMong
@Description("Test various HTTP range requests for artifact download, e.g. chunk download or download resume.")
public void rangeDownloadArtifactByName() throws Exception {
// create target
Target target = new Target("4712");
Target target = entityFactory.generateTarget("4712");
target = targetManagement.createTarget(target);
final List<Target> targets = new ArrayList<>();
targets.add(target);
// create ds
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet ds = testdataFactory.createDistributionSet("");
final int resultLength = 5 * 1000 * 1024;
@@ -512,17 +500,15 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTestWithMong
@Description("Ensures that the download fails if te controller is not authenticated.")
public void faildDownloadArtifactByNameIfAuthenticationMissing() throws Exception {
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
assertThat(artifactRepository.findAll()).hasSize(0);
// create target
Target target = new Target("4712");
Target target = entityFactory.generateTarget("4712");
target = targetManagement.createTarget(target);
final List<Target> targets = new ArrayList<>();
targets.add(target);
// create ds
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet ds = testdataFactory.createDistributionSet("");
// create artifact
final byte random[] = RandomUtils.nextBytes(5 * 1024);
@@ -538,12 +524,11 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTestWithMong
@Description("Downloads an MD5SUM file by the related artifacts filename.")
public void downloadMd5sumFileByName() throws Exception {
// create target
Target target = new Target("4712");
Target target = entityFactory.generateTarget("4712");
target = targetManagement.createTarget(target);
// create ds
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet ds = testdataFactory.createDistributionSet("");
// create artifact
final byte random[] = RandomUtils.nextBytes(5 * 1024);

View File

@@ -22,7 +22,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import java.util.ArrayList;
import java.util.List;
import org.eclipse.hawkbit.TestDataUtil;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.DistributionSet;
@@ -49,9 +48,8 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
@Description("Test of the controller can continue a started update even after a cancel command if it so desires.")
public void rootRsCancelActionButContinueAnyway() throws Exception {
// prepare test data
final Target target = new Target("4712");
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final Target target = entityFactory.generateTarget("4712");
final DistributionSet ds = testdataFactory.createDistributionSet("");
final Target savedTarget = targetManagement.createTarget(target);
final List<Target> toAssign = new ArrayList<Target>();
@@ -106,9 +104,8 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
@Test
@Description("Test for cancel operation of a update action.")
public void rootRsCancelAction() throws Exception {
final Target target = new Target("4712");
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final Target target = entityFactory.generateTarget("4712");
final DistributionSet ds = testdataFactory.createDistributionSet("");
final Target savedTarget = targetManagement.createTarget(target);
final List<Target> toAssign = new ArrayList<Target>();
@@ -224,9 +221,8 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
}
private Action createCancelAction(final String targetid) {
final Target target = new Target(targetid);
final DistributionSet ds = TestDataUtil.generateDistributionSet(targetid, softwareManagement,
distributionSetManagement);
final Target target = entityFactory.generateTarget(targetid);
final DistributionSet ds = testdataFactory.createDistributionSet(targetid);
final Target savedTarget = targetManagement.createTarget(target);
final List<Target> toAssign = new ArrayList<Target>();
toAssign.add(savedTarget);
@@ -241,9 +237,8 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
@Description("Tests the feedback channel of the cancel operation.")
public void rootRsCancelActionFeedback() throws Exception {
final Target target = new Target("4712");
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final Target target = entityFactory.generateTarget("4712");
final DistributionSet ds = testdataFactory.createDistributionSet("");
final Target savedTarget = targetManagement.createTarget(target);
@@ -253,7 +248,7 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
// cancel action manually
final Action cancelAction = deploymentManagement.cancelAction(updateAction,
targetManagement.findTargetByControllerID(savedTarget.getControllerId()));
assertThat(actionStatusRepository.findAll()).hasSize(2);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
long current = System.currentTimeMillis();
@@ -266,7 +261,7 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
.isGreaterThanOrEqualTo(current);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
assertThat(actionStatusRepository.findAll()).hasSize(3);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(3);
current = System.currentTimeMillis();
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
@@ -277,7 +272,7 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
assertThat(actionStatusRepository.findAll()).hasSize(4);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(4);
current = System.currentTimeMillis();
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
@@ -287,7 +282,7 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current);
assertThat(actionStatusRepository.findAll()).hasSize(5);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(5);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
// cancelation canceled -> should remove the action from active
@@ -300,7 +295,7 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current);
assertThat(actionStatusRepository.findAll()).hasSize(6);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(6);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
// cancelation rejected -> action still active until controller close it
@@ -315,7 +310,7 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current);
assertThat(actionStatusRepository.findAll()).hasSize(7);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(7);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
// cancelaction closed -> should remove the action from active
@@ -327,20 +322,17 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current);
assertThat(actionStatusRepository.findAll()).hasSize(8);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(8);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(0);
}
@Test
@Description("Tests the feeback chanel of for multiple open cancel operations on the same target.")
public void multipleCancelActionFeedback() throws Exception {
final Target target = new Target("4712");
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement, true);
final DistributionSet ds2 = TestDataUtil.generateDistributionSet("2", softwareManagement,
distributionSetManagement, true);
final DistributionSet ds3 = TestDataUtil.generateDistributionSet("3", softwareManagement,
distributionSetManagement, true);
final Target target = entityFactory.generateTarget("4712");
final DistributionSet ds = testdataFactory.createDistributionSet("", true);
final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true);
final DistributionSet ds3 = testdataFactory.createDistributionSet("3", true);
final Target savedTarget = targetManagement.createTarget(target);
@@ -351,7 +343,7 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
final Action updateAction3 = deploymentManagement.findActionWithDetails(
deploymentManagement.assignDistributionSet(ds3.getId(), new String[] { "4712" }).getActions().get(0));
assertThat(actionStatusRepository.findAll()).hasSize(3);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(3);
// 3 update actions, 0 cancel actions
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(3);
@@ -370,7 +362,7 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$id", equalTo(String.valueOf(cancelAction.getId()))))
.andExpect(jsonPath("$cancelAction.stopId", equalTo(String.valueOf(updateAction.getId()))));
assertThat(actionStatusRepository.findAll()).hasSize(6);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(6);
mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
@@ -386,7 +378,7 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(actionStatusRepository.findAll()).hasSize(7);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(7);
// 1 update actions, 1 cancel actions
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2);
@@ -396,7 +388,7 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$id", equalTo(String.valueOf(cancelAction2.getId()))))
.andExpect(jsonPath("$cancelAction.stopId", equalTo(String.valueOf(updateAction2.getId()))));
assertThat(actionStatusRepository.findAll()).hasSize(8);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(8);
mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
@@ -412,17 +404,18 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
.content(JsonBuilder.cancelActionFeedback(cancelAction2.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(actionStatusRepository.findAll()).hasSize(9);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(9);
assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet()).isEqualTo(ds3);
mvc.perform(get("/{tenant}/controller/v1/4712/deploymentBase/" + updateAction3.getId(),
tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(actionStatusRepository.findAll()).hasSize(10);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(10);
// 1 update actions, 0 cancel actions
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
final Action cancelAction3 = deploymentManagement.cancelAction(actionRepository.findOne(updateAction3.getId()),
final Action cancelAction3 = deploymentManagement.cancelAction(
deploymentManagement.findAction(updateAction3.getId()),
targetManagement.findTargetByControllerID(savedTarget.getControllerId()));
// action is in cancelling state
@@ -435,7 +428,7 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$id", equalTo(String.valueOf(cancelAction3.getId()))))
.andExpect(jsonPath("$cancelAction.stopId", equalTo(String.valueOf(updateAction3.getId()))));
assertThat(actionStatusRepository.findAll()).hasSize(12);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(12);
// now lets return feedback for the third cancelation
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction3.getId() + "/feedback",
@@ -443,7 +436,7 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
.content(JsonBuilder.cancelActionFeedback(cancelAction3.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(actionStatusRepository.findAll()).hasSize(13);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(13);
// final status
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(0);
@@ -453,9 +446,8 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
@Test
@Description("Tests the feeback channel closing for too many feedbacks, i.e. denial of service prevention.")
public void tooMuchCancelActionFeedback() throws Exception {
final Target target = targetManagement.createTarget(new Target("4712"));
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final Target target = targetManagement.createTarget(entityFactory.generateTarget("4712"));
final DistributionSet ds = testdataFactory.createDistributionSet("");
final List<Target> toAssign = new ArrayList<Target>();
toAssign.add(target);

View File

@@ -21,8 +21,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import java.util.HashMap;
import java.util.Map;
import org.eclipse.hawkbit.AbstractIntegrationTest;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.junit.Test;
@@ -40,13 +40,13 @@ import ru.yandex.qatools.allure.annotations.Stories;
@ActiveProfiles({ "im", "test" })
@Features("Component Tests - Direct Device Integration API")
@Stories("Config Data Resource")
public class DdiConfigDataTest extends AbstractIntegrationTest {
public class DdiConfigDataTest extends AbstractRestIntegrationTest {
@Test
@Description("We verify that the config data (i.e. device attributes like serial number, hardware revision etc.) "
+ "are requested only once from the device.")
public void requestConfigDataIfEmpty() throws Exception {
final Target target = new Target("4712");
final Target target = entityFactory.generateTarget("4712");
final Target savedTarget = targetManagement.createTarget(target);
final long current = System.currentTimeMillis();
@@ -84,7 +84,7 @@ public class DdiConfigDataTest extends AbstractIntegrationTest {
@Description("We verify that the config data (i.e. device attributes like serial number, hardware revision etc.) "
+ "can be uploaded correctly by the controller.")
public void putConfigData() throws Exception {
targetManagement.createTarget(new Target("4717"));
targetManagement.createTarget(entityFactory.generateTarget("4717"));
// initial
final Map<String, String> attributes = new HashMap<>();
@@ -127,7 +127,7 @@ public class DdiConfigDataTest extends AbstractIntegrationTest {
@Description("We verify that the config data (i.e. device attributes like serial number, hardware revision etc.) "
+ "upload limitation is inplace which is meant to protect the server from malicious attempts.")
public void putToMuchConfigData() throws Exception {
targetManagement.createTarget(new Target("4717"));
targetManagement.createTarget(entityFactory.generateTarget("4717"));
// initial
Map<String, String> attributes = new HashMap<>();
@@ -150,7 +150,7 @@ public class DdiConfigDataTest extends AbstractIntegrationTest {
@Description("We verify that the config data (i.e. device attributes like serial number, hardware revision etc.) "
+ "resource behaves as exptected in cae of invalid request attempts.")
public void badConfigData() throws Exception {
final Target target = new Target("4712");
final Target target = entityFactory.generateTarget("4712");
final Target savedTarget = targetManagement.createTarget(target);
// not allowed methods

View File

@@ -25,11 +25,11 @@ import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.RandomUtils;
import org.eclipse.hawkbit.TestDataUtil;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.ActionType;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.ActionStatus;
import org.eclipse.hawkbit.repository.model.RepositoryModelConstants;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.LocalArtifact;
import org.eclipse.hawkbit.repository.model.Target;
@@ -40,8 +40,6 @@ import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.fest.assertions.core.Condition;
import org.junit.Test;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.hateoas.MediaTypes;
import org.springframework.http.MediaType;
@@ -63,7 +61,7 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
@Test()
@Description("Ensures that artifacts are not found, when softare module does not exists.")
public void artifactsNotFound() throws Exception {
final Target target = TestDataUtil.createTarget(targetManagement);
final Target target = testdataFactory.createTarget();
final Long softwareModuleIdNotExist = 1l;
mvc.perform(get("/{tenant}/controller/v1/{targetNotExist}/softwaremodules/{softwareModuleId}/artifacts",
tenantAware.getCurrentTenant(), target.getName(), softwareModuleIdNotExist))
@@ -73,9 +71,8 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
@Test()
@Description("Ensures that artifacts are found, when software module exists.")
public void artifactsExists() throws Exception {
final Target target = TestDataUtil.createTarget(targetManagement);
final DistributionSet distributionSet = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final Target target = testdataFactory.createTarget();
final DistributionSet distributionSet = testdataFactory.createDistributionSet("");
deploymentManagement.assignDistributionSet(distributionSet.getId(), new String[] { target.getName() });
@@ -84,7 +81,7 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
tenantAware.getCurrentTenant(), target.getName(), softwareModuleId)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()).andExpect(jsonPath("$", hasSize(0)));
TestDataUtil.generateArtifacts(artifactManagement, softwareModuleId);
testdataFactory.createLocalArtifacts(softwareModuleId);
mvc.perform(get("/{tenant}/controller/v1/{targetNotExist}/softwaremodules/{softwareModuleId}/artifacts",
tenantAware.getCurrentTenant(), target.getName(), softwareModuleId)).andDo(MockMvcResultPrinter.print())
@@ -99,11 +96,9 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
@Description("Forced deployment to a controller. Checks if the resource reponse payload for a given deployment is as expected.")
public void deplomentForceAction() throws Exception {
// Prepare test data
final Target target = new Target("4712");
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement, true);
final DistributionSet ds2 = TestDataUtil.generateDistributionSet("2", softwareManagement,
distributionSetManagement, true);
final Target target = entityFactory.generateTarget("4712");
final DistributionSet ds = testdataFactory.createDistributionSet("", true);
final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true);
final byte random[] = RandomUtils.nextBytes(5 * 1024);
final LocalArtifact artifact = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random),
@@ -114,18 +109,18 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
final Target savedTarget = targetManagement.createTarget(target);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).isEmpty();
assertThat(actionRepository.findAll()).isEmpty();
assertThat(actionStatusRepository.findAll()).isEmpty();
assertThat(deploymentManagement.countActionsAll()).isEqualTo(0);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(0);
List<Target> saved = deploymentManagement.assignDistributionSet(ds.getId(), ActionType.FORCED,
Action.NO_FORCE_TIME, savedTarget.getControllerId()).getAssignedEntity();
RepositoryModelConstants.NO_FORCE_TIME, savedTarget.getControllerId()).getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
final Action action = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0);
assertThat(actionRepository.findAll()).hasSize(1);
assertThat(deploymentManagement.countActionsAll()).isEqualTo(1);
saved = deploymentManagement.assignDistributionSet(ds2, saved).getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2);
assertThat(actionRepository.findAll()).hasSize(2);
assertThat(deploymentManagement.countActionsAll()).isEqualTo(2);
final Action uaction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0);
assertThat(uaction.getDistributionSet()).isEqualTo(ds);
@@ -143,7 +138,7 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
.isGreaterThanOrEqualTo(current);
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
.isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(actionStatusRepository.findAll()).hasSize(2);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2);
current = System.currentTimeMillis();
@@ -227,9 +222,9 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
.isGreaterThanOrEqualTo(current);
// Retrieved is reported
final Iterable<ActionStatus> actionStatusMessages = actionStatusRepository
.findAll(new PageRequest(0, 100, Direction.DESC, "id"));
assertThat(actionStatusMessages).hasSize(3);
final Iterable<ActionStatus> actionStatusMessages = deploymentManagement
.findActionStatusByAction(new PageRequest(0, 100, Direction.DESC, "id"), uaction);
assertThat(actionStatusMessages).hasSize(2);
final ActionStatus actionStatusMessage = actionStatusMessages.iterator().next();
assertThat(actionStatusMessage.getStatus()).isEqualTo(Status.RETRIEVED);
}
@@ -238,11 +233,9 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
@Description("Attempt/soft deployment to a controller. Checks if the resource reponse payload for a given deployment is as expected.")
public void deplomentAttemptAction() throws Exception {
// Prepare test data
final Target target = new Target("4712");
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement, true);
final DistributionSet ds2 = TestDataUtil.generateDistributionSet("2", softwareManagement,
distributionSetManagement, true);
final Target target = entityFactory.generateTarget("4712");
final DistributionSet ds = testdataFactory.createDistributionSet("", true);
final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true);
final byte random[] = RandomUtils.nextBytes(5 * 1024);
final LocalArtifact artifact = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random),
@@ -253,19 +246,18 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
final Target savedTarget = targetManagement.createTarget(target);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).isEmpty();
assertThat(actionRepository.findAll()).isEmpty();
assertThat(actionStatusRepository.findAll()).isEmpty();
assertThat(deploymentManagement.countActionsAll()).isEqualTo(0);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(0);
List<Target> saved = deploymentManagement
.assignDistributionSet(ds.getId(), ActionType.SOFT, Action.NO_FORCE_TIME, savedTarget.getControllerId())
.getAssignedEntity();
List<Target> saved = deploymentManagement.assignDistributionSet(ds.getId(), ActionType.SOFT,
RepositoryModelConstants.NO_FORCE_TIME, savedTarget.getControllerId()).getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
final Action action = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0);
assertThat(actionRepository.findAll()).hasSize(1);
assertThat(deploymentManagement.countActionsAll()).isEqualTo(1);
saved = deploymentManagement.assignDistributionSet(ds2, saved).getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2);
assertThat(actionRepository.findAll()).hasSize(2);
assertThat(deploymentManagement.countActionsAll()).isEqualTo(2);
final Action uaction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0);
assertThat(uaction.getDistributionSet()).isEqualTo(ds);
@@ -284,7 +276,7 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
.isGreaterThanOrEqualTo(current);
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
.isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(actionStatusRepository.findAll()).hasSize(2);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2);
current = System.currentTimeMillis();
@@ -358,9 +350,9 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
.isGreaterThanOrEqualTo(current);
// Retrieved is reported
final Iterable<ActionStatus> actionStatusMessages = actionStatusRepository
.findAll(new PageRequest(0, 100, Direction.DESC, "id"));
assertThat(actionStatusMessages).hasSize(3);
final List<ActionStatus> actionStatusMessages = deploymentManagement
.findActionStatusByAction(new PageRequest(0, 100, Direction.DESC, "id"), uaction).getContent();
assertThat(actionStatusMessages).hasSize(2);
final ActionStatus actionStatusMessage = actionStatusMessages.iterator().next();
assertThat(actionStatusMessage.getStatus()).isEqualTo(Status.RETRIEVED);
}
@@ -369,11 +361,9 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
@Description("Attempt/soft deployment to a controller including automated switch to hard. Checks if the resource reponse payload for a given deployment is as expected.")
public void deplomentAutoForceAction() throws Exception {
// Prepare test data
final Target target = new Target("4712");
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement, true);
final DistributionSet ds2 = TestDataUtil.generateDistributionSet("2", softwareManagement,
distributionSetManagement, true);
final Target target = entityFactory.generateTarget("4712");
final DistributionSet ds = testdataFactory.createDistributionSet("", true);
final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true);
final byte random[] = RandomUtils.nextBytes(5 * 1024);
final LocalArtifact artifact = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random),
@@ -384,18 +374,18 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
final Target savedTarget = targetManagement.createTarget(target);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).isEmpty();
assertThat(actionRepository.findAll()).isEmpty();
assertThat(actionStatusRepository.findAll()).isEmpty();
assertThat(deploymentManagement.countActionsAll()).isEqualTo(0);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(0);
List<Target> saved = deploymentManagement.assignDistributionSet(ds.getId(), ActionType.TIMEFORCED,
System.currentTimeMillis(), savedTarget.getControllerId()).getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
final Action action = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0);
assertThat(actionRepository.findAll()).hasSize(1);
assertThat(deploymentManagement.countActionsAll()).isEqualTo(1);
saved = deploymentManagement.assignDistributionSet(ds2, saved).getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2);
assertThat(actionRepository.findAll()).hasSize(2);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2);
final Action uaction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0);
assertThat(uaction.getDistributionSet()).isEqualTo(ds);
@@ -414,7 +404,7 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
.isGreaterThanOrEqualTo(current);
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
.isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(actionStatusRepository.findAll()).hasSize(2);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2);
current = System.currentTimeMillis();
@@ -496,9 +486,9 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
.isGreaterThanOrEqualTo(current);
// Retrieved is reported
final Iterable<ActionStatus> actionStatusMessages = actionStatusRepository
.findAll(new PageRequest(0, 100, Direction.DESC, "id"));
assertThat(actionStatusMessages).hasSize(3);
final Iterable<ActionStatus> actionStatusMessages = deploymentManagement
.findActionStatusByAction(new PageRequest(0, 100, Direction.DESC, "id"), uaction).getContent();
assertThat(actionStatusMessages).hasSize(2);
final ActionStatus actionStatusMessage = actionStatusMessages.iterator().next();
assertThat(actionStatusMessage.getStatus()).isEqualTo(Status.RETRIEVED);
}
@@ -506,7 +496,7 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
@Test
@Description("Test various invalid access attempts to the deployment resource und the expected behaviour of the server.")
public void badDeploymentAction() throws Exception {
final Target target = targetManagement.createTarget(new Target("4712"));
final Target target = targetManagement.createTarget(entityFactory.generateTarget("4712"));
// not allowed methods
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/1", tenantAware.getCurrentTenant()))
@@ -527,10 +517,9 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
// wrong media type
final List<Target> toAssign = new ArrayList<Target>();
final List<Target> toAssign = new ArrayList<>();
toAssign.add(target);
final DistributionSet savedSet = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet savedSet = testdataFactory.createDistributionSet("");
final Action action1 = deploymentManagement.findActionWithDetails(
deploymentManagement.assignDistributionSet(savedSet, toAssign).getActions().get(0));
@@ -547,16 +536,14 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
@Description("The server protects itself against to many feedback upload attempts. The test verfies that "
+ "it is not possible to exceed the configured maximum number of feedback uplods.")
public void toMuchDeplomentActionFeedback() throws Exception {
final Target target = targetManagement.createTarget(new Target("4712"));
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final Target target = targetManagement.createTarget(entityFactory.generateTarget("4712"));
final DistributionSet ds = testdataFactory.createDistributionSet("");
final List<Target> toAssign = new ArrayList<Target>();
final List<Target> toAssign = new ArrayList<>();
toAssign.add(target);
deploymentManagement.assignDistributionSet(ds.getId(), new String[] { "4712" });
final Pageable pageReq = new PageRequest(0, 100);
final Action action = actionRepository.findByDistributionSet(pageReq, ds).getContent().get(0);
final Action action = deploymentManagement.findActionsByTarget(target).get(0);
final String feedback = JsonBuilder.deploymentActionFeedback(action.getId().toString(), "proceeding");
// assign distribution set creates an action status, so only 99 left
@@ -576,21 +563,18 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
@Test
@Description("Multiple uploads of deployment status feedback to the server.")
public void multipleDeplomentActionFeedback() throws Exception {
final Target target1 = new Target("4712");
final Target target2 = new Target("4713");
final Target target3 = new Target("4714");
final Target target1 = entityFactory.generateTarget("4712");
final Target target2 = entityFactory.generateTarget("4713");
final Target target3 = entityFactory.generateTarget("4714");
final Target savedTarget1 = targetManagement.createTarget(target1);
targetManagement.createTarget(target2);
targetManagement.createTarget(target3);
final DistributionSet ds1 = TestDataUtil.generateDistributionSet("1", softwareManagement,
distributionSetManagement, true);
final DistributionSet ds2 = TestDataUtil.generateDistributionSet("2", softwareManagement,
distributionSetManagement, true);
final DistributionSet ds3 = TestDataUtil.generateDistributionSet("3", softwareManagement,
distributionSetManagement, true);
final DistributionSet ds1 = testdataFactory.createDistributionSet("1", true);
final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true);
final DistributionSet ds3 = testdataFactory.createDistributionSet("3", true);
final List<Target> toAssign = new ArrayList<Target>();
final List<Target> toAssign = new ArrayList<>();
toAssign.add(savedTarget1);
final Action action1 = deploymentManagement.findActionWithDetails(
@@ -630,7 +614,8 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
assertThat(myT.getTargetInfo().getInstalledDistributionSet().getId()).isEqualTo(ds1.getId());
assertThat(myT.getAssignedDistributionSet()).isEqualTo(ds3);
Iterable<ActionStatus> actionStatusMessages = actionStatusRepository.findAll(new Sort(Direction.DESC, "id"));
Iterable<ActionStatus> actionStatusMessages = deploymentManagement
.findActionStatusAll(new PageRequest(0, 100, Direction.DESC, "id")).getContent();
assertThat(actionStatusMessages).hasSize(4);
assertThat(actionStatusMessages.iterator().next().getStatus()).isEqualTo(Status.FINISHED);
@@ -650,7 +635,8 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
assertThat(deploymentManagement.findActiveActionsByTarget(myT)).hasSize(1);
assertThat(myT.getTargetInfo().getInstalledDistributionSet().getId()).isEqualTo(ds2.getId());
assertThat(myT.getAssignedDistributionSet()).isEqualTo(ds3);
actionStatusMessages = actionStatusRepository.findAll(new PageRequest(0, 100, Direction.DESC, "id"));
actionStatusMessages = deploymentManagement.findActionStatusAll(new PageRequest(0, 100, Direction.DESC, "id"))
.getContent();
assertThat(actionStatusMessages).hasSize(5);
assertThat(actionStatusMessages).haveAtLeast(1, new ActionStatusCondition(Status.FINISHED));
@@ -669,7 +655,8 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
assertThat(deploymentManagement.findActiveActionsByTarget(myT)).hasSize(0);
assertThat(myT.getTargetInfo().getInstalledDistributionSet()).isEqualTo(ds3);
assertThat(myT.getAssignedDistributionSet()).isEqualTo(ds3);
actionStatusMessages = actionStatusRepository.findAll();
actionStatusMessages = deploymentManagement.findActionStatusAll(new PageRequest(0, 100, Direction.DESC, "id"))
.getContent();
assertThat(actionStatusMessages).hasSize(6);
assertThat(actionStatusMessages).haveAtLeast(1, new ActionStatusCondition(Status.FINISHED));
@@ -678,18 +665,18 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
@Test
@Description("Verfies that an update action is correctly set to error if the controller provides error feedback.")
public void rootRsSingleDeplomentActionWithErrorFeedback() throws Exception {
final Target target = new Target("4712");
DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement, distributionSetManagement);
final Target target = entityFactory.generateTarget("4712");
DistributionSet ds = testdataFactory.createDistributionSet("");
final Target savedTarget = targetManagement.createTarget(target);
List<Target> toAssign = new ArrayList<Target>();
List<Target> toAssign = new ArrayList<>();
toAssign.add(savedTarget);
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.UNKNOWN);
deploymentManagement.assignDistributionSet(ds, toAssign);
final Action action = actionRepository.findByDistributionSet(pageReq, ds).getContent().get(0);
final Action action = deploymentManagement.findActionsByDistributionSet(pageReq, ds).getContent().get(0);
long current = System.currentTimeMillis();
long lastModified = targetManagement.findTargetByControllerID("4712").getLastModifiedAt();
@@ -712,7 +699,8 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
.hasSize(0);
assertThat(deploymentManagement.findActiveActionsByTarget(myT)).hasSize(0);
assertThat(deploymentManagement.findActionsByTarget(myT)).hasSize(1);
final Iterable<ActionStatus> actionStatusMessages = actionStatusRepository.findAll();
final Iterable<ActionStatus> actionStatusMessages = deploymentManagement
.findActionStatusAll(new PageRequest(0, 100, Direction.DESC, "id")).getContent();
assertThat(actionStatusMessages).hasSize(2);
assertThat(actionStatusMessages).haveAtLeast(1, new ActionStatusCondition(Status.ERROR));
@@ -743,10 +731,10 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
.hasSize(1);
assertThat(deploymentManagement.findActiveActionsByTarget(myT)).hasSize(0);
assertThat(deploymentManagement.findInActiveActionsByTarget(myT)).hasSize(2);
assertThat(actionStatusRepository.findAll()).hasSize(4);
assertThat(actionStatusRepository.findByAction(pageReq, action).getContent()).haveAtLeast(1,
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(4);
assertThat(deploymentManagement.findActionStatusByAction(pageReq, action).getContent()).haveAtLeast(1,
new ActionStatusCondition(Status.ERROR));
assertThat(actionStatusRepository.findByAction(pageReq, action2).getContent()).haveAtLeast(1,
assertThat(deploymentManagement.findActionStatusByAction(pageReq, action2).getContent()).haveAtLeast(1,
new ActionStatusCondition(Status.FINISHED));
}
@@ -754,27 +742,23 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
@Test
@Description("Verfies that the controller can provided as much feedback entries as necessry as long as it is in the configured limites.")
public void rootRsSingleDeplomentActionFeedback() throws Exception {
final Target target = new Target("4712");
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final Target target = entityFactory.generateTarget("4712");
final DistributionSet ds = testdataFactory.createDistributionSet("");
final Target savedTarget = targetManagement.createTarget(target);
final List<Target> toAssign = new ArrayList<Target>();
final List<Target> toAssign = new ArrayList<>();
toAssign.add(savedTarget);
Target myT = targetManagement.findTargetByControllerID("4712");
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.UNKNOWN);
deploymentManagement.assignDistributionSet(ds, toAssign);
final Action action = actionRepository.findByDistributionSet(pageReq, ds).getContent().get(0);
final Action action = deploymentManagement.findActionsByDistributionSet(pageReq, ds).getContent().get(0);
myT = targetManagement.findTargetByControllerID("4712");
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(targetRepository.findByTargetInfoInstalledDistributionSet(new PageRequest(0, 10), ds)).hasSize(0);
assertThat(targetRepository.findByAssignedDistributionSet(new PageRequest(0, 10), ds)).hasSize(1);
assertThat(targetRepository
.findByAssignedDistributionSetOrTargetInfoInstalledDistributionSet(new PageRequest(0, 10), ds, ds))
.hasSize(1);
assertThat(targetManagement.findTargetByInstalledDistributionSet(ds.getId(), pageReq)).hasSize(0);
assertThat(targetManagement.findTargetByAssignedDistributionSet(ds.getId(), pageReq)).hasSize(1);
// Now valid Feedback
@@ -798,8 +782,9 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC))
.hasSize(0);
assertThat(deploymentManagement.findActiveActionsByTarget(myT)).hasSize(1);
assertThat(actionStatusRepository.findAll()).hasSize(5);
assertThat(actionStatusRepository.findAll()).haveAtLeast(5, new ActionStatusCondition(Status.RUNNING));
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(5);
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(5,
new ActionStatusCondition(Status.RUNNING));
current = System.currentTimeMillis();
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
@@ -817,8 +802,9 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC))
.hasSize(0);
assertThat(deploymentManagement.findActiveActionsByTarget(myT)).hasSize(1);
assertThat(actionStatusRepository.findAll()).hasSize(6);
assertThat(actionStatusRepository.findAll()).haveAtLeast(5, new ActionStatusCondition(Status.RUNNING));
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(6);
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(5,
new ActionStatusCondition(Status.RUNNING));
current = System.currentTimeMillis();
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
@@ -836,8 +822,9 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC))
.hasSize(0);
assertThat(deploymentManagement.findActiveActionsByTarget(myT)).hasSize(1);
assertThat(actionStatusRepository.findAll()).hasSize(7);
assertThat(actionStatusRepository.findAll()).haveAtLeast(6, new ActionStatusCondition(Status.RUNNING));
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(7);
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(6,
new ActionStatusCondition(Status.RUNNING));
current = System.currentTimeMillis();
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
@@ -856,9 +843,11 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC))
.hasSize(0);
assertThat(actionStatusRepository.findAll()).hasSize(8);
assertThat(actionStatusRepository.findAll()).haveAtLeast(7, new ActionStatusCondition(Status.RUNNING));
assertThat(actionStatusRepository.findAll()).haveAtLeast(1, new ActionStatusCondition(Status.CANCELED));
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(8);
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(7,
new ActionStatusCondition(Status.RUNNING));
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(1,
new ActionStatusCondition(Status.CANCELED));
current = System.currentTimeMillis();
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
@@ -870,10 +859,13 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(deploymentManagement.findActiveActionsByTarget(myT)).hasSize(1);
assertThat(actionStatusRepository.findAll()).hasSize(9);
assertThat(actionStatusRepository.findAll()).haveAtLeast(6, new ActionStatusCondition(Status.RUNNING));
assertThat(actionStatusRepository.findAll()).haveAtLeast(1, new ActionStatusCondition(Status.WARNING));
assertThat(actionStatusRepository.findAll()).haveAtLeast(1, new ActionStatusCondition(Status.CANCELED));
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(9);
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(6,
new ActionStatusCondition(Status.RUNNING));
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(1,
new ActionStatusCondition(Status.WARNING));
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(1,
new ActionStatusCondition(Status.CANCELED));
current = System.currentTimeMillis();
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
@@ -890,28 +882,27 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoD
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC))
.hasSize(1);
assertThat(actionStatusRepository.findAll()).hasSize(10);
assertThat(actionStatusRepository.findAll()).haveAtLeast(7, new ActionStatusCondition(Status.RUNNING));
assertThat(actionStatusRepository.findAll()).haveAtLeast(1, new ActionStatusCondition(Status.WARNING));
assertThat(actionStatusRepository.findAll()).haveAtLeast(1, new ActionStatusCondition(Status.CANCELED));
assertThat(actionStatusRepository.findAll()).haveAtLeast(1, new ActionStatusCondition(Status.FINISHED));
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(10);
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(7,
new ActionStatusCondition(Status.RUNNING));
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(1,
new ActionStatusCondition(Status.WARNING));
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(1,
new ActionStatusCondition(Status.CANCELED));
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(1,
new ActionStatusCondition(Status.FINISHED));
assertThat(targetRepository.findByTargetInfoInstalledDistributionSet(new PageRequest(0, 10), ds)).hasSize(1);
assertThat(targetRepository.findByAssignedDistributionSet(new PageRequest(0, 10), ds)).hasSize(1);
assertThat(targetRepository
.findByAssignedDistributionSetOrTargetInfoInstalledDistributionSet(new PageRequest(0, 10), ds, ds))
.hasSize(1);
assertThat(targetManagement.findTargetByInstalledDistributionSet(ds.getId(), pageReq)).hasSize(1);
assertThat(targetManagement.findTargetByAssignedDistributionSet(ds.getId(), pageReq)).hasSize(1);
}
@Test
@Description("Various forbidden request appempts on the feedback resource. Ensures correct answering behaviour as expected to these kind of errors.")
public void badDeplomentActionFeedback() throws Exception {
final Target target = new Target("4712");
final Target target2 = new Target("4713");
final DistributionSet savedSet = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet savedSet2 = TestDataUtil.generateDistributionSet("1", softwareManagement,
distributionSetManagement);
final Target target = entityFactory.generateTarget("4712");
final Target target2 = entityFactory.generateTarget("4713");
final DistributionSet savedSet = testdataFactory.createDistributionSet("");
final DistributionSet savedSet2 = testdataFactory.createDistributionSet("1");
// target does not exist
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/1234/feedback", tenantAware.getCurrentTenant())

View File

@@ -22,15 +22,14 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import java.util.ArrayList;
import java.util.List;
import org.eclipse.hawkbit.TestDataUtil;
import org.eclipse.hawkbit.WithSpringAuthorityRule;
import org.eclipse.hawkbit.WithUser;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.repository.util.WithSpringAuthorityRule;
import org.eclipse.hawkbit.repository.util.WithUser;
import org.eclipse.hawkbit.rest.AbstractRestIntegrationTestWithMongoDB;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
@@ -80,7 +79,7 @@ public class DdiRootControllerTest extends AbstractRestIntegrationTestWithMongoD
// create target first with "knownPrincipal" user and audit data
final String knownTargetControllerId = "target1";
final String knownCreatedBy = "knownPrincipal";
targetManagement.createTarget(new Target(knownTargetControllerId));
targetManagement.createTarget(entityFactory.generateTarget(knownTargetControllerId));
final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownTargetControllerId);
assertThat(findTargetByControllerID.getCreatedBy()).isEqualTo(knownCreatedBy);
assertThat(findTargetByControllerID.getCreatedAt()).isNotNull();
@@ -121,7 +120,7 @@ public class DdiRootControllerTest extends AbstractRestIntegrationTestWithMongoD
assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current);
assertThat(targetRepository.findByControllerId("4711").getTargetInfo().getUpdateStatus())
assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.REGISTERED);
// not allowed methods
@@ -169,9 +168,8 @@ public class DdiRootControllerTest extends AbstractRestIntegrationTestWithMongoD
mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant()).header("If-None-Match", etag))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotModified());
final Target target = targetRepository.findByControllerId("4711");
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final Target target = targetManagement.findTargetByControllerID("4711");
final DistributionSet ds = testdataFactory.createDistributionSet("");
deploymentManagement.assignDistributionSet(ds.getId(), new String[] { "4711" });
@@ -204,8 +202,7 @@ public class DdiRootControllerTest extends AbstractRestIntegrationTestWithMongoD
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotModified());
// Now another deployment
final DistributionSet ds2 = TestDataUtil.generateDistributionSet("2", softwareManagement,
distributionSetManagement);
final DistributionSet ds2 = testdataFactory.createDistributionSet("2");
deploymentManagement.assignDistributionSet(ds2.getId(), new String[] { "4711" });
@@ -226,10 +223,10 @@ public class DdiRootControllerTest extends AbstractRestIntegrationTestWithMongoD
@Description("Ensures that the target state machine of a precomissioned target switches from "
+ "UNKNOWN to REGISTERED when the target polls for the first time.")
public void rootRsPrecommissioned() throws Exception {
final Target target = new Target("4711");
final Target target = entityFactory.generateTarget("4711");
targetManagement.createTarget(target);
assertThat(targetRepository.findByControllerId("4711").getTargetInfo().getUpdateStatus())
assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.UNKNOWN);
final long current = System.currentTimeMillis();
@@ -242,7 +239,7 @@ public class DdiRootControllerTest extends AbstractRestIntegrationTestWithMongoD
assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current);
assertThat(targetRepository.findByControllerId("4711").getTargetInfo().getUpdateStatus())
assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.REGISTERED);
}
@@ -265,11 +262,10 @@ public class DdiRootControllerTest extends AbstractRestIntegrationTestWithMongoD
public void tryToFinishAnUpdateProcessAfterItHasBeenFinished() throws Exception {
// mock
final Target target = new Target("911");
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final Target target = entityFactory.generateTarget("911");
final DistributionSet ds = testdataFactory.createDistributionSet("");
Target savedTarget = targetManagement.createTarget(target);
final List<Target> toAssign = new ArrayList<Target>();
final List<Target> toAssign = new ArrayList<>();
toAssign.add(savedTarget);
savedTarget = deploymentManagement.assignDistributionSet(ds, toAssign).getAssignedEntity().iterator().next();
final Action savedAction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0);

View File

@@ -0,0 +1,162 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.ddi.rest.resource;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MvcResult;
import com.google.common.net.HttpHeaders;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
/**
* Test potential DOS attack scenarios and check if the filter prevents them.
*
*/
@ActiveProfiles({ "test" })
@Features("Component Tests - REST Security")
@Stories("Denial of Service protection filter")
public class DosFilterTest extends AbstractRestIntegrationTest {
@Test
@Description("Ensures that clients that are on the blacklist are forbidded ")
public void blackListedClientIsForbidden() throws Exception {
mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant())
.header(HttpHeaders.X_FORWARDED_FOR, "192.168.0.4 , 10.0.0.1 ")).andExpect(status().isForbidden());
}
@Test
@Description("Ensures that a READ DoS attempt is blocked ")
public void getFloddingAttackThatisPrevented() throws Exception {
MvcResult result = null;
int requests = 0;
do {
result = mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant())
.header(HttpHeaders.X_FORWARDED_FOR, "10.0.0.1")).andReturn();
requests++;
// we give up after 10.000 requests
assertThat(requests).isLessThan(10_000);
} while (result.getResponse().getStatus() != HttpStatus.TOO_MANY_REQUESTS.value());
// the filter shuts down after 100 GET requests
assertThat(requests).isGreaterThanOrEqualTo(100);
}
@Test
@Description("Ensures that an assumed READ DoS attempt is not blocked as the client (with IPv4 address) is on a whitelist")
public void unacceptableGetLoadButOnWhitelistIPv4() throws Exception {
for (int i = 0; i < 1_000; i++) {
mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant())
.header(HttpHeaders.X_FORWARDED_FOR, "127.0.0.1")).andExpect(status().isOk());
}
}
@Test
@Description("Ensures that an assumed READ DoS attempt is not blocked as the client (with IPv6 address) is on a whitelist")
public void unacceptableGetLoadButOnWhitelistIPv6() throws Exception {
for (int i = 0; i < 1_000; i++) {
mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant())
.header(HttpHeaders.X_FORWARDED_FOR, "0:0:0:0:0:0:0:1")).andExpect(status().isOk());
}
}
@Test
@Description("Ensures that a relatively high number of READ requests is allowed if it is below the DoS detection threshold")
public void acceptableGetLoad() throws Exception {
for (int x = 0; x < 3; x++) {
// sleep for one second
Thread.sleep(1100);
for (int i = 0; i < 99; i++) {
mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant())
.header(HttpHeaders.X_FORWARDED_FOR, "10.0.0.1")).andExpect(status().isOk());
}
}
}
@Test
@Description("Ensures that a WRITE DoS attempt is blocked ")
public void putPostFloddingAttackThatisPrevented() throws Exception {
final Long actionId = prepareDeploymentBase();
final String feedback = JsonBuilder.deploymentActionFeedback(actionId.toString(), "proceeding");
MvcResult result = null;
int requests = 0;
do {
result = mvc.perform(post("/{tenant}/controller/v1/4711/deploymentBase/" + actionId + "/feedback",
tenantAware.getCurrentTenant()).header(HttpHeaders.X_FORWARDED_FOR, "10.0.0.1").content(feedback)
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andReturn();
requests++;
// we give up after 500 requests
assertThat(requests).isLessThan(500);
} while (result.getResponse().getStatus() != HttpStatus.TOO_MANY_REQUESTS.value());
// the filter shuts down after 10 POST requests
assertThat(requests).isGreaterThanOrEqualTo(10);
}
@Test
@Description("Ensures that a relatively high number of WRITE requests is allowed if it is below the DoS detection threshold")
public void acceptablePutPostLoad() throws Exception {
final Long actionId = prepareDeploymentBase();
final String feedback = JsonBuilder.deploymentActionFeedback(actionId.toString(), "proceeding");
for (int x = 0; x < 5; x++) {
// sleep for one second
Thread.sleep(1100);
for (int i = 0; i < 9; i++) {
mvc.perform(post("/{tenant}/controller/v1/4711/deploymentBase/" + actionId + "/feedback",
tenantAware.getCurrentTenant()).header(HttpHeaders.X_FORWARDED_FOR, "10.0.0.1")
.content(feedback).contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
}
}
private Long prepareDeploymentBase() {
final DistributionSet ds = testdataFactory.createDistributionSet("test");
final Target target = targetManagement.createTarget(entityFactory.generateTarget("4711"));
final List<Target> toAssign = new ArrayList<>();
toAssign.add(target);
final Iterable<Target> saved = deploymentManagement.assignDistributionSet(ds, toAssign).getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(target)).hasSize(1);
final Action uaction = deploymentManagement.findActiveActionsByTarget(target).get(0);
return uaction.getId();
}
}

View File

@@ -23,10 +23,10 @@
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-repository</artifactId>
<artifactId>hawkbit-repository-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-core</artifactId>
<version>${project.version}</version>
@@ -41,6 +41,10 @@
<artifactId>hawkbit-dmf-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
@@ -73,6 +77,12 @@
<!-- Test -->
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-repository-test</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
@@ -90,9 +100,9 @@
</dependency>
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-repository</artifactId>
<artifactId>hawkbit-repository-jpa</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ru.yandex.qatools.allure</groupId>

View File

@@ -25,7 +25,7 @@ import org.eclipse.hawkbit.dmf.json.model.DownloadAndUpdateRequest;
import org.eclipse.hawkbit.dmf.json.model.SoftwareModule;
import org.eclipse.hawkbit.eventbus.EventSubscriber;
import org.eclipse.hawkbit.eventbus.event.CancelTargetAssignmentEvent;
import org.eclipse.hawkbit.eventbus.event.TargetAssignDistributionSetEvent;
import org.eclipse.hawkbit.repository.eventbus.event.TargetAssignDistributionSetEvent;
import org.eclipse.hawkbit.repository.model.LocalArtifact;
import org.eclipse.hawkbit.util.IpUtil;
import org.springframework.amqp.core.Message;
@@ -55,8 +55,8 @@ public class AmqpMessageDispatcherService extends BaseAmqpService {
/**
* Constructor.
*
* @param messageConverter
* message converter
* @param rabbitTemplate
* the rabbitTemplate
*/
@Autowired
public AmqpMessageDispatcherService(final RabbitTemplate rabbitTemplate) {
@@ -114,7 +114,7 @@ public class AmqpMessageDispatcherService extends BaseAmqpService {
}
private MessageProperties createConnectorMessageProperties(final String tenant, final String controllerId,
private static MessageProperties createConnectorMessageProperties(final String tenant, final String controllerId,
final EventTopic topic) {
final MessageProperties messageProperties = createMessageProperties();
messageProperties.setHeader(MessageHeaderKey.TOPIC, topic);

View File

@@ -30,11 +30,12 @@ import org.eclipse.hawkbit.dmf.json.model.ArtifactHash;
import org.eclipse.hawkbit.dmf.json.model.DownloadResponse;
import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken;
import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken.FileResource;
import org.eclipse.hawkbit.eventbus.event.TargetAssignDistributionSetEvent;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.im.authentication.TenantAwareAuthenticationDetails;
import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.ControllerManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.eventbus.event.TargetAssignDistributionSetEvent;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status;
@@ -97,6 +98,9 @@ public class AmqpMessageHandlerService extends BaseAmqpService {
@Autowired
private HostnameResolver hostnameResolver;
@Autowired
private EntityFactory entityFactory;
/**
* Constructor.
*
@@ -336,7 +340,7 @@ public class AmqpMessageHandlerService extends BaseAmqpService {
final ActionUpdateStatus actionUpdateStatus = convertMessage(message, ActionUpdateStatus.class);
final Action action = checkActionExist(message, actionUpdateStatus);
final ActionStatus actionStatus = new ActionStatus();
final ActionStatus actionStatus = entityFactory.generateActionStatus();
actionUpdateStatus.getMessage().forEach(actionStatus::addMessage);
actionStatus.setAction(action);
@@ -371,18 +375,18 @@ public class AmqpMessageHandlerService extends BaseAmqpService {
logAndThrowMessageError(message, "Status for action does not exisit.");
}
final Action addUpdateActionStatus = getUpdateActionStatus(action, actionStatus);
final Action addUpdateActionStatus = getUpdateActionStatus(actionStatus);
if (!addUpdateActionStatus.isActive()) {
lookIfUpdateAvailable(action.getTarget());
}
}
private Action getUpdateActionStatus(final Action action, final ActionStatus actionStatus) {
private Action getUpdateActionStatus(final ActionStatus actionStatus) {
if (actionStatus.getStatus().equals(Status.CANCELED)) {
return controllerManagement.addCancelActionStatus(actionStatus, action);
return controllerManagement.addCancelActionStatus(actionStatus);
}
return controllerManagement.addUpdateActionStatus(actionStatus, action);
return controllerManagement.addUpdateActionStatus(actionStatus);
}
private Action checkActionExist(final Message message, final ActionUpdateStatus actionUpdateStatus) {
@@ -449,4 +453,8 @@ public class AmqpMessageHandlerService extends BaseAmqpService {
this.eventBus = eventBus;
}
void setEntityFactory(final EntityFactory entityFactory) {
this.entityFactory = entityFactory;
}
}

View File

@@ -10,6 +10,8 @@ package org.eclipse.hawkbit;
import org.eclipse.hawkbit.amqp.AmqpSenderService;
import org.eclipse.hawkbit.amqp.DefaultAmqpSenderService;
import org.eclipse.hawkbit.repository.jpa.model.helper.SystemSecurityContextHolder;
import org.eclipse.hawkbit.security.SystemSecurityContext;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
@@ -22,6 +24,15 @@ import org.springframework.context.annotation.Configuration;
*/
@Configuration
public class AmqpTestConfiguration {
/**
* @return the {@link SystemSecurityContext} singleton bean which make it
* accessible in beans which cannot access the service directly,
* e.g. JPA entities.
*/
@Bean
public SystemSecurityContextHolder systemSecurityContextHolder() {
return SystemSecurityContextHolder.getInstance();
}
/**
* Method to set the Jackson2JsonMessageConverter.

View File

@@ -25,8 +25,6 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB;
import org.eclipse.hawkbit.TestDataUtil;
import org.eclipse.hawkbit.api.ArtifactUrlHandler;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
import org.eclipse.hawkbit.dmf.amqp.api.EventTopic;
@@ -34,11 +32,12 @@ import org.eclipse.hawkbit.dmf.amqp.api.MessageHeaderKey;
import org.eclipse.hawkbit.dmf.amqp.api.MessageType;
import org.eclipse.hawkbit.dmf.json.model.DownloadAndUpdateRequest;
import org.eclipse.hawkbit.eventbus.event.CancelTargetAssignmentEvent;
import org.eclipse.hawkbit.eventbus.event.TargetAssignDistributionSetEvent;
import org.eclipse.hawkbit.repository.eventbus.event.TargetAssignDistributionSetEvent;
import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.LocalArtifact;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.util.AbstractIntegrationTestWithMongoDB;
import org.eclipse.hawkbit.util.IpUtil;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
@@ -48,6 +47,7 @@ import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.ActiveProfiles;
import ru.yandex.qatools.allure.annotations.Description;
@@ -57,6 +57,7 @@ import ru.yandex.qatools.allure.annotations.Stories;
@ActiveProfiles({ "test" })
@Features("Component Tests - Device Management Federation API")
@Stories("AmqpMessage Dispatcher Service Test")
@SpringApplicationConfiguration(classes = { org.eclipse.hawkbit.RepositoryApplicationConfiguration.class })
public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWithMongoDB {
private static final String TENANT = "default";
@@ -108,8 +109,7 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit
@Test
@Description("Verfies that download and install event with 3 software moduls and no artifacts works")
public void testSendDownloadRequesWithSoftwareModulesAndNoArtifacts() {
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet dsA = testdataFactory.createDistributionSet("");
final TargetAssignDistributionSetEvent targetAssignDistributionSetEvent = new TargetAssignDistributionSetEvent(
1L, TENANT, CONTROLLER_ID, 1L, dsA.getModules(), AMQP_URI, TEST_TOKEN);
amqpMessageDispatcherService.targetAssignDistributionSet(targetAssignDistributionSetEvent);
@@ -139,11 +139,10 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit
@Test
@Description("Verfies that download and install event with software moduls and artifacts works")
public void testSendDownloadRequest() {
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet dsA = testdataFactory.createDistributionSet("");
final SoftwareModule module = dsA.getModules().iterator().next();
final List<DbArtifact> receivedList = new ArrayList<>();
for (final Artifact artifact : TestDataUtil.generateArtifacts(artifactManagement, module.getId())) {
for (final Artifact artifact : testdataFactory.createLocalArtifacts(module.getId())) {
module.addArtifact((LocalArtifact) artifact);
receivedList.add(new DbArtifact());
}

View File

@@ -36,16 +36,21 @@ import org.eclipse.hawkbit.dmf.json.model.ActionUpdateStatus;
import org.eclipse.hawkbit.dmf.json.model.DownloadResponse;
import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken;
import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken.FileResource;
import org.eclipse.hawkbit.eventbus.event.TargetAssignDistributionSetEvent;
import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.ControllerManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.eventbus.event.TargetAssignDistributionSetEvent;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.jpa.model.JpaAction;
import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget;
import org.eclipse.hawkbit.repository.jpa.model.helper.SecurityTokenGeneratorHolder;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.LocalArtifact;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.helper.SecurityTokenGeneratorHolder;
import org.eclipse.hawkbit.repository.model.TargetInfo;
import org.eclipse.hawkbit.security.SecurityTokenGenerator;
import org.junit.Before;
import org.junit.Test;
@@ -82,6 +87,9 @@ public class AmqpMessageHandlerServiceTest {
@Mock
private ControllerManagement controllerManagementMock;
@Mock
private EntityFactory entityFactoryMock;
@Mock
private ArtifactManagement artifactManagementMock;
@@ -114,6 +122,7 @@ public class AmqpMessageHandlerServiceTest {
amqpMessageHandlerService.setCache(cacheMock);
amqpMessageHandlerService.setHostnameResolver(hostnameResolverMock);
amqpMessageHandlerService.setEventBus(eventBus);
amqpMessageHandlerService.setEntityFactory(entityFactoryMock);
}
@@ -346,7 +355,8 @@ public class AmqpMessageHandlerServiceTest {
// Mock
final Action action = createActionWithTarget(22L, Status.FINISHED);
when(controllerManagementMock.findActionWithDetails(Matchers.any())).thenReturn(action);
when(controllerManagementMock.addUpdateActionStatus(Matchers.any(), Matchers.any())).thenReturn(action);
when(controllerManagementMock.addUpdateActionStatus(Matchers.any())).thenReturn(action);
when(entityFactoryMock.generateActionStatus()).thenReturn(new JpaActionStatus());
// for the test the same action can be used
final List<Action> actionList = new ArrayList<>();
actionList.add(action);
@@ -409,7 +419,7 @@ public class AmqpMessageHandlerServiceTest {
private List<SoftwareModule> createSoftwareModuleList() {
final List<SoftwareModule> softwareModuleList = new ArrayList<>();
final SoftwareModule softwareModule = new SoftwareModule();
final JpaSoftwareModule softwareModule = new JpaSoftwareModule();
softwareModule.setId(777L);
softwareModuleList.add(softwareModule);
return softwareModuleList;
@@ -420,14 +430,18 @@ public class AmqpMessageHandlerServiceTest {
initalizeSecurityTokenGenerator();
// Mock
final Action action = new Action();
action.setId(targetId);
action.setStatus(status);
action.setTenant("DEFAULT");
final Target target = new Target("target1");
action.setTarget(target);
return action;
final JpaAction actionMock = mock(JpaAction.class);
final JpaTarget targetMock = mock(JpaTarget.class);
final TargetInfo targetInfoMock = mock(TargetInfo.class);
when(actionMock.getId()).thenReturn(targetId);
when(actionMock.getStatus()).thenReturn(status);
when(actionMock.getTenant()).thenReturn("DEFAULT");
when(actionMock.getTarget()).thenReturn(targetMock);
when(targetMock.getControllerId()).thenReturn("target1");
when(targetMock.getSecurityToken()).thenReturn("securityToken");
when(targetMock.getTargetInfo()).thenReturn(targetInfoMock);
when(targetInfoMock.getAddress()).thenReturn(null);
return actionMock;
}
private void initalizeSecurityTokenGenerator() throws IllegalAccessException {

View File

@@ -10,17 +10,13 @@ package org.eclipse.hawkbit.util;
import static org.junit.Assert.assertEquals;
import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB;
import org.eclipse.hawkbit.AmqpTestConfiguration;
import org.eclipse.hawkbit.RepositoryApplicationConfiguration;
import org.eclipse.hawkbit.TestConfiguration;
import org.eclipse.hawkbit.TestDataUtil;
import org.eclipse.hawkbit.api.ArtifactUrlHandler;
import org.eclipse.hawkbit.api.UrlProtocol;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.LocalArtifact;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.tenancy.TenantAware;
import org.eclipse.hawkbit.repository.util.AbstractIntegrationTestWithMongoDB;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
@@ -35,29 +31,27 @@ import ru.yandex.qatools.allure.annotations.Stories;
*/
@Features("Component Tests - Artifact URL Handler")
@Stories("Test to generate the artifact download URL")
@SpringApplicationConfiguration(classes = { RepositoryApplicationConfiguration.class, TestConfiguration.class,
AmqpTestConfiguration.class })
@SpringApplicationConfiguration(classes = { AmqpTestConfiguration.class,
org.eclipse.hawkbit.RepositoryApplicationConfiguration.class })
public class PropertyBasedArtifactUrlHandlerTest extends AbstractIntegrationTestWithMongoDB {
private static final String HTTPS_LOCALHOST = "https://localhost:8080/";
private static final String HTTP_LOCALHOST = "http://localhost:8080/";
@Autowired
private ArtifactUrlHandler urlHandlerProperties;
@Autowired
private TenantAware tenantAware;
private LocalArtifact localArtifact;
private final String controllerId = "Test";
private static final String CONTROLLER_ID = "Test";
private String fileName;
private Long softwareModuleId;
private String sha1Hash;
@Before
public void setup() {
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet dsA = testdataFactory.createDistributionSet("");
final SoftwareModule module = dsA.getModules().iterator().next();
localArtifact = (LocalArtifact) TestDataUtil.generateArtifacts(artifactManagement, module.getId()).stream()
.findAny().get();
localArtifact = testdataFactory.createLocalArtifacts(module.getId()).stream().findAny().get();
softwareModuleId = localArtifact.getSoftwareModule().getId();
fileName = localArtifact.getFilename();
sha1Hash = localArtifact.getSha1Hash();
@@ -68,21 +62,22 @@ public class PropertyBasedArtifactUrlHandlerTest extends AbstractIntegrationTest
@Description("Tests the generation of http download url.")
public void testHttpUrl() {
final String url = urlHandlerProperties.getUrl(controllerId, softwareModuleId, fileName, sha1Hash,
final String url = urlHandlerProperties.getUrl(CONTROLLER_ID, softwareModuleId, fileName, sha1Hash,
UrlProtocol.HTTP);
assertEquals("http is build incorrect",
HTTP_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/" + controllerId + "/softwaremodules/"
+ localArtifact.getSoftwareModule().getId() + "/artifacts/" + localArtifact.getFilename(),
HTTP_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/" + CONTROLLER_ID
+ "/softwaremodules/" + localArtifact.getSoftwareModule().getId() + "/artifacts/"
+ localArtifact.getFilename(),
url);
}
@Test
@Description("Tests the generation of https download url.")
public void testHttpsUrl() {
final String url = urlHandlerProperties.getUrl(controllerId, softwareModuleId, fileName, sha1Hash,
final String url = urlHandlerProperties.getUrl(CONTROLLER_ID, softwareModuleId, fileName, sha1Hash,
UrlProtocol.HTTPS);
assertEquals("https is build incorrect",
HTTPS_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/" + controllerId
HTTPS_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/" + CONTROLLER_ID
+ "/softwaremodules/" + localArtifact.getSoftwareModule().getId() + "/artifacts/"
+ localArtifact.getFilename(),
url);
@@ -91,10 +86,10 @@ public class PropertyBasedArtifactUrlHandlerTest extends AbstractIntegrationTest
@Test
@Description("Tests the generation of coap download url.")
public void testCoapUrl() {
final String url = urlHandlerProperties.getUrl(controllerId, softwareModuleId, fileName, sha1Hash,
final String url = urlHandlerProperties.getUrl(CONTROLLER_ID, softwareModuleId, fileName, sha1Hash,
UrlProtocol.COAP);
assertEquals("coap is build incorrect", "coap://127.0.0.1:5683/fw/" + tenantAware.getCurrentTenant() + "/"
+ controllerId + "/sha1/" + localArtifact.getSha1Hash(), url);
+ CONTROLLER_ID + "/sha1/" + localArtifact.getSha1Hash(), url);
}
}

View File

@@ -0,0 +1,38 @@
#
# Copyright (c) 2015 Bosch Software Innovations GmbH and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# supported: H2, MYSQL
hawkbit.server.database=H2
spring.jpa.database=${hawkbit.server.database}
flyway.sqlMigrationSuffix=${spring.jpa.database}.sql
# effective DB setting
spring.datasource.url=${${hawkbit.server.database}.spring.datasource.url}
spring.datasource.driverClassName=${${hawkbit.server.database}.spring.datasource.driverClassName}
spring.datasource.username=${${hawkbit.server.database}.spring.datasource.username}
spring.datasource.password=${${hawkbit.server.database}.spring.datasource.password}
# H2
##;AUTOCOMMIT=ON
H2.spring.datasource.url=jdbc:h2:mem:sp-db;DB_CLOSE_ON_EXIT=FALSE
#H2.spring.datasource.url=jdbc:h2:./db/sp-db;AUTO_SERVER=TRUE;DB_CLOSE_ON_EXIT=FALSE;MVCC=TRUE
H2.spring.datasource.driverClassName=org.h2.Driver
H2.spring.datasource.username=sa
H2.spring.datasource.password=sa
# MYSQL
MYSQL.spring.datasource.url=jdbc:mysql://localhost:3306/sp_test
MYSQL.spring.datasource.driverClassName=org.mariadb.jdbc.Driver
MYSQL.spring.datasource.username=root
MYSQL.spring.datasource.password=

View File

@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2015 Bosch Software Innovations GmbH and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v10.html
-->
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml" />
<logger name="org.eclipse.hawkbit.eventbus.DeadEventListener" level="WARN" />
<Logger name="org.springframework.boot.actuate.audit.listener.AuditListener" level="WARN" />
<Logger name="org.hibernate.validator.internal.util.Version" level="WARN" />
<Logger name="org.apache.coyote.http11.Http11NioProtocol" level="WARN" />
<Logger name="org.apache.tomcat.util.net.NioSelectorPool" level="WARN" />
<Logger name="org.apache.tomcat.jdbc.pool.ConnectionPool" level="DEBUG" />
<Logger name="org.apache.catalina.startup.DigesterFactory" level="ERROR" />
<!-- <Logger name="org.eclipse.hawkbit.rest.util.MockMvcResultPrinter" level="DEBUG" /> -->
<!-- Security Log with hints on potential attacks -->
<logger name="server-security" level="INFO" />
<Root level="INFO">
<AppenderRef ref="Console" />
</Root>
</configuration>

View File

@@ -21,6 +21,43 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public enum ActionStatus {
/**
* Action requests download by this target which has now started.
*/
DOWNLOAD,
DOWNLOAD, RETRIEVED, RUNNING, FINISHED, ERROR, WARNING, CANCELED, CANCEL_REJECTED;
/**
* Action has been send to the target.
*/
RETRIEVED,
/**
* Action is still running for this target.
*/
RUNNING,
/**
* Action is finished successfully for this target.
*/
FINISHED,
/**
* Action has failed for this target.
*/
ERROR,
/**
* Action is still running but with warnings.
*/
WARNING,
/**
* Action has been canceled for this target.
*/
CANCELED,
/**
* Cancellation has been rejected by the target..
*/
CANCEL_REJECTED;
}

View File

@@ -22,7 +22,7 @@
<dependencies>
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-repository</artifactId>
<artifactId>hawkbit-repository-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>

View File

@@ -23,19 +23,6 @@ import com.fasterxml.jackson.annotation.JsonProperty;
@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class MgmtSoftwareModule extends MgmtNamedEntity {
/**
* API definition for Software module type#RUNTIME.
*/
public static final String SM_RUNTIME = "runtime";
/**
* API definition for for Software module type#OS.
*/
public static final String SM_OS = "os";
/**
* API definition for for Software module type#APPLICATION.
*/
public static final String SM_APPLICATION = "application";
@JsonProperty(value = "id", required = true)
private Long moduleId;

View File

@@ -23,9 +23,9 @@
<dependencies>
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-repository</artifactId>
<artifactId>hawkbit-repository-api</artifactId>
<version>${project.version}</version>
</dependency>
</dependency>
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-mgmt-api</artifactId>
@@ -47,6 +47,18 @@
</dependency>
<!-- Test -->
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-repository-test</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-repository-jpa</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-rest-core</artifactId>
@@ -90,13 +102,6 @@
<artifactId>spring-security-config</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-repository</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-http-security</artifactId>

View File

@@ -23,6 +23,7 @@ import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTypeRestApi;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.DistributionSetAssignmentResult;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.DistributionSet;
@@ -75,11 +76,12 @@ public final class MgmtDistributionSetMapper {
* @return converted list of {@link DistributionSet}s
*/
static List<DistributionSet> dsFromRequest(final Iterable<MgmtDistributionSetRequestBodyPost> sets,
final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement) {
final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement,
final EntityFactory entityFactory) {
final List<DistributionSet> mappedList = new ArrayList<>();
for (final MgmtDistributionSetRequestBodyPost dsRest : sets) {
mappedList.add(fromRequest(dsRest, softwareManagement, distributionSetManagement));
mappedList.add(fromRequest(dsRest, softwareManagement, distributionSetManagement, entityFactory));
}
return mappedList;
@@ -95,9 +97,10 @@ public final class MgmtDistributionSetMapper {
* @return converted {@link DistributionSet}
*/
static DistributionSet fromRequest(final MgmtDistributionSetRequestBodyPost dsRest,
final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement) {
final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement,
final EntityFactory entityFactory) {
final DistributionSet result = new DistributionSet();
final DistributionSet result = entityFactory.generateDistributionSet();
result.setDescription(dsRest.getDescription());
result.setName(dsRest.getName());
result.setType(findDistributionSetTypeWithExceptionIfNotFound(dsRest.getType(), distributionSetManagement));
@@ -135,13 +138,14 @@ public final class MgmtDistributionSetMapper {
* @return
*/
static List<DistributionSetMetadata> fromRequestDsMetadata(final DistributionSet ds,
final List<MgmtMetadata> metadata) {
final List<MgmtMetadata> metadata, final EntityFactory entityFactory) {
final List<DistributionSetMetadata> mappedList = new ArrayList<>(metadata.size());
for (final MgmtMetadata metadataRest : metadata) {
if (metadataRest.getKey() == null) {
throw new IllegalArgumentException("the key of the metadata must be present");
}
mappedList.add(new DistributionSetMetadata(metadataRest.getKey(), ds, metadataRest.getValue()));
mappedList.add(
entityFactory.generateDistributionSetMetadata(ds, metadataRest.getKey(), metadataRest.getValue()));
}
return mappedList;
}
@@ -170,12 +174,11 @@ public final class MgmtDistributionSetMapper {
response.setRequiredMigrationStep(distributionSet.isRequiredMigrationStep());
response.add(
linkTo(methodOn(MgmtDistributionSetRestApi.class).getDistributionSet(response.getDsId())).withRel("self"));
response.add(linkTo(methodOn(MgmtDistributionSetRestApi.class).getDistributionSet(response.getDsId()))
.withRel("self"));
response.add(linkTo(
methodOn(MgmtDistributionSetTypeRestApi.class).getDistributionSetType(distributionSet.getType().getId()))
.withRel("type"));
response.add(linkTo(methodOn(MgmtDistributionSetTypeRestApi.class)
.getDistributionSetType(distributionSet.getType().getId())).withRel("type"));
response.add(linkTo(methodOn(MgmtDistributionSetRestApi.class).getMetadata(response.getDsId(),
Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET),
@@ -206,7 +209,7 @@ public final class MgmtDistributionSetMapper {
static MgmtMetadata toResponseDsMetadata(final DistributionSetMetadata metadata) {
final MgmtMetadata metadataRest = new MgmtMetadata();
metadataRest.setKey(metadata.getId().getKey());
metadataRest.setKey(metadata.getKey());
metadataRest.setValue(metadata.getValue());
return metadataRest;
}

View File

@@ -27,22 +27,18 @@ import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetRestApi;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.DeploymentManagement;
import org.eclipse.hawkbit.repository.DistributionSetAssignmentResult;
import org.eclipse.hawkbit.repository.DistributionSetFields;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.DistributionSetMetadataFields;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.SystemManagement;
import org.eclipse.hawkbit.repository.TargetFields;
import org.eclipse.hawkbit.repository.TargetManagement;
import org.eclipse.hawkbit.repository.TargetWithActionType;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetMetadata;
import org.eclipse.hawkbit.repository.model.DsMetadataCompositeKey;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.rsql.RSQLUtility;
import org.eclipse.hawkbit.repository.model.TargetWithActionType;
import org.eclipse.hawkbit.tenancy.TenantAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -79,6 +75,9 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
@Autowired
private TenantAware currentTenant;
@Autowired
private EntityFactory entityFactory;
@Autowired
private DistributionSetManagement distributionSetManagement;
@@ -96,10 +95,10 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Page<DistributionSet> findDsPage;
if (rsqlParam != null) {
findDsPage = this.distributionSetManagement.findDistributionSetsAll(
RSQLUtility.parse(rsqlParam, DistributionSetFields.class), pageable, false);
findDsPage = this.distributionSetManagement.findDistributionSetsAll(rsqlParam, pageable, false);
} else {
findDsPage = this.distributionSetManagement.findDistributionSetsAll(pageable, false, null);
findDsPage = this.distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageable, false,
null);
}
final List<MgmtDistributionSet> rest = MgmtDistributionSetMapper.toResponseFromDsList(findDsPage.getContent());
@@ -123,8 +122,9 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
sets.stream().filter(ds -> ds.getType() == null).forEach(ds -> ds.setType(this.systemManagement
.getTenantMetadata(this.currentTenant.getCurrentTenant()).getDefaultDsType().getKey()));
final Iterable<DistributionSet> createdDSets = this.distributionSetManagement.createDistributionSets(
MgmtDistributionSetMapper.dsFromRequest(sets, this.softwareManagement, this.distributionSetManagement));
final Iterable<DistributionSet> createdDSets = this.distributionSetManagement
.createDistributionSets(MgmtDistributionSetMapper.dsFromRequest(sets, this.softwareManagement,
this.distributionSetManagement, entityFactory));
LOG.debug("{} distribution sets created, return status {}", sets.size(), HttpStatus.CREATED);
return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDistributionSets(createdDSets),
@@ -181,8 +181,8 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Page<Target> targetsAssignedDS;
if (rsqlParam != null) {
targetsAssignedDS = this.targetManagement.findTargetByAssignedDistributionSet(distributionSetId,
RSQLUtility.parse(rsqlParam, TargetFields.class), pageable);
targetsAssignedDS = this.targetManagement.findTargetByAssignedDistributionSet(distributionSetId, rsqlParam,
pageable);
} else {
targetsAssignedDS = this.targetManagement.findTargetByAssignedDistributionSet(distributionSetId, pageable);
}
@@ -210,7 +210,7 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
final Page<Target> targetsInstalledDS;
if (rsqlParam != null) {
targetsInstalledDS = this.targetManagement.findTargetByInstalledDistributionSet(distributionSetId,
RSQLUtility.parse(rsqlParam, TargetFields.class), pageable);
rsqlParam, pageable);
} else {
targetsInstalledDS = this.targetManagement.findTargetByInstalledDistributionSet(distributionSetId,
pageable);
@@ -257,8 +257,8 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
final Page<DistributionSetMetadata> metaDataPage;
if (rsqlParam != null) {
metaDataPage = this.distributionSetManagement.findDistributionSetMetadataByDistributionSetId(
distributionSetId, RSQLUtility.parse(rsqlParam, DistributionSetMetadataFields.class), pageable);
metaDataPage = this.distributionSetManagement
.findDistributionSetMetadataByDistributionSetId(distributionSetId, rsqlParam, pageable);
} else {
metaDataPage = this.distributionSetManagement
.findDistributionSetMetadataByDistributionSetId(distributionSetId, pageable);
@@ -278,8 +278,7 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
// check if distribution set exists otherwise throw exception
// immediately
final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId);
final DistributionSetMetadata findOne = this.distributionSetManagement
.findOne(new DsMetadataCompositeKey(ds, metadataKey));
final DistributionSetMetadata findOne = this.distributionSetManagement.findOne(ds, metadataKey);
return ResponseEntity.<MgmtMetadata> ok(MgmtDistributionSetMapper.toResponseDsMetadata(findOne));
}
@@ -289,8 +288,8 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
// check if distribution set exists otherwise throw exception
// immediately
final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId);
final DistributionSetMetadata updated = this.distributionSetManagement
.updateDistributionSetMetadata(new DistributionSetMetadata(metadataKey, ds, metadata.getValue()));
final DistributionSetMetadata updated = this.distributionSetManagement.updateDistributionSetMetadata(
entityFactory.generateDistributionSetMetadata(ds, metadataKey, metadata.getValue()));
return ResponseEntity.ok(MgmtDistributionSetMapper.toResponseDsMetadata(updated));
}
@@ -300,7 +299,7 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
// check if distribution set exists otherwise throw exception
// immediately
final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId);
this.distributionSetManagement.deleteDistributionSetMetadata(new DsMetadataCompositeKey(ds, metadataKey));
this.distributionSetManagement.deleteDistributionSetMetadata(ds, metadataKey);
return ResponseEntity.ok().build();
}
@@ -312,8 +311,8 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
// immediately
final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId);
final List<DistributionSetMetadata> created = this.distributionSetManagement
.createDistributionSetMetadata(MgmtDistributionSetMapper.fromRequestDsMetadata(ds, metadataRest));
final List<DistributionSetMetadata> created = this.distributionSetManagement.createDistributionSetMetadata(
MgmtDistributionSetMapper.fromRequestDsMetadata(ds, metadataRest, entityFactory));
return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDsMetadata(created), HttpStatus.CREATED);
}

View File

@@ -20,14 +20,13 @@ import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTagRequestBodyPut;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTagRestApi;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.TagFields;
import org.eclipse.hawkbit.repository.TagManagement;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult;
import org.eclipse.hawkbit.repository.rsql.RSQLUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -56,6 +55,9 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
@Autowired
private DistributionSetManagement distributionSetManagement;
@Autowired
private EntityFactory entityFactory;
@Override
public ResponseEntity<PagedList<MgmtTag>> getDistributionSetTags(
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam,
@@ -75,8 +77,8 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
countTargetsAll = this.tagManagement.countTargetTags();
} else {
final Page<DistributionSetTag> findTargetPage = this.tagManagement
.findAllDistributionSetTags(RSQLUtility.parse(rsqlParam, TagFields.class), pageable);
final Page<DistributionSetTag> findTargetPage = this.tagManagement.findAllDistributionSetTags(rsqlParam,
pageable);
countTargetsAll = findTargetPage.getTotalElements();
findTargetsAll = findTargetPage;
@@ -99,7 +101,7 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
LOG.debug("creating {} ds tags", tags.size());
final List<DistributionSetTag> createdTags = this.tagManagement
.createDistributionSetTags(MgmtTagMapper.mapDistributionSetTagFromRequest(tags));
.createDistributionSetTags(MgmtTagMapper.mapDistributionSetTagFromRequest(entityFactory, tags));
return new ResponseEntity<>(MgmtTagMapper.toResponseDistributionSetTag(createdTags), HttpStatus.CREATED);
}

View File

@@ -14,10 +14,11 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRequestBodyPost;
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetType;
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRequestBodyPost;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTypeRestApi;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
@@ -35,21 +36,22 @@ final class MgmtDistributionSetTypeMapper {
}
static List<DistributionSetType> smFromRequest(final SoftwareManagement softwareManagement,
static List<DistributionSetType> smFromRequest(final EntityFactory entityFactory,
final SoftwareManagement softwareManagement,
final Iterable<MgmtDistributionSetTypeRequestBodyPost> smTypesRest) {
final List<DistributionSetType> mappedList = new ArrayList<>();
for (final MgmtDistributionSetTypeRequestBodyPost smRest : smTypesRest) {
mappedList.add(fromRequest(softwareManagement, smRest));
mappedList.add(fromRequest(entityFactory, softwareManagement, smRest));
}
return mappedList;
}
static DistributionSetType fromRequest(final SoftwareManagement softwareManagement,
final MgmtDistributionSetTypeRequestBodyPost smsRest) {
static DistributionSetType fromRequest(final EntityFactory entityFactory,
final SoftwareManagement softwareManagement, final MgmtDistributionSetTypeRequestBodyPost smsRest) {
final DistributionSetType result = new DistributionSetType(smsRest.getKey(), smsRest.getName(),
smsRest.getDescription());
final DistributionSetType result = entityFactory.generateDistributionSetType(smsRest.getKey(),
smsRest.getName(), smsRest.getDescription());
// Add mandatory
smsRest.getMandatorymodules().stream().map(mand -> {

View File

@@ -12,14 +12,14 @@ import java.util.List;
import org.eclipse.hawkbit.mgmt.json.model.MgmtId;
import org.eclipse.hawkbit.mgmt.json.model.PagedList;
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetType;
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRequestBodyPost;
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRequestBodyPut;
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetType;
import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleType;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTypeRestApi;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.DistributionSetTypeFields;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
@@ -27,7 +27,6 @@ import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.rsql.RSQLUtility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
@@ -55,6 +54,9 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
@Autowired
private DistributionSetManagement distributionSetManagement;
@Autowired
private EntityFactory entityFactory;
@Override
public ResponseEntity<PagedList<MgmtDistributionSetType>> getDistributionSetTypes(
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam,
@@ -71,8 +73,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
final Slice<DistributionSetType> findModuleTypessAll;
Long countModulesAll;
if (rsqlParam != null) {
findModuleTypessAll = distributionSetManagement.findDistributionSetTypesByPredicate(
RSQLUtility.parse(rsqlParam, DistributionSetTypeFields.class), pageable);
findModuleTypessAll = distributionSetManagement.findDistributionSetTypesAll(rsqlParam, pageable);
countModulesAll = ((Page<DistributionSetType>) findModuleTypessAll).getTotalElements();
} else {
findModuleTypessAll = distributionSetManagement.findDistributionSetTypesAll(pageable);
@@ -125,7 +126,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
@RequestBody final List<MgmtDistributionSetTypeRequestBodyPost> distributionSetTypes) {
final List<DistributionSetType> createdSoftwareModules = distributionSetManagement.createDistributionSetTypes(
MgmtDistributionSetTypeMapper.smFromRequest(softwareManagement, distributionSetTypes));
MgmtDistributionSetTypeMapper.smFromRequest(entityFactory, softwareManagement, distributionSetTypes));
return new ResponseEntity<>(MgmtDistributionSetTypeMapper.toTypesResponse(createdSoftwareModules),
HttpStatus.CREATED);

View File

@@ -22,6 +22,7 @@ import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutSuccessAction.Succ
import org.eclipse.hawkbit.mgmt.json.model.rolloutgroup.MgmtRolloutGroupResponseBody;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRolloutRestApi;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.model.Action.ActionType;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.Rollout;
@@ -83,9 +84,9 @@ final class MgmtRolloutMapper {
return body;
}
static Rollout fromRequest(final MgmtRolloutRestRequestBody restRequest, final DistributionSet distributionSet,
final String filterQuery) {
final Rollout rollout = new Rollout();
static Rollout fromRequest(final EntityFactory entityFactory, final MgmtRolloutRestRequestBody restRequest,
final DistributionSet distributionSet, final String filterQuery) {
final Rollout rollout = entityFactory.generateRollout();
rollout.setName(restRequest.getName());
rollout.setDescription(restRequest.getDescription());
rollout.setDistributionSet(distributionSet);

View File

@@ -18,28 +18,26 @@ import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTarget;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRolloutRestApi;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.RolloutFields;
import org.eclipse.hawkbit.repository.RolloutGroupFields;
import org.eclipse.hawkbit.repository.RolloutGroupManagement;
import org.eclipse.hawkbit.repository.RolloutManagement;
import org.eclipse.hawkbit.repository.TargetFields;
import org.eclipse.hawkbit.repository.TargetFilterQueryManagement;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.Rollout;
import org.eclipse.hawkbit.repository.model.RolloutGroup;
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupConditions;
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupErrorAction;
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupErrorCondition;
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessAction;
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessCondition;
import org.eclipse.hawkbit.repository.model.RolloutGroupConditionBuilder;
import org.eclipse.hawkbit.repository.model.RolloutGroupConditions;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.rsql.RSQLUtility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
@@ -65,6 +63,12 @@ public class MgmtRolloutResource implements MgmtRolloutRestApi {
@Autowired
private DistributionSetManagement distributionSetManagement;
@Autowired
private TargetFilterQueryManagement targetFilterQueryManagement;
@Autowired
private EntityFactory entityFactory;
@Override
public ResponseEntity<PagedList<MgmtRolloutResponseBody>> getRollouts(
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam,
@@ -80,8 +84,7 @@ public class MgmtRolloutResource implements MgmtRolloutRestApi {
final Page<Rollout> findModulesAll;
if (rsqlParam != null) {
findModulesAll = this.rolloutManagement
.findAllWithDetailedStatusByPredicate(RSQLUtility.parse(rsqlParam, RolloutFields.class), pageable);
findModulesAll = this.rolloutManagement.findAllWithDetailedStatusByPredicate(rsqlParam, pageable);
} else {
findModulesAll = this.rolloutManagement.findAll(pageable);
}
@@ -102,7 +105,7 @@ public class MgmtRolloutResource implements MgmtRolloutRestApi {
// first check the given RSQL query if it's well formed, otherwise and
// exception is thrown
RSQLUtility.parse(rolloutRequestBody.getTargetFilterQuery(), TargetFields.class);
targetFilterQueryManagement.verifyTargetFilterQuerySyntax(rolloutRequestBody.getTargetFilterQuery());
final DistributionSet distributionSet = findDistributionSetOrThrowException(rolloutRequestBody);
@@ -136,12 +139,12 @@ public class MgmtRolloutResource implements MgmtRolloutRestApi {
errorActionExpr = rolloutRequestBody.getErrorAction().getExpression();
}
final RolloutGroupConditions rolloutGroupConditions = new RolloutGroup.RolloutGroupConditionBuilder()
final RolloutGroupConditions rolloutGroupConditions = new RolloutGroupConditionBuilder()
.successCondition(successCondition, successConditionExpr)
.successAction(successAction, successActionExpr).errorCondition(errorCondition, errorConditionExpr)
.errorAction(errorAction, errorActionExpr).build();
final Rollout rollout = this.rolloutManagement.createRollout(
MgmtRolloutMapper.fromRequest(rolloutRequestBody, distributionSet,
MgmtRolloutMapper.fromRequest(entityFactory, rolloutRequestBody, distributionSet,
rolloutRequestBody.getTargetFilterQuery()),
rolloutRequestBody.getAmountGroups(), rolloutGroupConditions);
@@ -191,8 +194,7 @@ public class MgmtRolloutResource implements MgmtRolloutRestApi {
final Page<RolloutGroup> findRolloutGroupsAll;
if (rsqlParam != null) {
findRolloutGroupsAll = this.rolloutGroupManagement.findRolloutGroupsByPredicate(rollout,
RSQLUtility.parse(rsqlParam, RolloutGroupFields.class), pageable);
findRolloutGroupsAll = this.rolloutGroupManagement.findRolloutGroupsAll(rollout, rsqlParam, pageable);
} else {
findRolloutGroupsAll = this.rolloutGroupManagement.findRolloutGroupsByRolloutId(rolloutId, pageable);
}
@@ -228,8 +230,7 @@ public class MgmtRolloutResource implements MgmtRolloutRestApi {
final Page<Target> rolloutGroupTargets;
if (rsqlParam != null) {
final Specification<Target> rsqlSpecification = RSQLUtility.parse(rsqlParam, TargetFields.class);
rolloutGroupTargets = this.rolloutGroupManagement.findRolloutGroupTargets(rolloutGroup, rsqlSpecification,
rolloutGroupTargets = this.rolloutGroupManagement.findRolloutGroupTargets(rolloutGroup, rsqlParam,
pageable);
} else {
final Page<Target> pageTargets = this.rolloutGroupManagement.findRolloutGroupTargets(rolloutGroup,

View File

@@ -22,6 +22,7 @@ import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleRequ
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleRestApi;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleTypeRestApi;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Artifact;
@@ -52,29 +53,31 @@ public final class MgmtSoftwareModuleMapper {
return smType;
}
static SoftwareModule fromRequest(final MgmtSoftwareModuleRequestBodyPost smsRest,
final SoftwareManagement softwareManagement) {
return new SoftwareModule(getSoftwareModuleTypeFromKeyString(smsRest.getType(), softwareManagement),
smsRest.getName(), smsRest.getVersion(), smsRest.getDescription(), smsRest.getVendor());
static SoftwareModule fromRequest(final EntityFactory entityFactory,
final MgmtSoftwareModuleRequestBodyPost smsRest, final SoftwareManagement softwareManagement) {
return entityFactory.generateSoftwareModule(
getSoftwareModuleTypeFromKeyString(smsRest.getType(), softwareManagement), smsRest.getName(),
smsRest.getVersion(), smsRest.getDescription(), smsRest.getVendor());
}
static List<SoftwareModuleMetadata> fromRequestSwMetadata(final SoftwareModule sw,
final List<MgmtMetadata> metadata) {
static List<SoftwareModuleMetadata> fromRequestSwMetadata(final EntityFactory entityFactory,
final SoftwareModule sw, final List<MgmtMetadata> metadata) {
final List<SoftwareModuleMetadata> mappedList = new ArrayList<>(metadata.size());
for (final MgmtMetadata metadataRest : metadata) {
if (metadataRest.getKey() == null) {
throw new IllegalArgumentException("the key of the metadata must be present");
}
mappedList.add(new SoftwareModuleMetadata(metadataRest.getKey(), sw, metadataRest.getValue()));
mappedList.add(
entityFactory.generateSoftwareModuleMetadata(sw, metadataRest.getKey(), metadataRest.getValue()));
}
return mappedList;
}
static List<SoftwareModule> smFromRequest(final Iterable<MgmtSoftwareModuleRequestBodyPost> smsRest,
final SoftwareManagement softwareManagement) {
static List<SoftwareModule> smFromRequest(final EntityFactory entityFactory,
final Iterable<MgmtSoftwareModuleRequestBodyPost> smsRest, final SoftwareManagement softwareManagement) {
final List<SoftwareModule> mappedList = new ArrayList<>();
for (final MgmtSoftwareModuleRequestBodyPost smRest : smsRest) {
mappedList.add(fromRequest(smRest, softwareManagement));
mappedList.add(fromRequest(entityFactory, smRest, softwareManagement));
}
return mappedList;
}
@@ -116,7 +119,7 @@ public final class MgmtSoftwareModuleMapper {
static MgmtMetadata toResponseSwMetadata(final SoftwareModuleMetadata metadata) {
final MgmtMetadata metadataRest = new MgmtMetadata();
metadataRest.setKey(metadata.getId().getKey());
metadataRest.setKey(metadata.getKey());
metadataRest.setValue(metadata.getValue());
return metadataRest;
}

View File

@@ -20,16 +20,13 @@ import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleRequ
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleRestApi;
import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.SoftwareModuleFields;
import org.eclipse.hawkbit.repository.SoftwareModuleMetadataFields;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata;
import org.eclipse.hawkbit.repository.model.SwMetadataCompositeKey;
import org.eclipse.hawkbit.repository.rsql.RSQLUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -61,6 +58,9 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
@Autowired
private SoftwareManagement softwareManagement;
@Autowired
private EntityFactory entityFactory;
@Override
public ResponseEntity<MgmtArtifact> uploadArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId,
@RequestParam("file") final MultipartFile file,
@@ -139,8 +139,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
final Slice<SoftwareModule> findModulesAll;
Long countModulesAll;
if (rsqlParam != null) {
findModulesAll = softwareManagement
.findSoftwareModulesByPredicate(RSQLUtility.parse(rsqlParam, SoftwareModuleFields.class), pageable);
findModulesAll = softwareManagement.findSoftwareModulesByPredicate(rsqlParam, pageable);
countModulesAll = ((Page<SoftwareModule>) findModulesAll).getTotalElements();
} else {
findModulesAll = softwareManagement.findSoftwareModulesAll(pageable);
@@ -163,8 +162,8 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
public ResponseEntity<List<MgmtSoftwareModule>> createSoftwareModules(
@RequestBody final List<MgmtSoftwareModuleRequestBodyPost> softwareModules) {
LOG.debug("creating {} softwareModules", softwareModules.size());
final Iterable<SoftwareModule> createdSoftwareModules = softwareManagement
.createSoftwareModule(MgmtSoftwareModuleMapper.smFromRequest(softwareModules, softwareManagement));
final Iterable<SoftwareModule> createdSoftwareModules = softwareManagement.createSoftwareModule(
MgmtSoftwareModuleMapper.smFromRequest(entityFactory, softwareModules, softwareManagement));
LOG.debug("{} softwareModules created, return status {}", softwareModules.size(), HttpStatus.CREATED);
return new ResponseEntity<>(MgmtSoftwareModuleMapper.toResponseSoftwareModules(createdSoftwareModules),
@@ -217,8 +216,8 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
final Page<SoftwareModuleMetadata> metaDataPage;
if (rsqlParam != null) {
metaDataPage = softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(softwareModuleId,
RSQLUtility.parse(rsqlParam, SoftwareModuleMetadataFields.class), pageable);
metaDataPage = softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(softwareModuleId, rsqlParam,
pageable);
} else {
metaDataPage = softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(softwareModuleId, pageable);
}
@@ -233,8 +232,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
public ResponseEntity<MgmtMetadata> getMetadataValue(@PathVariable("softwareModuleId") final Long softwareModuleId,
@PathVariable("metadataKey") final String metadataKey) {
final SoftwareModule sw = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null);
final SoftwareModuleMetadata findOne = softwareManagement
.findSoftwareModuleMetadata(new SwMetadataCompositeKey(sw, metadataKey));
final SoftwareModuleMetadata findOne = softwareManagement.findSoftwareModuleMetadata(sw, metadataKey);
return ResponseEntity.<MgmtMetadata> ok(MgmtSoftwareModuleMapper.toResponseSwMetadata(findOne));
}
@@ -242,8 +240,8 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
public ResponseEntity<MgmtMetadata> updateMetadata(@PathVariable("softwareModuleId") final Long softwareModuleId,
@PathVariable("metadataKey") final String metadataKey, @RequestBody final MgmtMetadata metadata) {
final SoftwareModule sw = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null);
final SoftwareModuleMetadata updated = softwareManagement
.updateSoftwareModuleMetadata(new SoftwareModuleMetadata(metadataKey, sw, metadata.getValue()));
final SoftwareModuleMetadata updated = softwareManagement.updateSoftwareModuleMetadata(
entityFactory.generateSoftwareModuleMetadata(sw, metadataKey, metadata.getValue()));
return ResponseEntity.ok(MgmtSoftwareModuleMapper.toResponseSwMetadata(updated));
}
@@ -251,7 +249,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
public ResponseEntity<Void> deleteMetadata(@PathVariable("softwareModuleId") final Long softwareModuleId,
@PathVariable("metadataKey") final String metadataKey) {
final SoftwareModule sw = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null);
softwareManagement.deleteSoftwareModuleMetadata(new SwMetadataCompositeKey(sw, metadataKey));
softwareManagement.deleteSoftwareModuleMetadata(sw, metadataKey);
return ResponseEntity.ok().build();
}
@@ -261,8 +259,8 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
@RequestBody final List<MgmtMetadata> metadataRest) {
final SoftwareModule sw = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null);
final List<SoftwareModuleMetadata> created = softwareManagement
.createSoftwareModuleMetadata(MgmtSoftwareModuleMapper.fromRequestSwMetadata(sw, metadataRest));
final List<SoftwareModuleMetadata> created = softwareManagement.createSoftwareModuleMetadata(
MgmtSoftwareModuleMapper.fromRequestSwMetadata(entityFactory, sw, metadataRest));
return new ResponseEntity<>(MgmtSoftwareModuleMapper.toResponseSwMetadata(created), HttpStatus.CREATED);

View File

@@ -18,6 +18,7 @@ import java.util.List;
import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleType;
import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeRequestBodyPost;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleTypeRestApi;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
/**
@@ -35,18 +36,25 @@ final class MgmtSoftwareModuleTypeMapper {
}
static List<SoftwareModuleType> smFromRequest(final Iterable<MgmtSoftwareModuleTypeRequestBodyPost> smTypesRest) {
static List<SoftwareModuleType> smFromRequest(final EntityFactory entityFactory,
final Iterable<MgmtSoftwareModuleTypeRequestBodyPost> smTypesRest) {
final List<SoftwareModuleType> mappedList = new ArrayList<>();
for (final MgmtSoftwareModuleTypeRequestBodyPost smRest : smTypesRest) {
mappedList.add(fromRequest(smRest));
mappedList.add(fromRequest(entityFactory, smRest));
}
return mappedList;
}
static SoftwareModuleType fromRequest(final MgmtSoftwareModuleTypeRequestBodyPost smsRest) {
return new SoftwareModuleType(smsRest.getKey(), smsRest.getName(), smsRest.getDescription(),
smsRest.getMaxAssignments());
static SoftwareModuleType fromRequest(final EntityFactory entityFactory,
final MgmtSoftwareModuleTypeRequestBodyPost smsRest) {
final SoftwareModuleType result = entityFactory.generateSoftwareModuleType();
result.setName(smsRest.getName());
result.setKey(smsRest.getKey());
result.setDescription(smsRest.getDescription());
result.setMaxAssignments(smsRest.getMaxAssignments());
return result;
}
static List<MgmtSoftwareModuleType> toTypesResponse(final List<SoftwareModuleType> types) {

View File

@@ -16,14 +16,13 @@ import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModule
import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeRequestBodyPut;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleTypeRestApi;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.SoftwareModuleTypeFields;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.rsql.RSQLUtility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
@@ -46,6 +45,9 @@ public class MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRes
@Autowired
private SoftwareManagement softwareManagement;
@Autowired
private EntityFactory entityFactory;
@Override
public ResponseEntity<PagedList<MgmtSoftwareModuleType>> getTypes(
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam,
@@ -62,8 +64,7 @@ public class MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRes
final Slice<SoftwareModuleType> findModuleTypessAll;
Long countModulesAll;
if (rsqlParam != null) {
findModuleTypessAll = this.softwareManagement.findSoftwareModuleTypesByPredicate(
RSQLUtility.parse(rsqlParam, SoftwareModuleTypeFields.class), pageable);
findModuleTypessAll = this.softwareManagement.findSoftwareModuleTypesAll(rsqlParam, pageable);
countModulesAll = ((Page<SoftwareModuleType>) findModuleTypessAll).getTotalElements();
} else {
findModuleTypessAll = this.softwareManagement.findSoftwareModuleTypesAll(pageable);
@@ -112,8 +113,8 @@ public class MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRes
public ResponseEntity<List<MgmtSoftwareModuleType>> createSoftwareModuleTypes(
@RequestBody final List<MgmtSoftwareModuleTypeRequestBodyPost> softwareModuleTypes) {
final List<SoftwareModuleType> createdSoftwareModules = this.softwareManagement
.createSoftwareModuleType(MgmtSoftwareModuleTypeMapper.smFromRequest(softwareModuleTypes));
final List<SoftwareModuleType> createdSoftwareModules = this.softwareManagement.createSoftwareModuleType(
MgmtSoftwareModuleTypeMapper.smFromRequest(entityFactory, softwareModuleTypes));
return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toTypesResponse(createdSoftwareModules),
HttpStatus.CREATED);

View File

@@ -18,9 +18,9 @@ import org.eclipse.hawkbit.mgmt.json.model.systemmanagement.MgmtSystemCache;
import org.eclipse.hawkbit.mgmt.json.model.systemmanagement.MgmtSystemStatisticsRest;
import org.eclipse.hawkbit.mgmt.json.model.systemmanagement.MgmtSystemTenantServiceUsage;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtSystemManagementRestApi;
import org.eclipse.hawkbit.report.model.SystemUsageReport;
import org.eclipse.hawkbit.report.model.TenantUsage;
import org.eclipse.hawkbit.repository.SystemManagement;
import org.eclipse.hawkbit.repository.report.model.SystemUsageReport;
import org.eclipse.hawkbit.repository.report.model.TenantUsage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

View File

@@ -123,3 +123,4 @@ public class MgmtSystemResource implements MgmtSystemRestApi {
}
}

View File

@@ -18,6 +18,7 @@ import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTag;
import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTagRequestBodyPut;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTagRestApi;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetTagRestApi;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.eclipse.hawkbit.repository.model.Tag;
import org.eclipse.hawkbit.repository.model.TargetTag;
@@ -84,8 +85,9 @@ final class MgmtTagMapper {
mapTag(response, distributionSetTag);
response.add(linkTo(methodOn(MgmtDistributionSetTagRestApi.class).getDistributionSetTag(distributionSetTag.getId()))
.withRel("self"));
response.add(
linkTo(methodOn(MgmtDistributionSetTagRestApi.class).getDistributionSetTag(distributionSetTag.getId()))
.withRel("self"));
response.add(linkTo(
methodOn(MgmtDistributionSetTagRestApi.class).getAssignedDistributionSets(distributionSetTag.getId()))
@@ -94,20 +96,22 @@ final class MgmtTagMapper {
return response;
}
static List<TargetTag> mapTargeTagFromRequest(final Iterable<MgmtTagRequestBodyPut> tags) {
static List<TargetTag> mapTargeTagFromRequest(final EntityFactory entityFactory,
final Iterable<MgmtTagRequestBodyPut> tags) {
final List<TargetTag> mappedList = new ArrayList<>();
for (final MgmtTagRequestBodyPut targetTagRest : tags) {
mappedList.add(
new TargetTag(targetTagRest.getName(), targetTagRest.getDescription(), targetTagRest.getColour()));
mappedList.add(entityFactory.generateTargetTag(targetTagRest.getName(), targetTagRest.getDescription(),
targetTagRest.getColour()));
}
return mappedList;
}
static List<DistributionSetTag> mapDistributionSetTagFromRequest(final Iterable<MgmtTagRequestBodyPut> tags) {
static List<DistributionSetTag> mapDistributionSetTagFromRequest(final EntityFactory entityFactory,
final Iterable<MgmtTagRequestBodyPut> tags) {
final List<DistributionSetTag> mappedList = new ArrayList<>();
for (final MgmtTagRequestBodyPut targetTagRest : tags) {
mappedList.add(new DistributionSetTag(targetTagRest.getName(), targetTagRest.getDescription(),
targetTagRest.getColour()));
mappedList.add(entityFactory.generateDistributionSetTag(targetTagRest.getName(),
targetTagRest.getDescription(), targetTagRest.getColour()));
}
return mappedList;
}

View File

@@ -25,10 +25,11 @@ import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTargetRequestBody;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetRestApi;
import org.eclipse.hawkbit.repository.ActionFields;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.ActionStatus;
import org.eclipse.hawkbit.repository.model.PollStatus;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetInfo.PollStatus;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.rest.data.SortDirection;
@@ -168,16 +169,17 @@ public final class MgmtTargetMapper {
return targetRest;
}
static List<Target> fromRequest(final Iterable<MgmtTargetRequestBody> targetsRest) {
static List<Target> fromRequest(final EntityFactory entityFactory,
final Iterable<MgmtTargetRequestBody> targetsRest) {
final List<Target> mappedList = new ArrayList<>();
for (final MgmtTargetRequestBody targetRest : targetsRest) {
mappedList.add(fromRequest(targetRest));
mappedList.add(fromRequest(entityFactory, targetRest));
}
return mappedList;
}
static Target fromRequest(final MgmtTargetRequestBody targetRest) {
final Target target = new Target(targetRest.getControllerId());
static Target fromRequest(final EntityFactory entityFactory, final MgmtTargetRequestBody targetRest) {
final Target target = entityFactory.generateTarget(targetRest.getControllerId());
target.setDescription(targetRest.getDescription());
target.setName(targetRest.getName());
return target;

View File

@@ -26,18 +26,16 @@ import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTargetRequestBody;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetRestApi;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetRestApi;
import org.eclipse.hawkbit.repository.ActionFields;
import org.eclipse.hawkbit.repository.ActionStatusFields;
import org.eclipse.hawkbit.repository.DeploymentManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.TargetFields;
import org.eclipse.hawkbit.repository.TargetManagement;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.ActionType;
import org.eclipse.hawkbit.repository.model.ActionStatus;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.rsql.RSQLUtility;
import org.eclipse.hawkbit.rest.data.SortDirection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -46,7 +44,6 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
@@ -67,6 +64,9 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
@Autowired
private DeploymentManagement deploymentManagement;
@Autowired
private EntityFactory entityFactory;
@Override
public ResponseEntity<MgmtTarget> getTarget(@PathVariable("targetId") final String targetId) {
final Target findTarget = findTargetWithExceptionIfNotFound(targetId);
@@ -93,8 +93,7 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
final Slice<Target> findTargetsAll;
final Long countTargetsAll;
if (rsqlParam != null) {
final Page<Target> findTargetPage = this.targetManagement
.findTargetsAll(RSQLUtility.parse(rsqlParam, TargetFields.class), pageable);
final Page<Target> findTargetPage = this.targetManagement.findTargetsAll(rsqlParam, pageable);
countTargetsAll = findTargetPage.getTotalElements();
findTargetsAll = findTargetPage;
} else {
@@ -110,7 +109,7 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
public ResponseEntity<List<MgmtTarget>> createTargets(@RequestBody final List<MgmtTargetRequestBody> targets) {
LOG.debug("creating {} targets", targets.size());
final Iterable<Target> createdTargets = this.targetManagement
.createTargets(MgmtTargetMapper.fromRequest(targets));
.createTargets(MgmtTargetMapper.fromRequest(entityFactory, targets));
LOG.debug("{} targets created, return status {}", targets.size(), HttpStatus.CREATED);
return new ResponseEntity<>(MgmtTargetMapper.toResponse(createdTargets), HttpStatus.CREATED);
}
@@ -170,9 +169,8 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
final Slice<Action> activeActions;
final Long totalActionCount;
if (rsqlParam != null) {
final Specification<Action> parse = RSQLUtility.parse(rsqlParam, ActionFields.class);
activeActions = this.deploymentManagement.findActionsByTarget(parse, foundTarget, pageable);
totalActionCount = this.deploymentManagement.countActionsByTarget(parse, foundTarget);
activeActions = this.deploymentManagement.findActionsByTarget(rsqlParam, foundTarget, pageable);
totalActionCount = this.deploymentManagement.countActionsByTarget(rsqlParam, foundTarget);
} else {
activeActions = this.deploymentManagement.findActionsByTarget(foundTarget, pageable);
totalActionCount = this.deploymentManagement.countActionsByTarget(foundTarget);
@@ -250,8 +248,8 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeActionStatusSortParam(sortParam);
final Page<ActionStatus> statusList = this.deploymentManagement.findActionStatusByAction(
new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting), action, true);
final Page<ActionStatus> statusList = this.deploymentManagement.findActionStatusByActionWithMessages(
new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting), action);
return new ResponseEntity<>(
new PagedList<>(MgmtTargetMapper.toActionStatusRestResponse(statusList.getContent()),

View File

@@ -19,15 +19,14 @@ import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTargetTagAssigmentResult;
import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTarget;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetTagRestApi;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.TagFields;
import org.eclipse.hawkbit.repository.TagManagement;
import org.eclipse.hawkbit.repository.TargetManagement;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetTag;
import org.eclipse.hawkbit.repository.model.TargetTagAssignmentResult;
import org.eclipse.hawkbit.repository.rsql.RSQLUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -56,6 +55,9 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
@Autowired
private TargetManagement targetManagement;
@Autowired
private EntityFactory entityFactory;
@Override
public ResponseEntity<PagedList<MgmtTag>> getTargetTags(
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam,
@@ -75,8 +77,7 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
countTargetsAll = this.tagManagement.countTargetTags();
} else {
final Page<TargetTag> findTargetPage = this.tagManagement
.findAllTargetTags(RSQLUtility.parse(rsqlParam, TagFields.class), pageable);
final Page<TargetTag> findTargetPage = this.tagManagement.findAllTargetTags(rsqlParam, pageable);
countTargetsAll = findTargetPage.getTotalElements();
findTargetsAll = findTargetPage;
@@ -96,7 +97,7 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
public ResponseEntity<List<MgmtTag>> createTargetTags(@RequestBody final List<MgmtTagRequestBodyPut> tags) {
LOG.debug("creating {} target tags", tags.size());
final List<TargetTag> createdTargetTags = this.tagManagement
.createTargetTags(MgmtTagMapper.mapTargeTagFromRequest(tags));
.createTargetTags(MgmtTagMapper.mapTargeTagFromRequest(entityFactory, tags));
return new ResponseEntity<>(MgmtTagMapper.toResponse(createdTargetTags), HttpStatus.CREATED);
}

View File

@@ -26,16 +26,15 @@ import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.hawkbit.TestDataUtil;
import org.eclipse.hawkbit.WithUser;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetMetadata;
import org.eclipse.hawkbit.repository.model.DsMetadataCompositeKey;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.util.TestdataFactory;
import org.eclipse.hawkbit.repository.util.WithUser;
import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
@@ -61,8 +60,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
@Description("This test verifies the call of all Software Modules that are assiged to a Distribution Set through the RESTful API.")
public void getSoftwaremodules() throws Exception {
// Create DistributionSet with three software modules
final DistributionSet set = TestDataUtil.generateDistributionSet("SMTest", softwareManagement,
distributionSetManagement);
final DistributionSet set = testdataFactory.createDistributionSet("SMTest");
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath("$.size", equalTo(set.getModules().size())));
@@ -73,10 +71,9 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
public void deleteFailureWhenDistributionSetInUse() throws Exception {
// create DisSet
final DistributionSet disSet = TestDataUtil.generateDistributionSetWithNoSoftwareModules("Eris", "560a",
distributionSetManagement);
final List<Long> smIDs = new ArrayList<Long>();
SoftwareModule sm = new SoftwareModule(osType, "Dysnomia ", "15,772", null, null);
final DistributionSet disSet = testdataFactory.createDistributionSetWithNoSoftwareModules("Eris", "560a");
final List<Long> smIDs = new ArrayList<>();
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "Dysnomia ", "15,772", null, null);
sm = softwareManagement.createSoftwareModule(sm);
smIDs.add(sm.getId());
final JSONArray smList = new JSONArray();
@@ -92,7 +89,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final String[] knownTargetIds = new String[] { "1", "2" };
final JSONArray list = new JSONArray();
for (final String targetId : knownTargetIds) {
targetManagement.createTarget(new Target(targetId));
targetManagement.createTarget(entityFactory.generateTarget(targetId));
list.put(new JSONObject().put("id", Long.valueOf(targetId)));
}
deploymentManagement.assignDistributionSet(disSet.getId(), knownTargetIds[0]);
@@ -117,10 +114,9 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
public void assignmentFailureWhenAssigningToUsedDistributionSet() throws Exception {
// create DisSet
final DistributionSet disSet = TestDataUtil.generateDistributionSetWithNoSoftwareModules("Mars", "686,980",
distributionSetManagement);
final DistributionSet disSet = testdataFactory.createDistributionSetWithNoSoftwareModules("Mars", "686,980");
final List<Long> smIDs = new ArrayList<>();
SoftwareModule sm = new SoftwareModule(osType, "Phobos", "0,3189", null, null);
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "Phobos", "0,3189", null, null);
sm = softwareManagement.createSoftwareModule(sm);
smIDs.add(sm.getId());
final JSONArray smList = new JSONArray();
@@ -136,7 +132,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final String[] knownTargetIds = new String[] { "1", "2" };
final JSONArray list = new JSONArray();
for (final String targetId : knownTargetIds) {
targetManagement.createTarget(new Target(targetId));
targetManagement.createTarget(entityFactory.generateTarget(targetId));
list.put(new JSONObject().put("id", Long.valueOf(targetId)));
}
// assign DisSet to target and test assignment
@@ -150,8 +146,8 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
.andExpect(jsonPath("$.total", equalTo(knownTargetIds.length)));
// Create another SM and post assignment
final List<Long> smID2s = new ArrayList<Long>();
SoftwareModule sm2 = new SoftwareModule(appType, "Deimos", "1,262", null, null);
final List<Long> smID2s = new ArrayList<>();
SoftwareModule sm2 = entityFactory.generateSoftwareModule(appType, "Deimos", "1,262", null, null);
sm2 = softwareManagement.createSoftwareModule(sm2);
smID2s.add(sm2.getId());
final JSONArray smList2 = new JSONArray();
@@ -170,21 +166,20 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
public void assignSoftwaremoduleToDistributionSet() throws Exception {
// create DisSet
final DistributionSet disSet = TestDataUtil.generateDistributionSetWithNoSoftwareModules("Jupiter", "398,88",
distributionSetManagement);
final DistributionSet disSet = testdataFactory.createDistributionSetWithNoSoftwareModules("Jupiter", "398,88");
// Test if size is 0
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath("$.size", equalTo(disSet.getModules().size())));
// create Software Modules
final List<Long> smIDs = new ArrayList<Long>();
SoftwareModule sm = new SoftwareModule(osType, "Europa", "3,551", null, null);
final List<Long> smIDs = new ArrayList<>();
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "Europa", "3,551", null, null);
sm = softwareManagement.createSoftwareModule(sm);
smIDs.add(sm.getId());
SoftwareModule sm2 = new SoftwareModule(appType, "Ganymed", "7,155", null, null);
SoftwareModule sm2 = entityFactory.generateSoftwareModule(appType, "Ganymed", "7,155", null, null);
sm2 = softwareManagement.createSoftwareModule(sm2);
smIDs.add(sm2.getId());
SoftwareModule sm3 = new SoftwareModule(runtimeType, "Kallisto", "16,689", null, null);
SoftwareModule sm3 = entityFactory.generateSoftwareModule(runtimeType, "Kallisto", "16,689", null, null);
sm3 = softwareManagement.createSoftwareModule(sm3);
smIDs.add(sm3.getId());
final JSONArray list = new JSONArray();
@@ -206,8 +201,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
public void unassignSoftwaremoduleFromDistributionSet() throws Exception {
// Create DistributionSet with three software modules
final DistributionSet set = TestDataUtil.generateDistributionSet("Venus", softwareManagement,
distributionSetManagement);
final DistributionSet set = testdataFactory.createDistributionSet("Venus");
int amountOfSM = set.getModules().size();
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
@@ -234,7 +228,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final String[] knownTargetIds = new String[] { "1", "2", "3", "4", "5" };
final JSONArray list = new JSONArray();
for (final String targetId : knownTargetIds) {
targetManagement.createTarget(new Target(targetId));
targetManagement.createTarget(entityFactory.generateTarget(targetId));
list.put(new JSONObject().put("id", Long.valueOf(targetId)));
}
// assign already one target to DS
@@ -258,7 +252,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final String knownTargetId = "knownTargetId1";
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
targetManagement.createTarget(new Target(knownTargetId));
targetManagement.createTarget(entityFactory.generateTarget(knownTargetId));
deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetId);
mvc.perform(get(
@@ -285,15 +279,15 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final String knownTargetId = "knownTargetId1";
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
final Target createTarget = targetManagement.createTarget(new Target(knownTargetId));
final Target createTarget = targetManagement.createTarget(entityFactory.generateTarget(knownTargetId));
// create some dummy targets which are not assigned or installed
targetManagement.createTarget(new Target("dummy1"));
targetManagement.createTarget(new Target("dummy2"));
targetManagement.createTarget(entityFactory.generateTarget("dummy1"));
targetManagement.createTarget(entityFactory.generateTarget("dummy2"));
// assign knownTargetId to distribution set
deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetId);
// make it in install state
TestDataUtil.sendUpdateActionStatusToTargets(controllerManagament, targetManagement, actionRepository,
createdDs, Lists.newArrayList(createTarget), Status.FINISHED, "some message");
testdataFactory.sendUpdateActionStatusToTargets(Lists.newArrayList(createTarget), Status.FINISHED,
"some message");
mvc.perform(get(
MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/installedTargets"))
@@ -348,10 +342,10 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
@Description("Ensures that multiple DS requested are listed with expected payload.")
public void getDistributionSets() throws Exception {
// prepare test data
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
.hasSize(0);
DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
DistributionSet set = testdataFactory.createDistributionSet("one");
set.setRequiredMigrationStep(set.isRequiredMigrationStep());
set = distributionSetManagement.updateDistributionSet(set);
@@ -361,7 +355,8 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
// load also lazy stuff
set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId());
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
.hasSize(1);
// perform request
mvc.perform(get("/rest/v1/distributionsets").accept(MediaType.APPLICATION_JSON))
@@ -392,8 +387,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Ensures that single DS requested by ID is listed with expected payload.")
public void getDistributionSet() throws Exception {
final DistributionSet set = TestDataUtil.createTestDistributionSet(softwareManagement,
distributionSetManagement);
final DistributionSet set = testdataFactory.createUpdatedDistributionSet();
// perform request
mvc.perform(get("/rest/v1/distributionsets/{dsId}", set.getId()).accept(MediaType.APPLICATION_JSON))
@@ -425,18 +419,19 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Ensures that multipe DS posted to API are created in the repository.")
public void createDistributionSets() throws JSONException, Exception {
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
.hasSize(0);
final SoftwareModule ah = softwareManagement
.createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, ""));
final SoftwareModule jvm = softwareManagement
.createSoftwareModule(new SoftwareModule(runtimeType, "oracle-jre", "1.7.2", null, ""));
final SoftwareModule os = softwareManagement
.createSoftwareModule(new SoftwareModule(osType, "poky", "3.0.2", null, ""));
final SoftwareModule ah = testdataFactory.createSoftwareModule(TestdataFactory.SM_TYPE_APP);
final SoftwareModule jvm = testdataFactory.createSoftwareModule(TestdataFactory.SM_TYPE_RT);
final SoftwareModule os = testdataFactory.createSoftwareModule(TestdataFactory.SM_TYPE_OS);
DistributionSet one = TestDataUtil.buildDistributionSet("one", "one", standardDsType, os, jvm, ah);
DistributionSet two = TestDataUtil.buildDistributionSet("two", "two", standardDsType, os, jvm, ah);
DistributionSet three = TestDataUtil.buildDistributionSet("three", "three", standardDsType, os, jvm, ah);
DistributionSet one = testdataFactory.generateDistributionSet("one", "one", standardDsType,
Lists.newArrayList(os, jvm, ah));
DistributionSet two = testdataFactory.generateDistributionSet("two", "two", standardDsType,
Lists.newArrayList(os, jvm, ah));
DistributionSet three = testdataFactory.generateDistributionSet("three", "three", standardDsType,
Lists.newArrayList(os, jvm, ah));
three.setRequiredMigrationStep(true);
final List<DistributionSet> sets = new ArrayList<>();
@@ -527,7 +522,8 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
.isEqualTo(String.valueOf(three.getId()));
// check in database
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(3);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
.hasSize(3);
assertThat(one.isRequiredMigrationStep()).isEqualTo(false);
assertThat(two.isRequiredMigrationStep()).isEqualTo(false);
assertThat(three.isRequiredMigrationStep()).isEqualTo(true);
@@ -541,42 +537,47 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
@Description("Ensures that DS deletion request to API is reflected by the repository.")
public void deleteUnassignedistributionSet() throws Exception {
// prepare test data
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
.hasSize(0);
final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
final DistributionSet set = testdataFactory.createDistributionSet("one");
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
.hasSize(1);
// perform request
mvc.perform(delete("/rest/v1/distributionsets/{smId}", set.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
// check repository content
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).isEmpty();
assertThat(distributionSetRepository.findAll()).isEmpty();
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
.isEmpty();
assertThat(distributionSetManagement.countDistributionSetsAll()).isEqualTo(0);
}
@Test
@Description("Ensures that assigned DS deletion request to API is reflected by the repository by means of deleted flag set.")
public void deleteAssignedDistributionSet() throws Exception {
// prepare test data
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
.hasSize(0);
final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
targetManagement.createTarget(new Target("test"));
final DistributionSet set = testdataFactory.createDistributionSet("one");
targetManagement.createTarget(entityFactory.generateTarget("test"));
deploymentManagement.assignDistributionSet(set.getId(), "test");
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
.hasSize(1);
// perform request
mvc.perform(delete("/rest/v1/distributionsets/{smId}", set.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
// check repository content
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, true, true)).hasSize(1);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
.hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, true, true))
.hasSize(1);
}
@Test
@@ -584,14 +585,15 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
public void updateDistributionSet() throws Exception {
// prepare test data
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
.hasSize(0);
final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
final DistributionSet set = testdataFactory.createDistributionSet("one");
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
.hasSize(1);
final DistributionSet update = new DistributionSet();
final DistributionSet update = entityFactory.generateDistributionSet();
update.setVersion("anotherVersion");
update.setName(null);
update.setType(standardDsType);
@@ -600,18 +602,16 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true).getContent().get(0)
.getVersion()).isEqualTo("anotherVersion");
assertThat(
distributionSetManagement.findDistributionSetsAll(pageReq, false, true).getContent().get(0).getName())
.isEqualTo(set.getName());
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)
.getContent().get(0).getVersion()).isEqualTo("anotherVersion");
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)
.getContent().get(0).getName()).isEqualTo(set.getName());
}
@Test
@Description("Ensures that the server reacts properly to invalid requests (URI, Media Type, Methods) with correct reponses.")
public void invalidRequestsOnDistributionSetsResource() throws Exception {
final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
final DistributionSet set = testdataFactory.createDistributionSet("one");
final List<DistributionSet> sets = new ArrayList<>();
sets.add(set);
@@ -652,8 +652,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
@Test
@Description("Ensures that the metadata creation through API is reflected by the repository.")
public void createMetadata() throws Exception {
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
final DistributionSet testDS = testdataFactory.createDistributionSet("one");
final String knownKey1 = "knownKey1";
final String knownKey2 = "knownKey2";
@@ -673,10 +672,8 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
.andExpect(jsonPath("[1]key", equalTo(knownKey2)))
.andExpect(jsonPath("[1]value", equalTo(knownValue2)));
final DistributionSetMetadata metaKey1 = distributionSetManagement
.findOne(new DsMetadataCompositeKey(testDS, knownKey1));
final DistributionSetMetadata metaKey2 = distributionSetManagement
.findOne(new DsMetadataCompositeKey(testDS, knownKey2));
final DistributionSetMetadata metaKey1 = distributionSetManagement.findOne(testDS, knownKey1);
final DistributionSetMetadata metaKey2 = distributionSetManagement.findOne(testDS, knownKey2);
assertThat(metaKey1.getValue()).isEqualTo(knownValue1);
assertThat(metaKey2.getValue()).isEqualTo(knownValue2);
@@ -690,10 +687,9 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final String knownValue = "knownValue";
final String updateValue = "valueForUpdate";
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
distributionSetManagement
.createDistributionSetMetadata(new DistributionSetMetadata(knownKey, testDS, knownValue));
final DistributionSet testDS = testdataFactory.createDistributionSet("one");
distributionSetManagement.createDistributionSetMetadata(
entityFactory.generateDistributionSetMetadata(testDS, knownKey, knownValue));
final JSONObject jsonObject = new JSONObject().put("key", knownKey).put("value", updateValue);
@@ -703,8 +699,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("key", equalTo(knownKey))).andExpect(jsonPath("value", equalTo(updateValue)));
final DistributionSetMetadata assertDS = distributionSetManagement
.findOne(new DsMetadataCompositeKey(testDS, knownKey));
final DistributionSetMetadata assertDS = distributionSetManagement.findOne(testDS, knownKey);
assertThat(assertDS.getValue()).isEqualTo(updateValue);
}
@@ -716,16 +711,15 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final String knownKey = "knownKey";
final String knownValue = "knownValue";
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
distributionSetManagement
.createDistributionSetMetadata(new DistributionSetMetadata(knownKey, testDS, knownValue));
final DistributionSet testDS = testdataFactory.createDistributionSet("one");
distributionSetManagement.createDistributionSetMetadata(
entityFactory.generateDistributionSetMetadata(testDS, knownKey, knownValue));
mvc.perform(delete("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
try {
distributionSetManagement.findOne(new DsMetadataCompositeKey(testDS, knownKey));
distributionSetManagement.findOne(testDS, knownKey);
fail("expected EntityNotFoundException but didn't throw");
} catch (final EntityNotFoundException e) {
// ok as expected
@@ -738,10 +732,9 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
// prepare and create metadata
final String knownKey = "knownKey";
final String knownValue = "knownValue";
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
distributionSetManagement
.createDistributionSetMetadata(new DistributionSetMetadata(knownKey, testDS, knownValue));
final DistributionSet testDS = testdataFactory.createDistributionSet("one");
distributionSetManagement.createDistributionSetMetadata(
entityFactory.generateDistributionSetMetadata(testDS, knownKey, knownValue));
mvc.perform(get("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
@@ -757,11 +750,11 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final String offsetParam = "0";
final String knownKeyPrefix = "knownKey";
final String knownValuePrefix = "knownValue";
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
final DistributionSet testDS = testdataFactory.createDistributionSet("one");
for (int index = 0; index < totalMetadata; index++) {
distributionSetManagement.createDistributionSetMetadata(new DistributionSetMetadata(knownKeyPrefix + index,
distributionSetManagement.findDistributionSetById(testDS.getId()), knownValuePrefix + index));
distributionSetManagement.createDistributionSetMetadata(entityFactory.generateDistributionSetMetadata(
distributionSetManagement.findDistributionSetById(testDS.getId()), knownKeyPrefix + index,
knownValuePrefix + index));
}
mvc.perform(get("/rest/v1/distributionsets/{dsId}/metadata?offset=" + offsetParam + "&limit=" + limitParam,
@@ -777,9 +770,9 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
public void searchDistributionSetRsql() throws Exception {
final String dsSuffix = "test";
final int amount = 10;
TestDataUtil.generateDistributionSets(dsSuffix, amount, softwareManagement, distributionSetManagement);
TestDataUtil.generateDistributionSet("DS1test", softwareManagement, distributionSetManagement);
TestDataUtil.generateDistributionSet("DS2test", softwareManagement, distributionSetManagement);
testdataFactory.createDistributionSets(dsSuffix, amount);
testdataFactory.createDistributionSet("DS1test");
testdataFactory.createDistributionSet("DS2test");
final String rsqlFindLikeDs1OrDs2 = "name==DS1test,name==DS2test";
@@ -794,9 +787,9 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
@Description("Ensures that a DS search with complete==true parameter returns only DS that are actually completely filled with mandatory modules.")
public void filterDistributionSetComplete() throws Exception {
final int amount = 10;
TestDataUtil.generateDistributionSets(amount, softwareManagement, distributionSetManagement);
distributionSetManagement.createDistributionSet(new DistributionSet("incomplete", "2", "incomplete",
distributionSetManagement.findDistributionSetTypeByKey("ecl_os"), null));
testdataFactory.createDistributionSets(amount);
distributionSetManagement.createDistributionSet(entityFactory.generateDistributionSet("incomplete", "2",
"incomplete", distributionSetManagement.findDistributionSetTypeByKey("os"), null));
final String rsqlFindLikeDs1OrDs2 = "complete==" + Boolean.TRUE;
@@ -815,7 +808,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final String[] knownTargetIds = new String[] { "1", "2", "3", "4", "5" };
final JSONArray list = new JSONArray();
for (final String targetId : knownTargetIds) {
targetManagement.createTarget(new Target(targetId));
targetManagement.createTarget(entityFactory.generateTarget(targetId));
list.put(new JSONObject().put("id", Long.valueOf(targetId)));
}
@@ -837,11 +830,11 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final int totalMetadata = 10;
final String knownKeyPrefix = "knownKey";
final String knownValuePrefix = "knownValue";
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
final DistributionSet testDS = testdataFactory.createDistributionSet("one");
for (int index = 0; index < totalMetadata; index++) {
distributionSetManagement.createDistributionSetMetadata(new DistributionSetMetadata(knownKeyPrefix + index,
distributionSetManagement.findDistributionSetById(testDS.getId()), knownValuePrefix + index));
distributionSetManagement.createDistributionSetMetadata(entityFactory.generateDistributionSetMetadata(
distributionSetManagement.findDistributionSetById(testDS.getId()), knownKeyPrefix + index,
knownValuePrefix + index));
}
final String rsqlSearchValue1 = "value==knownValue1";
@@ -857,7 +850,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final Set<DistributionSet> created = new HashSet<>();
for (int index = 0; index < amount; index++) {
final String str = String.valueOf(character);
created.add(TestDataUtil.generateDistributionSet(str, softwareManagement, distributionSetManagement));
created.add(testdataFactory.createDistributionSet(str));
character++;
}
return created;

View File

@@ -23,12 +23,11 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import java.util.ArrayList;
import java.util.List;
import org.eclipse.hawkbit.WithUser;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.util.WithUser;
import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
@@ -58,11 +57,13 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests.")
public void getDistributionSetTypes() throws Exception {
DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
DistributionSetType testType = distributionSetManagement.createDistributionSetType(
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123"));
testType.setDescription("Desc1234");
testType = distributionSetManagement.updateDistributionSetType(testType);
// 4 types overall (2 hawkbit tenant default, 1 test default and 1
// generated in this test)
mvc.perform(get("/rest/v1/distributionsettypes").accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
@@ -96,8 +97,8 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests with sorting by KEY.")
public void getDistributionSetTypesSortedByKey() throws Exception {
DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("zzzzz", "TestName123", "Desc123"));
DistributionSetType testType = distributionSetManagement.createDistributionSetType(
entityFactory.generateDistributionSetType("zzzzz", "TestName123", "Desc123"));
testType.setDescription("Desc1234");
testType = distributionSetManagement.updateDistributionSetType(testType);
@@ -112,7 +113,8 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
.andExpect(jsonPath("$content.[0].createdAt", equalTo(testType.getCreatedAt())))
.andExpect(jsonPath("$content.[0].lastModifiedBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[0].lastModifiedAt", equalTo(testType.getLastModifiedAt())))
.andExpect(jsonPath("$content.[0].key", equalTo("zzzzz"))).andExpect(jsonPath("$total", equalTo(4)));
.andExpect(jsonPath("$content.[0].key", equalTo("zzzzz")))
.andExpect(jsonPath("$total", equalTo(DEFAULT_DS_TYPES + 1)));
// ascending
mvc.perform(get("/rest/v1/distributionsettypes").accept(MediaType.APPLICATION_JSON)
@@ -125,7 +127,8 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
.andExpect(jsonPath("$content.[3].createdAt", equalTo(testType.getCreatedAt())))
.andExpect(jsonPath("$content.[3].lastModifiedBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[3].lastModifiedAt", equalTo(testType.getLastModifiedAt())))
.andExpect(jsonPath("$content.[3].key", equalTo("zzzzz"))).andExpect(jsonPath("$total", equalTo(4)));
.andExpect(jsonPath("$content.[3].key", equalTo("zzzzz")))
.andExpect(jsonPath("$total", equalTo(DEFAULT_DS_TYPES + 1)));
}
@Test
@@ -133,15 +136,15 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes POST requests.")
public void createDistributionSetTypes() throws JSONException, Exception {
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(3);
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES);
final List<DistributionSetType> types = new ArrayList<>();
types.add(new DistributionSetType("test1", "TestName1", "Desc1").addMandatoryModuleType(osType)
.addOptionalModuleType(runtimeType));
types.add(new DistributionSetType("test2", "TestName2", "Desc2").addOptionalModuleType(osType)
.addOptionalModuleType(runtimeType).addOptionalModuleType(appType));
types.add(new DistributionSetType("test3", "TestName3", "Desc3").addMandatoryModuleType(osType)
.addMandatoryModuleType(runtimeType));
types.add(entityFactory.generateDistributionSetType("test1", "TestName1", "Desc1")
.addMandatoryModuleType(osType).addOptionalModuleType(runtimeType));
types.add(entityFactory.generateDistributionSetType("test2", "TestName2", "Desc2")
.addOptionalModuleType(osType).addOptionalModuleType(runtimeType).addOptionalModuleType(appType));
types.add(entityFactory.generateDistributionSetType("test3", "TestName3", "Desc3")
.addMandatoryModuleType(osType).addMandatoryModuleType(runtimeType));
final MvcResult mvcResult = mvc
.perform(post("/rest/v1/distributionsettypes/").content(JsonBuilder.distributionSetTypes(types))
@@ -205,8 +208,8 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes POST requests.")
public void addMandatoryModuleToDistributionSetType() throws JSONException, Exception {
DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
DistributionSetType testType = distributionSetManagement.createDistributionSetType(
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123"));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
mvc.perform(post("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes", testType.getId())
@@ -224,8 +227,8 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes POST requests.")
public void addOptionalModuleToDistributionSetType() throws JSONException, Exception {
DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
DistributionSetType testType = distributionSetManagement.createDistributionSetType(
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123"));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
mvc.perform(post("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes", testType.getId())
@@ -244,8 +247,8 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes GET requests.")
public void getMandatoryModulesOfDistributionSetType() throws JSONException, Exception {
final DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
final DistributionSetType testType = distributionSetManagement.createDistributionSetType(
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
@@ -263,8 +266,8 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes GET requests.")
public void getOptionalModulesOfDistributionSetType() throws JSONException, Exception {
final DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
final DistributionSetType testType = distributionSetManagement.createDistributionSetType(
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
@@ -275,7 +278,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("[0].name", equalTo(appType.getName())))
.andExpect(jsonPath("[0].description", equalTo(appType.getDescription())))
.andExpect(jsonPath("[0].maxAssignments", equalTo(1)))
.andExpect(jsonPath("[0].maxAssignments", equalTo(Integer.MAX_VALUE)))
.andExpect(jsonPath("[0].key", equalTo("application")));
}
@@ -283,8 +286,8 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes/{ID} GET requests.")
public void getMandatoryModuleOfDistributionSetType() throws JSONException, Exception {
final DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
final DistributionSetType testType = distributionSetManagement.createDistributionSetType(
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
@@ -305,8 +308,8 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes/{ID} GET requests.")
public void getOptionalModuleOfDistributionSetType() throws JSONException, Exception {
final DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
final DistributionSetType testType = distributionSetManagement.createDistributionSetType(
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
@@ -327,8 +330,8 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes/{ID} DELETE requests.")
public void removeMandatoryModuleToDistributionSetType() throws JSONException, Exception {
DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
DistributionSetType testType = distributionSetManagement.createDistributionSetType(
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
@@ -349,8 +352,8 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes/{ID} DELETE requests.")
public void removeOptionalModuleToDistributionSetType() throws JSONException, Exception {
DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
DistributionSetType testType = distributionSetManagement.createDistributionSetType(
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
@@ -372,8 +375,8 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID} GET requests.")
public void getDistributionSetType() throws Exception {
DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
DistributionSetType testType = distributionSetManagement.createDistributionSetType(
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123"));
testType.setDescription("Desc1234");
testType = distributionSetManagement.updateDistributionSetType(testType);
@@ -391,41 +394,41 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/DistributionSetTypes/{ID} DELETE requests (hard delete scenario).")
public void deleteDistributionSetTypeUnused() throws Exception {
final DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
final DistributionSetType testType = distributionSetManagement.createDistributionSetType(
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123"));
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(4);
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES + 1);
mvc.perform(delete("/rest/v1/distributionsettypes/{dsId}", testType.getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(3);
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES);
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/DistributionSetTypes/{ID} DELETE requests (soft delete scenario).")
public void deleteDistributionSetTypeUsed() throws Exception {
final DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
distributionSetManagement
.createDistributionSet(new DistributionSet("sdfsd", "dsfsdf", "sdfsdf", testType, null));
final DistributionSetType testType = distributionSetManagement.createDistributionSetType(
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123"));
distributionSetManagement.createDistributionSet(
entityFactory.generateDistributionSet("sdfsd", "dsfsdf", "sdfsdf", testType, null));
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(4);
assertThat(distributionSetTypeRepository.count()).isEqualTo(4);
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES + 1);
assertThat(distributionSetManagement.countDistributionSetsAll()).isEqualTo(1);
mvc.perform(delete("/rest/v1/distributionsettypes/{smId}", testType.getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(distributionSetTypeRepository.count()).isEqualTo(4);
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(3);
assertThat(distributionSetManagement.countDistributionSetsAll()).isEqualTo(1);
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES);
}
@Test
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID} PUT requests.")
public void updateDistributionSetTypeOnlyDescriptionAndNameUntouched() throws Exception {
final DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
final DistributionSetType testType = distributionSetManagement.createDistributionSetType(
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123"));
final String body = new JSONObject().put("id", testType.getId()).put("description", "foobardesc")
.put("name", "nameShouldNotBeChanged").toString();
@@ -440,6 +443,8 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@Test
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests with paging.")
public void getDistributionSetTypesWithoutAddtionalRequestParameters() throws Exception {
// 3 types overall (2 hawkbit tenant default, 1 test default
final int types = 3;
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk())
@@ -451,7 +456,8 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@Test
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests with paging.")
public void getDistributionSetTypesWithPagingLimitRequestParameter() throws Exception {
final int types = 3;
final int types = DEFAULT_DS_TYPES;
final int limitSize = 1;
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_REQUEST_MAPPING)
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize)))
@@ -464,7 +470,8 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@Test
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests with paging.")
public void getDistributionSetTypesWithPagingLimitAndOffsetRequestParameter() throws Exception {
final int types = 3;
final int types = DEFAULT_DS_TYPES;
final int offsetParam = 2;
final int expectedSize = types - offsetParam;
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_REQUEST_MAPPING)
@@ -479,11 +486,11 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@Test
@Description("Ensures that the server is behaving as expected on invalid requests (wrong media type, wrong ID etc.).")
public void invalidRequestsOnDistributionSetTypesResource() throws Exception {
final DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
final DistributionSetType testType = distributionSetManagement.createDistributionSetType(
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123"));
final SoftwareModuleType testSmType = softwareManagement
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
final SoftwareModuleType testSmType = softwareManagement.createSoftwareModuleType(
entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5));
final List<DistributionSetType> types = new ArrayList<>();
types.add(testType);
@@ -526,8 +533,10 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
// Modules types at creation time invalid
final DistributionSetType testNewType = new DistributionSetType("test123", "TestName123", "Desc123");
testNewType.addMandatoryModuleType(new SoftwareModuleType("foo", "bar", "test", Integer.MAX_VALUE));
final DistributionSetType testNewType = entityFactory.generateDistributionSetType("test123",
"TestName123", "Desc123");
testNewType.addMandatoryModuleType(
entityFactory.generateSoftwareModuleType("foo", "bar", "test", Integer.MAX_VALUE));
mvc.perform(post("/rest/v1/distributionsettypes")
.content(JsonBuilder.distributionSetTypes(Lists.newArrayList(testNewType)))
@@ -560,10 +569,10 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@Test
@Description("Search erquest of software module types.")
public void searchDistributionSetTypeRsql() throws Exception {
final DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
final DistributionSetType testType2 = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test1234", "TestName1234", "Desc123"));
final DistributionSetType testType = distributionSetManagement.createDistributionSetType(
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123"));
final DistributionSetType testType2 = distributionSetManagement.createDistributionSetType(
entityFactory.generateDistributionSetType("test1234", "TestName1234", "Desc123"));
final String rsqlFindLikeDs1OrDs2 = "name==TestName123,name==TestName1234";
@@ -577,7 +586,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
char character = 'a';
for (int index = 0; index < amount; index++) {
final String str = String.valueOf(character);
final SoftwareModule softwareModule = new SoftwareModule(osType, str, str, str, str);
final SoftwareModule softwareModule = entityFactory.generateSoftwareModule(osType, str, str, str, str);
softwareManagement.createSoftwareModule(softwareModule);
character++;

View File

@@ -11,7 +11,6 @@ package org.eclipse.hawkbit.mgmt.rest.resource;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.eclipse.hawkbit.TestDataUtil;
import org.eclipse.hawkbit.cache.CacheConstants;
import org.eclipse.hawkbit.cache.DownloadArtifactCache;
import org.eclipse.hawkbit.cache.DownloadType;
@@ -46,11 +45,9 @@ public class MgmtDownloadResourceTest extends AbstractRestIntegrationTestWithMon
@Before
public void setupCache() {
final DistributionSet distributionSet = TestDataUtil.generateDistributionSet("Test", softwareManagement,
distributionSetManagement);
final DistributionSet distributionSet = testdataFactory.createDistributionSet("Test");
final SoftwareModule softwareModule = distributionSet.getModules().stream().findFirst().get();
final Artifact artifact = TestDataUtil.generateArtifacts(artifactManagement, softwareModule.getId()).stream()
.findFirst().get();
final Artifact artifact = testdataFactory.createLocalArtifacts(softwareModule.getId()).stream().findFirst().get();
downloadIdCache.put(downloadIdSha1, new DownloadArtifactCache(DownloadType.BY_SHA1, artifact.getSha1Hash()));
}

View File

@@ -21,8 +21,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import java.util.List;
import java.util.concurrent.Callable;
import org.eclipse.hawkbit.TestDataUtil;
import org.eclipse.hawkbit.WithUser;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.RolloutGroupManagement;
import org.eclipse.hawkbit.repository.RolloutManagement;
@@ -30,8 +28,9 @@ import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.Rollout;
import org.eclipse.hawkbit.repository.model.Rollout.RolloutStatus;
import org.eclipse.hawkbit.repository.model.RolloutGroup;
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupConditionBuilder;
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessCondition;
import org.eclipse.hawkbit.repository.util.WithUser;
import org.eclipse.hawkbit.repository.model.RolloutGroupConditionBuilder;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
@@ -73,8 +72,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
@Description("Testing that creating rollout with insufficient permission returns forbidden")
@WithUser(allSpPermissions = true, removeFromAllPermission = "ROLLOUT_MANAGEMENT")
public void createRolloutWithInsufficientPermissionReturnsForbidden() throws Exception {
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet dsA = testdataFactory.createDistributionSet("");
mvc.perform(post("/rest/v1/rollouts")
.content(JsonBuilder.rollout("name", "desc", 10, dsA.getId(), "name==test", null))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
@@ -92,8 +90,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
@Test
@Description("Testing that creating rollout with not valid formed target filter query returns bad request")
public void createRolloutWithNotWellFormedFilterReturnsBadRequest() throws Exception {
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet dsA = testdataFactory.createDistributionSet("");
mvc.perform(post("/rest/v1/rollouts")
.content(JsonBuilder.rollout("name", "desc", 10, dsA.getId(), "name=test", null))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
@@ -107,8 +104,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
final String targetFilterQuery = null;
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet dsA = testdataFactory.createDistributionSet("");
mvc.perform(post("/rest/v1/rollouts")
.content(JsonBuilder.rollout("rollout1", "desc", 10, dsA.getId(), targetFilterQuery, null))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
@@ -121,8 +117,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
@Test
@Description("Testing that rollout can be created")
public void createRollout() throws Exception {
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet dsA = testdataFactory.createDistributionSet("");
postRollout("rollout1", 10, dsA.getId(), "name==target1");
}
@@ -137,8 +132,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
@Test
@Description("Testing that rollout paged list contains rollouts")
public void rolloutPagedListContainsAllRollouts() throws Exception {
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet dsA = testdataFactory.createDistributionSet("");
// setup - create 2 rollouts
postRollout("rollout1", 10, dsA.getId(), "name==target1");
postRollout("rollout2", 5, dsA.getId(), "name==target2");
@@ -159,8 +153,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
@Test
@Description("Testing that rollout paged list is limited by the query param limit")
public void rolloutPagedListIsLimitedToQueryParam() throws Exception {
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet dsA = testdataFactory.createDistributionSet("");
// setup - create 2 rollouts
postRollout("rollout1", 10, dsA.getId(), "name==target1");
postRollout("rollout2", 5, dsA.getId(), "name==target2");
@@ -175,9 +168,8 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void retrieveRolloutGroupsForSpecificRollout() throws Exception {
// setup
final int amountTargets = 20;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
@@ -198,9 +190,8 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void startingRolloutSwitchesIntoRunningState() throws Exception {
// setup
final int amountTargets = 20;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
@@ -221,9 +212,8 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void pausingRolloutSwitchesIntoPausedState() throws Exception {
// setup
final int amountTargets = 20;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
@@ -248,9 +238,8 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void resumingRolloutSwitchesIntoRunningState() throws Exception {
// setup
final int amountTargets = 20;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
@@ -279,9 +268,8 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void startingAlreadyStartedRolloutReturnsBadRequest() throws Exception {
// setup
final int amountTargets = 20;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
@@ -301,9 +289,8 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void resumingNotStartedRolloutReturnsBadRequest() throws Exception {
// setup
final int amountTargets = 20;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
@@ -319,9 +306,8 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void startingRolloutFirstRolloutGroupIsInRunningState() throws Exception {
// setup
final int amountTargets = 10;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 2, dsA.getId(), "controllerId==rollout*");
@@ -345,9 +331,8 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void retrieveSingleRolloutGroup() throws Exception {
// setup
final int amountTargets = 10;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
@@ -369,9 +354,8 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void retrieveTargetsFromRolloutGroup() throws Exception {
// setup
final int amountTargets = 10;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 2, dsA.getId(), "controllerId==rollout*");
@@ -393,9 +377,8 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
// setup
final int amountTargets = 10;
final List<Target> targets = targetManagement
.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 2, dsA.getId(), "controllerId==rollout*");
@@ -418,9 +401,8 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void retrieveTargetsFromRolloutGroupAfterRolloutIsStarted() throws Exception {
// setup
final int amountTargets = 10;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 2, dsA.getId(), "controllerId==rollout*");
@@ -443,9 +425,8 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void startingRolloutSwitchesIntoRunningStateAsync() throws Exception {
final int amountTargets = 1000;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
@@ -468,12 +449,14 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
final int amountTargetsRollout2 = 25;
final int amountTargetsRollout3 = 25;
final int amountTargetsOther = 25;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargetsRollout1, "rollout1", "rollout1"));
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargetsRollout2, "rollout2", "rollout2"));
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargetsRollout3, "rollout3", "rollout3"));
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargetsOther, "other1", "other1"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
targetManagement
.createTargets(testdataFactory.generateTargets(amountTargetsRollout1, "rollout1", "rollout1"));
targetManagement
.createTargets(testdataFactory.generateTargets(amountTargetsRollout2, "rollout2", "rollout2"));
targetManagement
.createTargets(testdataFactory.generateTargets(amountTargetsRollout3, "rollout3", "rollout3"));
targetManagement.createTargets(testdataFactory.generateTargets(amountTargetsOther, "other1", "other1"));
final DistributionSet dsA = testdataFactory.createDistributionSet("");
createRollout("rollout1", 5, dsA.getId(), "controllerId==rollout1*");
final Rollout rollout2 = createRollout("rollout2", 5, dsA.getId(), "controllerId==rollout2*");
@@ -503,9 +486,8 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void retrieveRolloutGroupsForSpecificRolloutWithRSQLParam() throws Exception {
// setup
final int amountTargets = 20;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
@@ -577,7 +559,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
private Rollout createRollout(final String name, final int amountGroups, final long distributionSetId,
final String targetFilterQuery) {
final Rollout rollout = new Rollout();
final Rollout rollout = entityFactory.generateRollout();
rollout.setDistributionSet(distributionSetManagement.findDistributionSetById(distributionSetId));
rollout.setName(name);
rollout.setTargetFilterQuery(targetFilterQuery);

View File

@@ -32,9 +32,6 @@ import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.eclipse.hawkbit.HashGeneratorUtils;
import org.eclipse.hawkbit.TestDataUtil;
import org.eclipse.hawkbit.WithUser;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
@@ -44,7 +41,8 @@ import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.LocalArtifact;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata;
import org.eclipse.hawkbit.repository.model.SwMetadataCompositeKey;
import org.eclipse.hawkbit.repository.util.HashGeneratorUtils;
import org.eclipse.hawkbit.repository.util.WithUser;
import org.eclipse.hawkbit.rest.AbstractRestIntegrationTestWithMongoDB;
import org.eclipse.hawkbit.rest.json.model.ExceptionInfo;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
@@ -77,7 +75,6 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
public void assertPreparationOfRepo() {
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("no softwaremodule should be founded")
.hasSize(0);
assertThat(artifactRepository.findAll()).as("no artifacts should be founded").hasSize(0);
}
@Test
@@ -92,11 +89,15 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
final String updateVendor = "newVendor1";
final String updateDescription = "newDescription1";
softwareManagement.createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, ""));
softwareManagement.createSoftwareModule(new SoftwareModule(runtimeType, "oracle-jre", "1.7.2", null, ""));
softwareManagement.createSoftwareModule(new SoftwareModule(osType, "poky", "3.0.2", null, ""));
softwareManagement.createSoftwareModule(
entityFactory.generateSoftwareModule(appType, "agent-hub", "1.0.1", null, ""));
softwareManagement.createSoftwareModule(
entityFactory.generateSoftwareModule(runtimeType, "oracle-jre", "1.7.2", null, ""));
softwareManagement
.createSoftwareModule(entityFactory.generateSoftwareModule(osType, "poky", "3.0.2", null, ""));
SoftwareModule sm = new SoftwareModule(osType, knownSWName, knownSWVersion, knownSWDescription, knownSWVendor);
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, knownSWName, knownSWVersion,
knownSWDescription, knownSWVendor);
sm = softwareManagement.createSoftwareModule(sm);
assertThat(sm.getName()).as("Wrong name of the software module").isEqualTo(knownSWName);
@@ -122,9 +123,8 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
@Test
@Description("Tests the uppload of an artifact binary. The upload is executed and the content checked in the repository for completenes.")
public void uploadArtifact() throws Exception {
SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null);
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null);
sm = softwareManagement.createSoftwareModule(sm);
assertThat(artifactRepository.findAll()).hasSize(0);
// create test file
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
@@ -163,7 +163,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
private void assertArtifact(final SoftwareModule sm, final byte[] random) throws IOException {
// check result in db...
// repo
assertThat(artifactRepository.findAll()).as("Wrong artifact size").hasSize(1);
assertThat(artifactManagement.countLocalArtifactsAll()).as("Wrong artifact size").isEqualTo(1);
// binary
assertTrue("Wrong artifact content",
@@ -189,9 +189,9 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
@Description("Verfies that the system does not accept empty artifact uploads. Expected response: BAD REQUEST")
public void emptyUploadArtifact() throws Exception {
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
assertThat(artifactRepository.findAll()).hasSize(0);
assertThat(artifactManagement.countLocalArtifactsAll()).isEqualTo(0);
SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null);
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null);
sm = softwareManagement.createSoftwareModule(sm);
final MockMultipartFile file = new MockMultipartFile("file", "orig", null, new byte[0]);
@@ -204,7 +204,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
@Test
@Description("Verfies that the system does not accept identical artifacts uploads for the same software module. Expected response: CONFLICT")
public void duplicateUploadArtifact() throws Exception {
SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null);
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null);
sm = softwareManagement.createSoftwareModule(sm);
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
@@ -226,9 +226,9 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
@Test
@Description("verfies that option to upload artifacts with a custom defined by metadata, i.e. not the file name of the binary itself.")
public void uploadArtifactWithCustomName() throws Exception {
SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null);
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null);
sm = softwareManagement.createSoftwareModule(sm);
assertThat(artifactRepository.findAll()).hasSize(0);
assertThat(artifactManagement.countLocalArtifactsAll()).isEqualTo(0);
// create test file
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
@@ -243,7 +243,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
// check result in db...
// repo
assertThat(artifactRepository.findAll()).as("Artifact size is wring").hasSize(1);
assertThat(artifactManagement.countLocalArtifactsAll()).isEqualTo(1);
// hashes
assertThat(artifactManagement.findLocalArtifactByFilename("customFilename")).as("Local artifact is wrong")
@@ -253,9 +253,9 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
@Test
@Description("Verfies that the system refuses upload of an artifact where the provided hash sums do not match. Expected result: BAD REQUEST")
public void uploadArtifactWithHashCheck() throws Exception {
SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null);
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null);
sm = softwareManagement.createSoftwareModule(sm);
assertThat(artifactRepository.findAll()).hasSize(0);
assertThat(artifactManagement.countLocalArtifactsAll()).isEqualTo(0);
// create test file
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
@@ -297,7 +297,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
@Test
@Description("Tests binary download of an artifact including verfication that the downloaded binary is consistent and that the etag header is as expected identical to the SHA1 hash of the file.")
public void downloadArtifact() throws Exception {
SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null);
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null);
sm = softwareManagement.createSoftwareModule(sm);
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
@@ -325,14 +325,14 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
Arrays.equals(result2.getResponse().getContentAsByteArray(), random));
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Softwaremodule size is wrong").hasSize(1);
assertThat(artifactRepository.findAll()).as("Wrong artifact repostiory").hasSize(2);
assertThat(artifactManagement.countLocalArtifactsAll()).isEqualTo(2);
}
@Test
@Description("Verifies the listing of one defined artifact assigned to a given software module. That includes the artifact metadata and download links.")
public void getArtifact() throws Exception {
// prepare data for test
SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null);
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null);
sm = softwareManagement.createSoftwareModule(sm);
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
@@ -358,7 +358,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
@Test
@Description("Verifies the listing of all artifacts assigned to a software module. That includes the artifact metadata and download links.")
public void getArtifacts() throws Exception {
SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null);
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null);
sm = softwareManagement.createSoftwareModule(sm);
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
@@ -401,7 +401,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
final MockMultipartFile file = new MockMultipartFile("file", "orig", null, random);
SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null);
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null);
sm = softwareManagement.createSoftwareModule(sm);
// no artifact available
@@ -434,7 +434,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
@Test
@Description("Verfies that the system refuses unsupported request types and answers as defined to them, e.g. NOT FOUND on a non existing resource. Or a HTTP POST for updating a resource results in METHOD NOT ALLOWED etc.")
public void invalidRequestsOnSoftwaremodulesResource() throws Exception {
SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null);
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null);
sm = softwareManagement.createSoftwareModule(sm);
final List<SoftwareModule> modules = new ArrayList<>();
@@ -516,13 +516,16 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Test retrieval of all software modules the user has access to.")
public void getSoftwareModules() throws Exception {
SoftwareModule os = new SoftwareModule(osType, "name1", "version1", "description1", "vendor1");
SoftwareModule os = entityFactory.generateSoftwareModule(osType, "name1", "version1", "description1",
"vendor1");
os = softwareManagement.createSoftwareModule(os);
SoftwareModule jvm = new SoftwareModule(runtimeType, "name1", "version1", "description1", "vendor1");
SoftwareModule jvm = entityFactory.generateSoftwareModule(runtimeType, "name1", "version1", "description1",
"vendor1");
jvm = softwareManagement.createSoftwareModule(jvm);
SoftwareModule ah = new SoftwareModule(appType, "name1", "version1", "description1", "vendor1");
SoftwareModule ah = entityFactory.generateSoftwareModule(appType, "name1", "version1", "description1",
"vendor1");
ah = softwareManagement.createSoftwareModule(ah);
mvc.perform(get("/rest/v1/softwaremodules").accept(MediaType.APPLICATION_JSON))
@@ -584,22 +587,28 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
@Test
@Description("Test the various filter parameters, e.g. filter by name or type of the module.")
public void getSoftwareModulesWithFilterParameters() throws Exception {
SoftwareModule os1 = new SoftwareModule(osType, "osName1", "1.0.0", "description1", "vendor1");
SoftwareModule os1 = entityFactory.generateSoftwareModule(osType, "osName1", "1.0.0", "description1",
"vendor1");
os1 = softwareManagement.createSoftwareModule(os1);
SoftwareModule jvm1 = new SoftwareModule(runtimeType, "runtimeName1", "2.0.0", "description1", "vendor1");
SoftwareModule jvm1 = entityFactory.generateSoftwareModule(runtimeType, "runtimeName1", "2.0.0",
"description1", "vendor1");
jvm1 = softwareManagement.createSoftwareModule(jvm1);
SoftwareModule ah1 = new SoftwareModule(appType, "appName1", "3.0.0", "description1", "vendor1");
SoftwareModule ah1 = entityFactory.generateSoftwareModule(appType, "appName1", "3.0.0", "description1",
"vendor1");
ah1 = softwareManagement.createSoftwareModule(ah1);
SoftwareModule os2 = new SoftwareModule(osType, "osName2", "1.0.1", "description2", "vendor2");
SoftwareModule os2 = entityFactory.generateSoftwareModule(osType, "osName2", "1.0.1", "description2",
"vendor2");
os2 = softwareManagement.createSoftwareModule(os2);
SoftwareModule jvm2 = new SoftwareModule(runtimeType, "runtimeName2", "2.0.1", "description2", "vendor2");
SoftwareModule jvm2 = entityFactory.generateSoftwareModule(runtimeType, "runtimeName2", "2.0.1",
"description2", "vendor2");
jvm2 = softwareManagement.createSoftwareModule(jvm2);
SoftwareModule ah2 = new SoftwareModule(appType, "appName2", "3.0.1", "description2", "vendor2");
SoftwareModule ah2 = entityFactory.generateSoftwareModule(appType, "appName2", "3.0.1", "description2",
"vendor2");
ah2 = softwareManagement.createSoftwareModule(ah2);
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(6);
@@ -676,7 +685,8 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Tests GET request on /rest/v1/softwaremodules/{smId}.")
public void getSoftareModule() throws Exception {
SoftwareModule os = new SoftwareModule(osType, "name1", "version1", "description1", "vendor1");
SoftwareModule os = entityFactory.generateSoftwareModule(osType, "name1", "version1", "description1",
"vendor1");
os = softwareManagement.createSoftwareModule(os);
mvc.perform(get("/rest/v1/softwaremodules/{smId}", os.getId()).accept(MediaType.APPLICATION_JSON))
@@ -695,7 +705,8 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
.andExpect(jsonPath("$_links.artifacts.href",
equalTo("http://localhost/rest/v1/softwaremodules/" + os.getId() + "/artifacts")));
SoftwareModule jvm = new SoftwareModule(runtimeType, "name1", "version1", "description1", "vendor1");
SoftwareModule jvm = entityFactory.generateSoftwareModule(runtimeType, "name1", "version1", "description1",
"vendor1");
jvm = softwareManagement.createSoftwareModule(jvm);
mvc.perform(get("/rest/v1/softwaremodules/{smId}", jvm.getId()).accept(MediaType.APPLICATION_JSON))
@@ -714,7 +725,8 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
.andExpect(jsonPath("$_links.artifacts.href",
equalTo("http://localhost/rest/v1/softwaremodules/" + jvm.getId() + "/artifacts")));
SoftwareModule ah = new SoftwareModule(appType, "name1", "version1", "description1", "vendor1");
SoftwareModule ah = entityFactory.generateSoftwareModule(appType, "name1", "version1", "description1",
"vendor1");
ah = softwareManagement.createSoftwareModule(ah);
mvc.perform(get("/rest/v1/softwaremodules/{smId}", ah.getId()).accept(MediaType.APPLICATION_JSON))
@@ -740,9 +752,12 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Verfies that the create request actually results in the creation of the modules in the repository.")
public void createSoftwareModules() throws JSONException, Exception {
final SoftwareModule os = new SoftwareModule(osType, "name1", "version1", "description1", "vendor1");
final SoftwareModule jvm = new SoftwareModule(runtimeType, "name2", "version1", "description1", "vendor1");
final SoftwareModule ah = new SoftwareModule(appType, "name3", "version1", "description1", "vendor1");
final SoftwareModule os = entityFactory.generateSoftwareModule(osType, "name1", "version1", "description1",
"vendor1");
final SoftwareModule jvm = entityFactory.generateSoftwareModule(runtimeType, "name2", "version1",
"description1", "vendor1");
final SoftwareModule ah = entityFactory.generateSoftwareModule(appType, "name3", "version1",
"description1", "vendor1");
final List<SoftwareModule> modules = new ArrayList<>();
modules.add(os);
@@ -823,7 +838,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
@Description("Verifies successfull deletion of software modules that are not in use, i.e. assigned to a DS.")
public void deleteUnassignedSoftwareModule() throws Exception {
SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null);
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null);
sm = softwareManagement.createSoftwareModule(sm);
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
@@ -831,24 +846,20 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
artifactManagement.createLocalArtifact(new ByteArrayInputStream(random), sm.getId(), "file1", false);
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Softwaremoudle size is wrong").hasSize(1);
assertThat(artifactRepository.findAll()).as("artifact site is wrong").hasSize(1);
assertThat(softwareModuleRepository.findAll()).as("Softwaremoudle size is wrong").hasSize(1);
assertThat(artifactManagement.countLocalArtifactsAll()).isEqualTo(1);
mvc.perform(delete("/rest/v1/softwaremodules/{smId}", sm.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
assertThat(softwareManagement.findSoftwareModulesAll(pageReq))
.as("After delete no softwarmodule should be available").isEmpty();
assertThat(softwareModuleRepository.findAll()).as("After delete no softwarmodule should be available")
.isEmpty();
assertThat(artifactRepository.findAll()).as("After delete no artifact should be available").isEmpty();
assertThat(artifactManagement.countLocalArtifactsAll()).isEqualTo(0);
}
@Test
@Description("Verifies successfull deletion of software modules that are in use, i.e. assigned to a DS which should result in movinf the module to the archive.")
public void deleteAssignedSoftwareModule() throws Exception {
final DistributionSet ds1 = TestDataUtil.generateDistributionSet("a", softwareManagement,
distributionSetManagement);
final DistributionSet ds1 = testdataFactory.createDistributionSet("a");
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
@@ -856,8 +867,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
ds1.findFirstModuleByType(appType).getId(), "file1", false);
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(3);
assertThat(artifactRepository.findAll()).hasSize(1);
assertThat(softwareModuleRepository.findAll()).hasSize(3);
assertThat(artifactManagement.countLocalArtifactsAll()).isEqualTo(1);
mvc.perform(delete("/rest/v1/softwaremodules/{smId}", ds1.findFirstModuleByType(appType).getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
@@ -869,17 +879,14 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
// all 3 are now marked as deleted
assertThat(softwareManagement.findSoftwareModulesAll(pageReq).getNumber())
.as("After delete no softwarmodule should be available").isEqualTo(0);
assertThat(softwareModuleRepository.findAll()).as("After delete no softwarmodule should marked as deleted")
.hasSize(3);
assertThat(artifactRepository.findAll()).as("After delete artifact should available for marked as deleted sm's")
.hasSize(1);
assertThat(artifactManagement.countLocalArtifactsAll()).isEqualTo(1);
}
@Test
@Description("Tests the deletion of an artifact including verfication that the artifact is actually erased in the repository and removed from the software module.")
public void deleteArtifact() throws Exception {
// Create 1 SM
SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null);
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null);
sm = softwareManagement.createSoftwareModule(sm);
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
@@ -893,7 +900,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(1);
assertThat(softwareManagement.findSoftwareModuleWithDetails(sm.getId()).getArtifacts()).hasSize(2);
assertThat(artifactRepository.findAll()).hasSize(2);
assertThat(artifactManagement.countLocalArtifactsAll()).isEqualTo(2);
// delete
mvc.perform(delete("/rest/v1/softwaremodules/{smId}/artifacts/{artId}", sm.getId(), artifact.getId()))
@@ -902,8 +909,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
// check that only one artifact is still alive and still assigned
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("After the sm should be marked as deleted")
.hasSize(1);
assertThat(artifactRepository.findAll()).as("After delete artifact should available for marked as deleted sm's")
.hasSize(1);
assertThat(artifactManagement.countLocalArtifactsAll()).isEqualTo(1);
assertThat(softwareManagement.findSoftwareModuleWithDetails(sm.getId()).getArtifacts())
.as("After delete artifact should available for marked as deleted sm's").hasSize(1);
@@ -918,8 +924,8 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
final String knownKey2 = "knownKey1";
final String knownValue2 = "knownValue1";
final SoftwareModule sm = softwareManagement
.createSoftwareModule(new SoftwareModule(osType, "name 1", "version 1", null, null));
final SoftwareModule sm = softwareManagement.createSoftwareModule(
entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null));
final JSONArray jsonArray = new JSONArray();
jsonArray.put(new JSONObject().put("key", knownKey1).put("value", knownValue1));
@@ -932,10 +938,8 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
.andExpect(jsonPath("[1]key", equalTo(knownKey2)))
.andExpect(jsonPath("[1]value", equalTo(knownValue2)));
final SoftwareModuleMetadata metaKey1 = softwareManagement
.findSoftwareModuleMetadata(new SwMetadataCompositeKey(sm, knownKey1));
final SoftwareModuleMetadata metaKey2 = softwareManagement
.findSoftwareModuleMetadata(new SwMetadataCompositeKey(sm, knownKey2));
final SoftwareModuleMetadata metaKey1 = softwareManagement.findSoftwareModuleMetadata(sm, knownKey1);
final SoftwareModuleMetadata metaKey2 = softwareManagement.findSoftwareModuleMetadata(sm, knownKey2);
assertThat(metaKey1.getValue()).as("Metadata key is wrong").isEqualTo(knownValue1);
assertThat(metaKey2.getValue()).as("Metadata key is wrong").isEqualTo(knownValue2);
@@ -949,9 +953,10 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
final String knownValue = "knownValue";
final String updateValue = "valueForUpdate";
final SoftwareModule sm = softwareManagement
.createSoftwareModule(new SoftwareModule(osType, "name 1", "version 1", null, null));
softwareManagement.createSoftwareModuleMetadata(new SoftwareModuleMetadata(knownKey, sm, knownValue));
final SoftwareModule sm = softwareManagement.createSoftwareModule(
entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null));
softwareManagement.createSoftwareModuleMetadata(
entityFactory.generateSoftwareModuleMetadata(sm, knownKey, knownValue));
final JSONObject jsonObject = new JSONObject().put("key", knownKey).put("value", updateValue);
@@ -961,8 +966,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("key", equalTo(knownKey))).andExpect(jsonPath("value", equalTo(updateValue)));
final SoftwareModuleMetadata assertDS = softwareManagement
.findSoftwareModuleMetadata(new SwMetadataCompositeKey(sm, knownKey));
final SoftwareModuleMetadata assertDS = softwareManagement.findSoftwareModuleMetadata(sm, knownKey);
assertThat(assertDS.getValue()).as("Metadata is wrong").isEqualTo(updateValue);
}
@@ -973,15 +977,16 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
final String knownKey = "knownKey";
final String knownValue = "knownValue";
final SoftwareModule sm = softwareManagement
.createSoftwareModule(new SoftwareModule(osType, "name 1", "version 1", null, null));
softwareManagement.createSoftwareModuleMetadata(new SoftwareModuleMetadata(knownKey, sm, knownValue));
final SoftwareModule sm = softwareManagement.createSoftwareModule(
entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null));
softwareManagement.createSoftwareModuleMetadata(
entityFactory.generateSoftwareModuleMetadata(sm, knownKey, knownValue));
mvc.perform(delete("/rest/v1/softwaremodules/{swId}/metadata/{key}", sm.getId(), knownKey))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
try {
softwareManagement.findSoftwareModuleMetadata(new SwMetadataCompositeKey(sm, knownKey));
softwareManagement.findSoftwareModuleMetadata(sm, knownKey);
fail("expected EntityNotFoundException but didn't throw");
} catch (final EntityNotFoundException e) {
// ok as expected
@@ -994,12 +999,13 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
final int totalMetadata = 10;
final String knownKeyPrefix = "knownKey";
final String knownValuePrefix = "knownValue";
final SoftwareModule sm = softwareManagement
.createSoftwareModule(new SoftwareModule(osType, "name 1", "version 1", null, null));
final SoftwareModule sm = softwareManagement.createSoftwareModule(
entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null));
for (int index = 0; index < totalMetadata; index++) {
softwareManagement.createSoftwareModuleMetadata(new SoftwareModuleMetadata(knownKeyPrefix + index,
softwareManagement.findSoftwareModuleById(sm.getId()), knownValuePrefix + index));
softwareManagement.createSoftwareModuleMetadata(entityFactory.generateSoftwareModuleMetadata(
softwareManagement.findSoftwareModuleById(sm.getId()), knownKeyPrefix + index,
knownValuePrefix + index));
}
final String rsqlSearchValue1 = "value==knownValue1";
@@ -1014,7 +1020,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestW
char character = 'a';
for (int index = 0; index < amount; index++) {
final String str = String.valueOf(character);
final SoftwareModule softwareModule = new SoftwareModule(osType, str, str, str, str);
final SoftwareModule softwareModule = entityFactory.generateSoftwareModule(osType, str, str, str, str);
softwareManagement.createSoftwareModule(softwareModule);
character++;

View File

@@ -23,10 +23,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import java.util.ArrayList;
import java.util.List;
import org.eclipse.hawkbit.WithUser;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.util.WithUser;
import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
@@ -54,8 +54,8 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests.")
public void getSoftwareModuleTypes() throws Exception {
SoftwareModuleType testType = softwareManagement
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
SoftwareModuleType testType = softwareManagement.createSoftwareModuleType(
entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5));
testType.setDescription("Desc1234");
testType = softwareManagement.updateSoftwareModuleType(testType);
@@ -77,7 +77,8 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
jsonPath("$content.[?(@.key==" + appType.getKey() + ")][0].name", equalTo(appType.getName())))
.andExpect(jsonPath("$content.[?(@.key==" + appType.getKey() + ")][0].description",
equalTo(appType.getDescription())))
.andExpect(jsonPath("$content.[?(@.key==" + appType.getKey() + ")][0].maxAssignments", equalTo(1)))
.andExpect(jsonPath("$content.[?(@.key==" + appType.getKey() + ")][0].maxAssignments",
equalTo(Integer.MAX_VALUE)))
.andExpect(jsonPath("$content.[?(@.key==" + appType.getKey() + ")][0].key", equalTo("application")))
.andExpect(jsonPath("$content.[?(@.key==test123)][0].id", equalTo(testType.getId().intValue())))
.andExpect(jsonPath("$content.[?(@.key==test123)][0].name", equalTo("TestName123")))
@@ -96,8 +97,8 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests with sorting by MAXASSIGNMENTS field.")
public void getSoftwareModuleTypesSortedByMaxAssignments() throws Exception {
SoftwareModuleType testType = softwareManagement
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
SoftwareModuleType testType = softwareManagement.createSoftwareModuleType(
entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5));
testType.setDescription("Desc1234");
testType = softwareManagement.updateSoftwareModuleType(testType);
@@ -106,30 +107,30 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
.param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, "MAXASSIGNMENTS:DESC"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content.[0].id", equalTo(testType.getId().intValue())))
.andExpect(jsonPath("$content.[0].name", equalTo("TestName123")))
.andExpect(jsonPath("$content.[0].description", equalTo("Desc1234")))
.andExpect(jsonPath("$content.[0].createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[0].createdAt", equalTo(testType.getCreatedAt())))
.andExpect(jsonPath("$content.[0].lastModifiedBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[0].lastModifiedAt", equalTo(testType.getLastModifiedAt())))
.andExpect(jsonPath("$content.[0].maxAssignments", equalTo(5)))
.andExpect(jsonPath("$content.[0].key", equalTo("test123"))).andExpect(jsonPath("$total", equalTo(4)));
.andExpect(jsonPath("$content.[1].id", equalTo(testType.getId().intValue())))
.andExpect(jsonPath("$content.[1].name", equalTo("TestName123")))
.andExpect(jsonPath("$content.[1].description", equalTo("Desc1234")))
.andExpect(jsonPath("$content.[1].createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[1].createdAt", equalTo(testType.getCreatedAt())))
.andExpect(jsonPath("$content.[1].lastModifiedBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[1].lastModifiedAt", equalTo(testType.getLastModifiedAt())))
.andExpect(jsonPath("$content.[1].maxAssignments", equalTo(5)))
.andExpect(jsonPath("$content.[1].key", equalTo("test123"))).andExpect(jsonPath("$total", equalTo(4)));
// ascending
mvc.perform(get("/rest/v1/softwaremoduletypes").accept(MediaType.APPLICATION_JSON)
.param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, "MAXASSIGNMENTS:ASC"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content.[3].id", equalTo(testType.getId().intValue())))
.andExpect(jsonPath("$content.[3].name", equalTo("TestName123")))
.andExpect(jsonPath("$content.[3].description", equalTo("Desc1234")))
.andExpect(jsonPath("$content.[3].createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[3].createdAt", equalTo(testType.getCreatedAt())))
.andExpect(jsonPath("$content.[3].lastModifiedBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[3].lastModifiedAt", equalTo(testType.getLastModifiedAt())))
.andExpect(jsonPath("$content.[3].maxAssignments", equalTo(5)))
.andExpect(jsonPath("$content.[3].key", equalTo("test123"))).andExpect(jsonPath("$total", equalTo(4)));
.andExpect(jsonPath("$content.[2].id", equalTo(testType.getId().intValue())))
.andExpect(jsonPath("$content.[2].name", equalTo("TestName123")))
.andExpect(jsonPath("$content.[2].description", equalTo("Desc1234")))
.andExpect(jsonPath("$content.[2].createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[2].createdAt", equalTo(testType.getCreatedAt())))
.andExpect(jsonPath("$content.[2].lastModifiedBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[2].lastModifiedAt", equalTo(testType.getLastModifiedAt())))
.andExpect(jsonPath("$content.[2].maxAssignments", equalTo(5)))
.andExpect(jsonPath("$content.[2].key", equalTo("test123"))).andExpect(jsonPath("$total", equalTo(4)));
}
@Test
@@ -138,9 +139,9 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
public void createSoftwareModuleTypes() throws JSONException, Exception {
final List<SoftwareModuleType> types = new ArrayList<>();
types.add(new SoftwareModuleType("test1", "TestName1", "Desc1", 1));
types.add(new SoftwareModuleType("test2", "TestName2", "Desc2", 2));
types.add(new SoftwareModuleType("test3", "TestName3", "Desc3", 3));
types.add(entityFactory.generateSoftwareModuleType("test1", "TestName1", "Desc1", 1));
types.add(entityFactory.generateSoftwareModuleType("test2", "TestName2", "Desc2", 2));
types.add(entityFactory.generateSoftwareModuleType("test3", "TestName3", "Desc3", 3));
final MvcResult mvcResult = mvc
.perform(post("/rest/v1/softwaremoduletypes/").content(JsonBuilder.softwareModuleTypes(types))
@@ -182,8 +183,8 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} GET requests.")
public void getSoftwareModuleType() throws Exception {
SoftwareModuleType testType = softwareManagement
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
SoftwareModuleType testType = softwareManagement.createSoftwareModuleType(
entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5));
testType.setDescription("Desc1234");
testType = softwareManagement.updateSoftwareModuleType(testType);
@@ -203,8 +204,8 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} DELETE requests (hard delete scenario).")
public void deleteSoftwareModuleTypeUnused() throws Exception {
final SoftwareModuleType testType = softwareManagement
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
final SoftwareModuleType testType = softwareManagement.createSoftwareModuleType(
entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5));
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(4);
@@ -218,26 +219,24 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} DELETE requests (soft delete scenario).")
public void deleteSoftwareModuleTypeUsed() throws Exception {
final SoftwareModuleType testType = softwareManagement
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
softwareManagement
.createSoftwareModule(new SoftwareModule(testType, "name", "version", "description", "vendor"));
final SoftwareModuleType testType = softwareManagement.createSoftwareModuleType(
entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5));
softwareManagement.createSoftwareModule(
entityFactory.generateSoftwareModule(testType, "name", "version", "description", "vendor"));
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(4);
assertThat(softwareModuleTypeRepository.count()).isEqualTo(4);
mvc.perform(delete("/rest/v1/softwaremoduletypes/{smId}", testType.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
assertThat(softwareModuleTypeRepository.count()).isEqualTo(4);
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(3);
}
@Test
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} PUT requests.")
public void updateSoftwareModuleTypeOnlyDescriptionAndNameUntouched() throws Exception {
final SoftwareModuleType testType = softwareManagement
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
final SoftwareModuleType testType = softwareManagement.createSoftwareModuleType(
entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5));
final String body = new JSONObject().put("id", testType.getId()).put("description", "foobardesc")
.put("name", "nameShouldNotBeChanged").toString();
@@ -292,8 +291,8 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
@Test
@Description("Ensures that the server is behaving as expected on invalid requests (wrong media type, wrong ID etc.).")
public void invalidRequestsOnSoftwaremoduleTypesResource() throws Exception {
final SoftwareModuleType testType = softwareManagement
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
final SoftwareModuleType testType = softwareManagement.createSoftwareModuleType(
entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5));
final List<SoftwareModuleType> types = new ArrayList<>();
types.add(testType);
@@ -331,10 +330,10 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
@Test
@Description("Search erquest of software module types.")
public void searchSoftwareModuleTypeRsql() throws Exception {
final SoftwareModuleType testType = softwareManagement
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
final SoftwareModuleType testType2 = softwareManagement
.createSoftwareModuleType(new SoftwareModuleType("test1234", "TestName1234", "Desc123", 5));
final SoftwareModuleType testType = softwareManagement.createSoftwareModuleType(
entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5));
final SoftwareModuleType testType2 = softwareManagement.createSoftwareModuleType(
entityFactory.generateSoftwareModuleType("test1234", "TestName1234", "Desc123", 5));
final String rsqlFindLikeDs1OrDs2 = "name==TestName123,name==TestName1234";
@@ -349,7 +348,7 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
char character = 'a';
for (int index = 0; index < amount; index++) {
final String str = String.valueOf(character);
final SoftwareModule softwareModule = new SoftwareModule(osType, str, str, str, str);
final SoftwareModule softwareModule = entityFactory.generateSoftwareModule(osType, str, str, str, str);
softwareManagement.createSoftwareModule(softwareModule);
character++;

View File

@@ -29,22 +29,22 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.TestDataUtil;
import org.eclipse.hawkbit.WithUser;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.ActionFields;
import org.eclipse.hawkbit.repository.ActionStatusFields;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget;
import org.eclipse.hawkbit.repository.jpa.model.JpaTargetInfo;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.ActionType;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.util.WithUser;
import org.eclipse.hawkbit.repository.model.ActionStatus;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetInfo;
import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest;
import org.eclipse.hawkbit.rest.exception.MessageNotReadableException;
import org.eclipse.hawkbit.rest.json.model.ExceptionInfo;
@@ -56,7 +56,6 @@ import org.json.JSONObject;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.HttpStatus;
@@ -110,9 +109,8 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
final String knownTargetId = "targetId";
final List<Action> actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId);
actions.get(0).setStatus(Status.FINISHED);
controllerManagament.addUpdateActionStatus(
new ActionStatus(actions.get(0), Status.FINISHED, System.currentTimeMillis(), "testmessage"),
actions.get(0));
controllerManagament.addUpdateActionStatus(entityFactory.generateActionStatus(actions.get(0),
Status.FINISHED, System.currentTimeMillis(), "testmessage"));
final PageRequest pageRequest = new PageRequest(0, 1000, Direction.ASC, ActionFields.ID.getFieldName());
final ActionStatus status = deploymentManagement
@@ -141,7 +139,7 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
public void securityTokenIsNotInResponseIfMissingPermission() throws Exception {
final String knownControllerId = "knownControllerId";
targetManagement.createTarget(new Target(knownControllerId));
targetManagement.createTarget(entityFactory.generateTarget(knownControllerId));
mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}", knownControllerId))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath("securityToken").doesNotExist());
@@ -154,7 +152,7 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
public void securityTokenIsInResponseWithCorrectPermission() throws Exception {
final String knownControllerId = "knownControllerId";
final Target createTarget = targetManagement.createTarget(new Target(knownControllerId));
final Target createTarget = targetManagement.createTarget(entityFactory.generateTarget(knownControllerId));
mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}", knownControllerId))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath("securityToken", equalTo(createTarget.getSecurityToken())));
@@ -185,8 +183,8 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
}
private void createTarget(final String controllerId) {
final Target target = new Target(controllerId);
final TargetInfo targetInfo = new TargetInfo(target);
final JpaTarget target = (JpaTarget) entityFactory.generateTarget(controllerId);
final JpaTargetInfo targetInfo = new JpaTargetInfo(target);
targetInfo.setAddress(IpUtil.createHttpUri("127.0.0.1").toString());
target.setTargetInfo(targetInfo);
targetManagement.createTarget(target);
@@ -197,9 +195,8 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
public void searchActionsRsql() throws Exception {
// prepare test
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final Target createTarget = targetManagement.createTarget(new Target("knownTargetId"));
final DistributionSet dsA = testdataFactory.createDistributionSet("");
final Target createTarget = targetManagement.createTarget(entityFactory.generateTarget("knownTargetId"));
deploymentManagement.assignDistributionSet(dsA, Lists.newArrayList(createTarget));
@@ -306,7 +303,7 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
@Description("Ensures that deletion is executed if permitted.")
public void deleteTargetReturnsOK() throws Exception {
final String knownControllerId = "knownControllerIdDelete";
targetManagement.createTarget(new Target(knownControllerId));
targetManagement.createTarget(entityFactory.generateTarget(knownControllerId));
mvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId))
.andExpect(status().isOk());
@@ -342,7 +339,7 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
final String body = new JSONObject().put("description", knownNewDescription).toString();
// prepare
final Target t = new Target(knownControllerId);
final Target t = entityFactory.generateTarget(knownControllerId);
t.setDescription("old description");
t.setName(knownNameNotModiy);
targetManagement.createTarget(t);
@@ -525,8 +522,7 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
final String knownControllerId = "1";
final String knownName = "someName";
createSingleTarget(knownControllerId, knownName);
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet ds = testdataFactory.createDistributionSet("");
deploymentManagement.assignDistributionSet(ds.getId(), knownControllerId);
// test
@@ -596,12 +592,12 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
final String knownControllerId = "1";
final String knownName = "someName";
createSingleTarget(knownControllerId, knownName);
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet ds = testdataFactory.createDistributionSet("");
// assign ds to target
deploymentManagement.assignDistributionSet(ds.getId(), knownControllerId);
final Long actionId = deploymentManagement.assignDistributionSet(ds.getId(), knownControllerId).getActions()
.get(0);
// give feedback, so installedDS is in SNYC
feedbackToByInSync(knownControllerId, ds);
feedbackToByInSync(actionId);
// test
final SoftwareModule os = ds.findFirstModuleByType(osType);
@@ -683,13 +679,13 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
@Test
public void createTargetsListReturnsSuccessful() throws Exception {
final Target test1 = new Target("id1");
final Target test1 = entityFactory.generateTarget("id1");
test1.setDescription("testid1");
test1.setName("testname1");
final Target test2 = new Target("id2");
final Target test2 = entityFactory.generateTarget("id2");
test2.setDescription("testid2");
test2.setName("testname2");
final Target test3 = new Target("id3");
final Target test3 = entityFactory.generateTarget("id3");
test3.setName("testname3");
test3.setDescription("testid3");
@@ -812,7 +808,7 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
@Test
public void getActionWithEmptyResult() throws Exception {
final String knownTargetId = "targetId";
final Target target = new Target(knownTargetId);
final Target target = entityFactory.generateTarget(knownTargetId);
targetManagement.createTarget(target);
mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/"
@@ -1027,13 +1023,12 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
final PageRequest pageRequest = new PageRequest(0, 100, Direction.ASC, ActionStatusFields.ID.getFieldName());
Target target = new Target(knownTargetId);
Target target = entityFactory.generateTarget(knownTargetId);
target = targetManagement.createTarget(target);
final List<Target> targets = new ArrayList<>();
targets.add(target);
final Iterator<DistributionSet> sets = TestDataUtil
.generateDistributionSets(2, softwareManagement, distributionSetManagement).iterator();
final Iterator<DistributionSet> sets = testdataFactory.createDistributionSets(2).iterator();
final DistributionSet one = sets.next();
final DistributionSet two = sets.next();
@@ -1045,8 +1040,8 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
Thread.sleep(10);
deploymentManagement.assignDistributionSet(two, updatedTargets);
// two updates, one cancelation
final List<Action> actions = actionRepository.findAll(pageRequest).getContent();
// two updates, one cancellation
final List<Action> actions = deploymentManagement.findActionsByTarget(target);
assertThat(actions).hasSize(2);
return actions;
@@ -1073,9 +1068,8 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
@Test
public void assignDistributionSetToTarget() throws Exception {
final Target target = targetManagement.createTarget(new Target("fsdfsd"));
final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
final Target target = targetManagement.createTarget(entityFactory.generateTarget("fsdfsd"));
final DistributionSet set = testdataFactory.createDistributionSet("one");
mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS")
.content("{\"id\":" + set.getId() + "}").contentType(MediaType.APPLICATION_JSON))
@@ -1087,9 +1081,8 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
@Test
public void assignDistributionSetToTargetWithActionTimeForcedAndTime() throws Exception {
final Target target = targetManagement.createTarget(new Target("fsdfsd"));
final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
final Target target = targetManagement.createTarget(entityFactory.generateTarget("fsdfsd"));
final DistributionSet set = testdataFactory.createDistributionSet("one");
final long forceTime = System.currentTimeMillis();
final String body = new JSONObject().put("id", set.getId()).put("type", "timeforced")
@@ -1109,14 +1102,13 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
@Test
public void invalidRequestsOnAssignDistributionSetToTarget() throws Exception {
final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
final DistributionSet set = testdataFactory.createDistributionSet("one");
mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS")
.content("{\"id\":" + set.getId() + "}").contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
targetManagement.createTarget(new Target("fsdfsd"));
targetManagement.createTarget(entityFactory.generateTarget("fsdfsd"));
mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS")
.content("{\"id\":" + set.getId() + "}").contentType(MediaType.APPLICATION_JSON))
@@ -1206,7 +1198,7 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
final Map<String, String> knownControllerAttrs = new HashMap<>();
knownControllerAttrs.put("a", "1");
knownControllerAttrs.put("b", "2");
final Target target = new Target(knownTargetId);
final Target target = entityFactory.generateTarget(knownTargetId);
targetManagement.createTarget(target);
controllerManagament.updateControllerAttributes(knownTargetId, knownControllerAttrs);
@@ -1220,7 +1212,7 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
public void getControllerEmptyAttributesReturnsNoContent() throws Exception {
// create target with attributes
final String knownTargetId = "targetIdWithAttributes";
final Target target = new Target(knownTargetId);
final Target target = entityFactory.generateTarget(knownTargetId);
targetManagement.createTarget(target);
// test query target over rest resource
@@ -1254,7 +1246,7 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
}
private void createSingleTarget(final String controllerId, final String name) {
final Target target = new Target(controllerId);
final Target target = entityFactory.generateTarget(controllerId);
target.setName(name);
target.setDescription(TARGET_DESCRIPTION_TEST);
targetManagement.createTarget(target);
@@ -1271,7 +1263,7 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
char character = 'a';
for (int index = 0; index < amount; index++) {
final String str = String.valueOf(character);
final Target target = new Target(str);
final Target target = entityFactory.generateTarget(str);
target.setName(str);
target.setDescription(str);
final Target savedTarget = targetManagement.createTarget(target);
@@ -1283,20 +1275,12 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
/**
* helper method to give feedback mark an target IN_SNCY
*
* @param controllerId
* the controller id to give feedback to
* @param savedSet
* the distribution set
* @throws Exception
* @throws JSONException
*/
private void feedbackToByInSync(final String controllerId, final DistributionSet savedSet)
throws Exception, JSONException {
final Pageable pageReq = new PageRequest(0, 100);
final Action action = actionRepository.findByDistributionSet(pageReq, savedSet).getContent().get(0);
private void feedbackToByInSync(final Long actionId) {
final Action action = deploymentManagement.findAction(actionId);
final ActionStatus actionStatus = new ActionStatus(action, Status.FINISHED, 0l);
controllerManagement.addUpdateActionStatus(actionStatus, action);
final ActionStatus actionStatus = entityFactory.generateActionStatus(action, Status.FINISHED, 0L);
controllerManagement.addUpdateActionStatus(actionStatus);
}
/**
@@ -1306,10 +1290,9 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
*/
private Target createTargetAndStartAction() {
// prepare test
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
final DistributionSet dsA = testdataFactory.createDistributionSet("");
final Target tA = targetManagement
.createTarget(TestDataUtil.buildTargetFixture("target-id-A", "first description"));
.createTarget(testdataFactory.generateTarget("target-id-A", "first description"));
// assign a distribution set so we get an active update action
deploymentManagement.assignDistributionSet(dsA, Lists.newArrayList(tA));
// verify active action

View File

@@ -13,9 +13,9 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.apache.commons.lang3.RandomStringUtils;
import org.eclipse.hawkbit.AbstractIntegrationTest;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest;
import org.eclipse.hawkbit.rest.json.model.ExceptionInfo;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.junit.BeforeClass;
@@ -34,7 +34,7 @@ import ru.yandex.qatools.allure.annotations.Stories;
*/
@Features("Component Tests - Management API")
@Stories("Download Resource")
public class SMRessourceMisingMongoDbConnectionTest extends AbstractIntegrationTest {
public class SMRessourceMisingMongoDbConnectionTest extends AbstractRestIntegrationTest {
@BeforeClass
public static void initialize() {
@@ -48,11 +48,11 @@ public class SMRessourceMisingMongoDbConnectionTest extends AbstractIntegrationT
public void missingMongoDbConnectionResultsInErrorAtUpload() throws Exception {
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
assertThat(artifactRepository.findAll()).hasSize(0);
SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1",
"version 1", null, null);
assertThat(artifactManagement.countLocalArtifactsAll()).isEqualTo(0);
SoftwareModule sm = entityFactory.generateSoftwareModule(
softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", "version 1", null, null);
sm = softwareManagement.createSoftwareModule(sm);
assertThat(artifactRepository.findAll()).hasSize(0);
assertThat(artifactManagement.countLocalArtifactsAll()).isEqualTo(0);
// create test file
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
@@ -70,7 +70,7 @@ public class SMRessourceMisingMongoDbConnectionTest extends AbstractIntegrationT
assertThat(exceptionInfo.getMessage()).isEqualTo(SpServerError.SP_ARTIFACT_UPLOAD_FAILED.getMessage());
// ensure that the JPA transaction was rolled back
assertThat(artifactRepository.findAll()).hasSize(0);
assertThat(artifactManagement.countLocalArtifactsAll()).isEqualTo(0);
}

View File

@@ -7,22 +7,8 @@
# http://www.eclipse.org/legal/epl-v10.html
#
# used if IM profile is disabled
security.ignored=true
# IM required for integration tests
spring.profiles.active=im,suiteembedded,artifactrepository,redis
server.port=12222
spring.data.mongodb.uri=mongodb://localhost/spArtifactRepository${random.value}
spring.data.mongodb.port=28017
# supported: H2, MYSQL
hawkbit.server.database=H2
hawkbit.server.database.env=TEST
spring.main.show_banner=false
hawkbit.server.ddi.security.authentication.header=true

View File

@@ -1,26 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2015 Bosch Software Innovations GmbH and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v10.html
-->
<Configuration status="WARN" monitorInterval="30">
<Appenders>
<Console name="Console" target="SYSTEM_OUT" follow="true">
<PatternLayout pattern="[%t] [%-5level] %logger{36} - %msg%n" charset="UTF-8"/>
</Console>
</Appenders>
<Loggers>
<Logger name="org.eclipse.hawkbit.MockMvcResultPrinter" level="error" />
<Root level="error">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>

View File

@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2015 Bosch Software Innovations GmbH and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v10.html
-->
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml" />
<logger name="org.eclipse.hawkbit.eventbus.DeadEventListener" level="WARN" />
<Logger name="org.springframework.boot.actuate.audit.listener.AuditListener" level="WARN" />
<Logger name="org.hibernate.validator.internal.util.Version" level="WARN" />
<Logger name="org.apache.coyote.http11.Http11NioProtocol" level="WARN" />
<Logger name="org.apache.tomcat.util.net.NioSelectorPool" level="WARN" />
<Logger name="org.apache.tomcat.jdbc.pool.ConnectionPool" level="DEBUG" />
<Logger name="org.apache.catalina.startup.DigesterFactory" level="ERROR" />
<!-- <Logger name="org.eclipse.hawkbit.rest.util.MockMvcResultPrinter" level="DEBUG" /> -->
<!-- Security Log with hints on potential attacks -->
<logger name="server-security" level="INFO" />
<Root level="INFO">
<AppenderRef ref="Console" />
</Root>
</configuration>

1
hawkbit-repository/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/.springBeans

View File

@@ -0,0 +1,49 @@
<!--
Copyright (c) 2015 Bosch Software Innovations GmbH and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v10.html
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-repository</artifactId>
<version>0.2.0-SNAPSHOT</version>
</parent>
<artifactId>hawkbit-repository-api</artifactId>
<name>hawkBit :: Repository API</name>
<dependencies>
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-security-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>cz.jirutka.rsql</groupId>
<artifactId>rsql-parser</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,307 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository;
import java.io.InputStream;
import java.util.List;
import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.exception.ArtifactDeleteFailedException;
import org.eclipse.hawkbit.repository.exception.ArtifactUploadFailedException;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.GridFSDBFileNotFoundException;
import org.eclipse.hawkbit.repository.exception.InvalidMD5HashException;
import org.eclipse.hawkbit.repository.exception.InvalidSHA1HashException;
import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.repository.model.ExternalArtifact;
import org.eclipse.hawkbit.repository.model.ExternalArtifactProvider;
import org.eclipse.hawkbit.repository.model.LocalArtifact;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.hateoas.Identifiable;
import org.springframework.security.access.prepost.PreAuthorize;
/**
* Service for {@link Artifact} management operations.
*
*/
public interface ArtifactManagement {
/**
* Creates {@link ExternalArtifact} based on given provider.
*
* @param externalRepository
* the artifact is located in
* @param urlSuffix
* of the artifact
* {@link ExternalArtifactProvider#getDefaultSuffix()} is used if
* empty.
* @param moduleId
* to assign the artifact to
*
* @return created {@link ExternalArtifact}
*
* @throws EntityNotFoundException
* if {@link SoftwareModule} with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
ExternalArtifact createExternalArtifact(@NotNull ExternalArtifactProvider externalRepository, String urlSuffix,
@NotNull Long moduleId);
/**
* @return the total amount of local artifacts stored in the artifact
* management
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Long countLocalArtifactsAll();
/**
* @return the total amount of external artifacts stored in the artifact
* management
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Long countExternalArtifactsAll();
/**
* Persists {@link ExternalArtifactProvider} based on given properties.
*
* @param name
* of the provided
* @param description
* which is optional
* @param basePath
* of all {@link ExternalArtifact}s of the provider
* @param defaultUrlSuffix
* that is used if {@link ExternalArtifact#getUrlSuffix()} is
* empty.
* @return created {@link ExternalArtifactProvider}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
ExternalArtifactProvider createExternalArtifactProvider(@NotEmpty String name, String description,
@NotNull String basePath, String defaultUrlSuffix);
/**
* Persists artifact binary as provided by given InputStream. assign the
* artifact in addition to given {@link SoftwareModule}.
*
* @param inputStream
* to read from for artifact binary
* @param moduleId
* to assign the new artifact to
* @param filename
* of the artifact
* @param overrideExisting
* to <code>true</code> if the artifact binary can be overridden
* if it already exists
*
* @return uploaded {@link LocalArtifact}
*
* @throw ArtifactUploadFailedException if upload fails
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
LocalArtifact createLocalArtifact(@NotNull InputStream inputStream, @NotNull Long moduleId, final String filename,
final boolean overrideExisting);
/**
* Persists artifact binary as provided by given InputStream. assign the
* artifact in addition to given {@link SoftwareModule}.
*
* @param inputStream
* to read from for artifact binary
* @param moduleId
* to assign the new artifact to
* @param filename
* of the artifact
* @param overrideExisting
* to <code>true</code> if the artifact binary can be overridden
* if it already exists
* @param contentType
* the contentType of the file
*
* @return uploaded {@link LocalArtifact}
*
* @throw ArtifactUploadFailedException if upload fails
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
LocalArtifact createLocalArtifact(@NotNull InputStream inputStream, @NotNull Long moduleId,
@NotNull String filename, final boolean overrideExisting, @NotNull String contentType);
/**
* Persists artifact binary as provided by given InputStream. assign the
* artifact in addition to given {@link SoftwareModule}.
*
* @param stream
* to read from for artifact binary
* @param moduleId
* to assign the new artifact to
* @param filename
* of the artifact
* @param providedSha1Sum
* optional sha1 checksum to check the new file against
* @param providedMd5Sum
* optional md5 checksum to check the new file against
* @param overrideExisting
* to <code>true</code> if the artifact binary can be overdiden
* if it already exists
* @param contentType
* the contentType of the file
* @return uploaded {@link LocalArtifact}
*
* @throws EntityNotFoundException
* if given software module does not exist
* @throws EntityAlreadyExistsException
* if File with that name already exists in the Software Module
* @throws ArtifactUploadFailedException
* if upload fails with internal server errors
* @throws InvalidMD5HashException
* if check against provided MD5 checksum failed
* @throws InvalidSHA1HashException
* if check against provided SHA1 checksum failed
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
LocalArtifact createLocalArtifact(@NotNull InputStream stream, @NotNull Long moduleId, @NotEmpty String filename,
String providedMd5Sum, String providedSha1Sum, boolean overrideExisting, String contentType);
/**
* Deletes {@link Artifact} based on given id.
*
* @param id
* of the {@link Artifact} that has to be deleted.
* @throws ArtifactDeleteFailedException
* if deletion failed (MongoDB is not available)
*
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteExternalArtifact(@NotNull Long id);
/**
* Deletes a local artifact.
*
* @param existing
* the related local artifact
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteLocalArtifact(@NotNull LocalArtifact existing);
/**
* Deletes {@link Artifact} based on given id.
*
* @param id
* of the {@link Artifact} that has to be deleted.
* @throws ArtifactDeleteFailedException
* if deletion failed (MongoDB is not available)
*
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteLocalArtifact(@NotNull Long id);
/**
* Searches for {@link Artifact} with given {@link Identifiable}.
*
* @param id
* to search for
* @return found {@link Artifact} or <code>null</code> is it could not be
* found.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Artifact findArtifact(@NotNull Long id);
/**
* Find by artifact by software module id and filename.
*
* @param filename
* file name
* @param softwareModuleId
* software module id.
* @return LocalArtifact if artifact present
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER)
List<LocalArtifact> findByFilenameAndSoftwareModule(@NotNull String filename, @NotNull Long softwareModuleId);
/**
* Find all local artifact by sha1 and return the first artifact.
*
* @param sha1
* the sha1
* @return the first local artifact
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER)
LocalArtifact findFirstLocalArtifactsBySHA1(@NotNull String sha1);
/**
* Searches for {@link Artifact} with given file name.
*
* @param filename
* to search for
* @return found List of {@link LocalArtifact}s.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER)
List<LocalArtifact> findLocalArtifactByFilename(@NotNull String filename);
/**
* Get local artifact for a base software module.
*
* @param pageReq
* Pageable
* @param swId
* software module id
* @return Page<LocalArtifact>
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<LocalArtifact> findLocalArtifactBySoftwareModule(@NotNull Pageable pageReq, @NotNull Long swId);
/**
* Finds {@link SoftwareModule} by given id.
*
* @param id
* to search for
* @return the found {@link SoftwareModule}s or <code>null</code> if not
* found.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER)
SoftwareModule findSoftwareModuleById(@NotNull Long id);
/**
* Retrieves software module including details (
* {@link SoftwareModule#getArtifacts()}).
*
* @param id
* parameter
* @param isDeleted
* parameter
* @return the found {@link SoftwareModule}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
SoftwareModule findSoftwareModuleWithDetails(@NotNull Long id);
/**
* Loads {@link DbArtifact} from store for given {@link LocalArtifact}.
*
* @param artifact
* to search for
* @return loaded {@link DbArtifact}
*
* @throws GridFSDBFileNotFoundException
* if file could not be found in store
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DOWNLOAD_ARTIFACT + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.HAS_CONTROLLER_DOWNLOAD)
DbArtifact loadLocalArtifactBinary(@NotNull LocalArtifact artifact);
}

View File

@@ -0,0 +1,76 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
/**
* Repository API constants.
*
*/
public final class Constants {
/**
* {@link SoftwareModuleType#getKey()} of a {@link SoftwareModuleType}
* generated by repository for every new account for Firmware/Operating
* System.
*/
public static final String SMT_DEFAULT_OS_KEY = "os";
/**
* {@link SoftwareModuleType#getKey()} of a {@link SoftwareModuleType}
* generated by repository for every new account for applications.
*/
public static final String SMT_DEFAULT_APP_KEY = "application";
/**
* {@link SoftwareModuleType#getName()} of a {@link SoftwareModuleType}
* generated by repository for every new account for "Firmware/Operating
* System" .
*/
public static final String SMT_DEFAULT_OS_NAME = "Firmware";
/**
* {@link SoftwareModuleType#getName()} of a {@link SoftwareModuleType}
* generated by repository for every new account for "applications/apps".
*/
public static final String SMT_DEFAULT_APP_NAME = "Application";
/**
* {@link DistributionSetType#getKey()} of a {@link DistributionSetType}
* generated by repository for every new account that includes
* {@link #SMT_DEFAULT_OS_KEY} as mandatory module and optional
* {@link #SMT_DEFAULT_APP_KEY}s.
*/
public static final String DST_DEFAULT_OS_WITH_APPS_KEY = "os_app";
/**
* {@link DistributionSetType#getName()} of a {@link DistributionSetType}
* generated by repository for every new account that includes
* {@link #SMT_DEFAULT_OS_KEY} as mandatory module and optional
* {@link #SMT_DEFAULT_APP_KEY}s.
*/
public static final String DST_DEFAULT_OS_WITH_APPS_NAME = "OS with app(s)";
/**
* {@link DistributionSetType#getKey()} of a {@link DistributionSetType}
* generated by repository for every new account that includes only
* {@link #SMT_DEFAULT_OS_KEY} as mandatory module.
*/
public static final String DST_DEFAULT_OS_ONLY_KEY = "os";
/**
* {@link DistributionSetType#getName()} of a {@link DistributionSetType}
* generated by repository for every new account that includes only
* {@link #SMT_DEFAULT_OS_KEY} as mandatory module.
*/
public static final String DST_DEFAULT_OS_ONLY_NAME = "OS only";
private Constants() {
// Utility class.
}
}

View File

@@ -0,0 +1,283 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository;
import java.net.URI;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.eventbus.event.DownloadProgressEvent;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.ToManyAttributeEntriesException;
import org.eclipse.hawkbit.repository.exception.ToManyStatusEntriesException;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.ActionStatus;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.LocalArtifact;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetInfo;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.security.access.prepost.PreAuthorize;
import com.google.common.eventbus.EventBus;
/**
* Service layer for all operations of the DDI API (with access permissions only
* for the controller).
*
*/
public interface ControllerManagement {
/**
* Adds an {@link ActionStatus} for a cancel {@link Action} including
* potential state changes for the target and the {@link Action} itself.
*
* @param actionStatus
* to be added
* @return the persisted {@link Action}
*
* @throws EntityAlreadyExistsException
* if a given entity already exists
*
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
Action addCancelActionStatus(@NotNull ActionStatus actionStatus);
/**
* Sends the download progress in percentage and notifies the
* {@link EventBus} with a {@link DownloadProgressEvent}.
*
* @param statusId
* the ID of the {@link ActionStatus}
* @param progressPercent
* the progress in percentage which must be between 0-100
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
void downloadProgressPercent(long statusId, int progressPercent);
/**
* Simple addition of a new {@link ActionStatus} entry to the {@link Action}
* . No state changes.
*
* @param statusMessage
* to add to the action
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
void addInformationalActionStatus(@NotNull ActionStatus statusMessage);
/**
* Adds an {@link ActionStatus} entry for an update {@link Action} including
* potential state changes for the target and the {@link Action} itself.
*
* @param actionStatus
* to be added
* @return the updated {@link Action}
*
* @throws EntityAlreadyExistsException
* if a given entity already exists
* @throws ToManyStatusEntriesException
* if more than the allowed number of status entries are
* inserted
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
Action addUpdateActionStatus(@NotNull ActionStatus actionStatus);
/**
* Retrieves all {@link Action}s which are active and assigned to a
* {@link Target}.
*
* @param target
* the target to retrieve the actions from
* @return a list of actions assigned to given target which are active
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
List<Action> findActionByTargetAndActive(@NotNull Target target);
/**
* Get the {@link Action} entity for given actionId with all lazy
* attributes.
*
* @param actionId
* to be id of the action
* @return the corresponding {@link Action}
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
Action findActionWithDetails(@NotNull Long actionId);
/**
* register new target in the repository (plug-and-play).
*
* @param controllerId
* reference
* @param address
* the client IP address of the target, might be {@code null}
* @return target reference
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
Target findOrRegisterTargetIfItDoesNotexist(@NotEmpty String controllerId, URI address);
/**
* Retrieves all {@link SoftwareModule}s which are assigned to the given
* {@link DistributionSet}.
*
* @param distributionSet
* the distribution set which should be assigned to the returned
* {@link SoftwareModule}s
* @return a list of {@link SoftwareModule}s assigned to given
* {@code distributionSet}
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
List<SoftwareModule> findSoftwareModulesByDistributionSet(@NotNull DistributionSet distributionSet);
/**
* Retrieves last {@link Action} for a download of an artifact of given
* module and target.
*
* @param controllerId
* to look for
* @param module
* that should be assigned to the target
* @return last {@link Action} for given combination
*
* @throws EntityNotFoundException
* if action for given combination could not be found
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
Action getActionForDownloadByTargetAndSoftwareModule(@NotEmpty String controllerId, @NotNull SoftwareModule module);
/**
* @return current {@link TenantConfigurationKey#POLLING_TIME_INTERVAL}.
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
String getPollingTime();
/**
* An direct access to the security token of an
* {@link Target#getSecurityToken()} without authorization. This is
* necessary to be able to access the security-token without any
* security-context information because the security-token is used for
* authentication.
*
* @param controllerId
* the ID of the controller to retrieve the security token for
* @return the security context of the target, in case no target exists for
* the given controllerId {@code null} is returned
*/
String getSecurityTokenByControllerId(@NotEmpty String controllerId);
/**
* Checks if a given target has currently or has even been assigned to the
* given artifact through the action history list. This can e.g. indicate if
* a target is allowed to download a given artifact because it has currently
* assigned or had ever been assigned to the target and so it's visible to a
* specific target e.g. for downloading.
*
* @param controllerId
* the ID of the target to check
* @param localArtifact
* the artifact to verify if the given target had even been
* assigned to
* @return {@code true} if the given target has currently or had ever a
* relation to the given artifact through the action history,
* otherwise {@code false}
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
boolean hasTargetArtifactAssigned(@NotNull String controllerId, @NotNull LocalArtifact localArtifact);
/**
* Registers retrieved status for given {@link Target} and {@link Action} if
* it does not exist yet.
*
* @param action
* to the handle status for
* @param message
* for the status
* @return the update action in case the status has been changed to
* {@link Status#RETRIEVED}
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
Action registerRetrieved(@NotNull Action action, String message);
/**
* Updates attributes of the controller.
*
* @param controllerId
* to update
* @param attributes
* to insert
*
* @return updated {@link Target}
*
* @throws EntityNotFoundException
* if target that has to be updated could not be found
* @throws ToManyAttributeEntriesException
* if maximum
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
Target updateControllerAttributes(@NotEmpty String controllerId, @NotNull Map<String, String> attributes);
/**
* Refreshes the time of the last time the controller has been connected to
* the server.
*
* @param controllerId
* of the target to to update
* @param address
* the client address of the target, might be {@code null}
* @return the updated target
*
* @throws EntityNotFoundException
* if target with given ID could not be found
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
Target updateLastTargetQuery(@NotEmpty String controllerId, URI address);
/**
* Refreshes the time of the last time the controller has been connected to
* the server.
*
* @param target
* to update
* @param address
* the client address of the target, might be {@code null}
* @return the updated target
*
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
TargetInfo updateLastTargetQuery(@NotNull TargetInfo target, @NotNull URI address);
/**
* Update selective the target status of a given {@code target}.
*
* @param targetInfo
* the target to update the target status
* @param status
* the status to be set of the target. Might be {@code null} if
* the target status should not be updated
* @param lastTargetQuery
* the last target query to be set of the target. Might be
* {@code null} if the target lastTargetQuery should not be
* updated
* @param address
* the client address of the target, might be {@code null}
* @return the updated TargetInfo
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
TargetInfo updateTargetStatus(@NotNull TargetInfo targetInfo, TargetUpdateStatus status, Long lastTargetQuery,
URI address);
}

View File

@@ -0,0 +1,512 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository;
import java.util.Collection;
import java.util.List;
import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.exception.CancelActionNotAllowedException;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.ActionType;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.ActionStatus;
import org.eclipse.hawkbit.repository.model.ActionWithStatusCount;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.Rollout;
import org.eclipse.hawkbit.repository.model.RolloutGroup;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetWithActionType;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.security.access.prepost.PreAuthorize;
/**
* A DeploymentManagement service provides operations for the deployment of
* {@link DistributionSet}s to {@link Target}s.
*
*/
public interface DeploymentManagement {
/**
* method assigns the {@link DistributionSet} to all {@link Target}s.
*
* @param pset
* {@link DistributionSet} which is assigned to the
* {@link Target}s
* @param targets
* the {@link Target}s which should obtain the
* {@link DistributionSet}
*
* @return the changed targets
*
* @throw IncompleteDistributionSetException if mandatory
* {@link SoftwareModuleType} are not assigned as define by the
* {@link DistributionSetType}. *
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET)
DistributionSetAssignmentResult assignDistributionSet(@NotNull DistributionSet pset,
@NotEmpty List<Target> targets);
/**
* method assigns the {@link DistributionSet} to all {@link Target}s by
* their IDs with a specific {@link ActionType} and {@code forcetime}.
*
* @param dsID
* the ID of the distribution set to assign
* @param actionType
* the type of the action to apply on the assignment
* @param forcedTimestamp
* the time when the action should be forced, only necessary for
* {@link ActionType#TIMEFORCED}
* @param targetIDs
* the IDs of the target to assign the distribution set
* @return the assignment result
*
* @throw IncompleteDistributionSetException if mandatory
* {@link SoftwareModuleType} are not assigned as define by the
* {@link DistributionSetType}.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET)
DistributionSetAssignmentResult assignDistributionSet(@NotNull final Long dsID, final ActionType actionType,
final long forcedTimestamp, @NotEmpty final String... targetIDs);
/**
* method assigns the {@link DistributionSet} to all {@link Target}s by
* their IDs with a specific {@link ActionType} and {@code forcetime}.
*
* @param dsID
* the ID of the distribution set to assign
* @param targets
* a list of all targets and their action type
* @return the assignment result
*
* @throw IncompleteDistributionSetException if mandatory
* {@link SoftwareModuleType} are not assigned as define by the
* {@link DistributionSetType}.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET)
DistributionSetAssignmentResult assignDistributionSet(@NotNull Long dsID,
@NotEmpty Collection<TargetWithActionType> targets);
/**
* method assigns the {@link DistributionSet} to all {@link Target}s by
* their IDs with a specific {@link ActionType} and {@code forcetime}.
*
* @param dsID
* the ID of the distribution set to assign
* @param targets
* a list of all targets and their action type
* @param rollout
* the rollout for this assignment
* @param rolloutGroup
* the rollout group for this assignment
* @return the assignment result
*
* @throw IncompleteDistributionSetException if mandatory
* {@link SoftwareModuleType} are not assigned as define by the
* {@link DistributionSetType}.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET)
DistributionSetAssignmentResult assignDistributionSet(@NotNull Long dsID,
@NotEmpty Collection<TargetWithActionType> targets, Rollout rollout, RolloutGroup rolloutGroup);
/**
* method assigns the {@link DistributionSet} to all {@link Target}s by
* their IDs.
*
* @param dsID
* {@link DistributionSet} which is assigned to the
* {@link Target}s
* @param targetIDs
* IDs of the {@link Target}s which should obtain the
* {@link DistributionSet}
*
* @return the changed targets
*
* @throws EntityNotFoundException
* if {@link DistributionSet} does not exist.
*
* @throw IncompleteDistributionSetException if mandatory
* {@link SoftwareModuleType} are not assigned as define by the
* {@link DistributionSetType}.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET)
DistributionSetAssignmentResult assignDistributionSet(@NotNull Long dsID, @NotEmpty String... targetIDs);
/**
* Cancels given {@link Action} for given {@link Target}. The method will
* immediately add a {@link Status#CANCELED} status to the action. However,
* it might be possible that the controller will continue to work on the
* cancellation.
*
* @param action
* to be canceled
* @param target
* for which the action needs cancellation
*
* @return generated {@link Action} or <code>null</code> if not active on
* given {@link Target}.
* @throws CancelActionNotAllowedException
* in case the given action is not active or is already a cancel
* action
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET)
Action cancelAction(@NotNull Action action, @NotNull Target target);
/**
* counts all actions associated to a specific target.
*
* @param rsqlParam
* rsql query string
* @param target
* the target associated to the actions to count
* @return the count value of found actions associated to the target
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Long countActionsByTarget(@NotNull String rsqlParam, @NotNull Target target);
/**
* @return the total amount of stored action status
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Long countActionStatusAll();
/**
* @return the total amount of stored actions
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Long countActionsAll();
/**
* counts all actions associated to a specific target.
*
* @param target
* the target associated to the actions to count
* @return the count value of found actions associated to the target
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Long countActionsByTarget(@NotNull Target target);
/**
* Creates an action entry into the action repository. In case of existing
* scheduled actions the scheduled actions gets canceled. A scheduled action
* is created in-active.
*
* @param targets
* the targets to create scheduled actions for
* @param distributionSet
* the distribution set for the actions
* @param actionType
* the action type for the action
* @param forcedTime
* the forcedTime of the action
* @param rollout
* the roll out for this action
* @param rolloutGroup
* the roll out group for this action
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET)
void createScheduledAction(@NotEmpty Collection<Target> targets, @NotNull DistributionSet distributionSet,
@NotNull ActionType actionType, Long forcedTime, @NotNull Rollout rollout,
@NotNull RolloutGroup rolloutGroup);
/**
* Get the {@link Action} entity for given actionId.
*
* @param actionId
* to be id of the action
* @return the corresponding {@link Action}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Action findAction(@NotNull Long actionId);
/**
* Retrieves all actions for a specific rollout and in a specific status.
*
* @param rollout
* the rollout the actions beglong to
* @param actionStatus
* the status of the actions
* @return the actions referring a specific rollout an in a specific status
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
List<Action> findActionsByRolloutAndStatus(@NotNull Rollout rollout, @NotNull Action.Status actionStatus);
/**
* Retrieving all actions referring to a given rollout with a specific
* action as parent reference and a specific status.
*
* Finding all actions of a specific rolloutgroup parent relation.
*
* @param rollout
* the rollout the actions belong to
* @param rolloutGroupParent
* the parent rollout group the actions should reference
* @param actionStatus
* the status the actions have
* @return the actions referring a specific rollout and a specific parent
* rollout group in a specific status
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_SYSTEM_CODE)
List<Action> findActionsByRolloutGroupParentAndStatus(@NotNull Rollout rollout,
@NotNull RolloutGroup rolloutGroupParent, @NotNull Action.Status actionStatus);
/**
* Retrieves all {@link Action}s of a specific target.
*
* @param pageable
* pagination parameter
* @param target
* of which the actions have to be searched
* @return a paged list of actions associated with the given target
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Slice<Action> findActionsByTarget(@NotNull Pageable pageable, @NotNull Target target);
/**
* Retrieves all {@link Action}s from repository.
*
* @param pageable
* pagination parameter
* @return a paged list of {@link Action}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Slice<Action> findActionsAll(@NotNull Pageable pageable);
/**
* Retrieves all {@link Action} which assigned to a specific
* {@link DistributionSet}.
*
* @param pageable
* the page request parameter for paging and sorting the result
* @param distributionSet
* the distribution set which should be assigned to the actions
* in the result
* @return a list of {@link Action} which are assigned to a specific
* {@link DistributionSet}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Slice<Action> findActionsByDistributionSet(@NotNull Pageable pageable, @NotNull DistributionSet distributionSet);
/**
* Retrieves all {@link Action}s assigned to a specific {@link Target} and a
* given specification.
*
* @param rsqlParam
* rsql query string
* @param target
* the target which must be assigned to the actions
* @param pageable
* the page request
* @return a slice of actions assigned to the specific target and the
* specification
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Slice<Action> findActionsByTarget(@NotNull String rsqlParam, @NotNull Target target, @NotNull Pageable pageable);
/**
* Retrieves all {@link Action}s of a specific target ordered by action ID.
*
* @param target
* the target associated with the actions
* @return a list of actions associated with the given target ordered by
* action ID
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
List<Action> findActionsByTarget(@NotNull Target target);
/**
* Retrieves all {@link Action}s which are referring the given
* {@link Target}.
*
* @param foundTarget
* the target to find actions for
* @param pageable
* the pageable request to limit, sort the actions
* @return a slice of actions found for a specific target
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Slice<Action> findActionsByTarget(@NotNull Target foundTarget, @NotNull Pageable pageable);
/**
* Retrieves all the {@link ActionStatus} entries of the given
* {@link Action} and {@link Target}.
*
* @param pageReq
* pagination parameter
* @param action
* to be filtered on
* @param withMessages
* to <code>true</code> if {@link ActionStatus#getMessages()}
* need to be fetched.
* @return the corresponding {@link Page} of {@link ActionStatus}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<ActionStatus> findActionStatusByAction(@NotNull Pageable pageReq, @NotNull Action action);
/**
* Retrieves all {@link ActionStatus} inclusive their messages by a specific
* {@link Action}.
*
* @param pageable
* the page request parameter for paging and sorting the result
* @param action
* the {@link Action} to retrieve the {@link ActionStatus} from
* @return a page of {@link ActionStatus} by a speciifc {@link Action}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<ActionStatus> findActionStatusByActionWithMessages(@NotNull Pageable pageable, @NotNull Action action);
/**
* Retrieves all {@link Action}s of a specific target ordered by action ID.
*
* @param target
* the target associated with the actions
* @return a list of actions associated with the given target ordered by
* action ID
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
List<ActionWithStatusCount> findActionsWithStatusCountByTargetOrderByIdDesc(@NotNull Target target);
/**
* Get the {@link Action} entity for given actionId with all lazy attributes
* (i.e. distributionSet, target, target.assignedDs).
*
* @param actionId
* to be id of the action
* @return the corresponding {@link Action}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Action findActionWithDetails(@NotNull Long actionId);
/**
* Retrieves all active {@link Action}s of a specific target ordered by
* action ID.
*
* @param pageable
* the pagination parameter
* @param target
* the target associated with the actions
* @return a paged list of actions associated with the given target
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<Action> findActiveActionsByTarget(@NotNull Pageable pageable, @NotNull Target target);
/**
* Retrieves all active {@link Action}s of a specific target ordered by
* action ID.
*
* @param target
* the target associated with the actions
* @return a list of actions associated with the given target
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
List<Action> findActiveActionsByTarget(@NotNull Target target);
/**
* Retrieves all inactive {@link Action}s of a specific target ordered by
* action ID.
*
* @param pageable
* the pagination parameter
* @param target
* the target associated with the actions
* @return a paged list of actions associated with the given target
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<Action> findInActiveActionsByTarget(@NotNull Pageable pageable, @NotNull Target target);
/**
* Retrieves all inactive {@link Action}s of a specific target ordered by
* action ID.
*
* @param target
* the target associated with the actions
* @return a list of actions associated with the given target
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
List<Action> findInActiveActionsByTarget(@NotNull Target target);
/**
* Force cancels given {@link Action} for given {@link Target}. Force
* canceling means that the action is marked as canceled on the SP server
* and a cancel request is sent to the target. But however it's not tracked,
* if the targets handles the cancel request or not.
*
* @param action
* to be canceled
* @param target
* for which the action needs cancellation
*
* @return generated {@link Action} or <code>null</code> if not active on
* {@link Target}.
* @throws CancelActionNotAllowedException
* in case the given action is not active
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET)
Action forceQuitAction(@NotNull Action action);
/**
* Updates a {@link Action} and forces the {@link Action} if it's not
* already forced.
*
* @param targetId
* the ID of the target
* @param actionId
* the ID of the action
* @return the updated or the found {@link Action}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET)
Action forceTargetAction(@NotNull Long actionId);
/**
* Starting an action which is scheduled, e.g. in case of roll out a
* scheduled action must be started now.
*
* @param action
* the action to start now.
* @return the action which has been started
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_SYSTEM_CODE)
Action startScheduledAction(@NotNull Action action);
/**
* All {@link ActionStatus} entries in the repository.
*
* @param pageable
* the pagination parameter
* @return {@link Page} of {@link ActionStatus} entries
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<ActionStatus> findActionStatusAll(@NotNull Pageable pageable);
}

View File

@@ -51,11 +51,6 @@ public class DistributionSetAssignmentResult extends AssignmentResult<Target> {
this.actions = actions;
this.targetManagement = targetManagement;
}
@Override
public List<Target> getAssignedEntity() {
return targetManagement.findTargetByControllerID(assignedTargets);
}
/**
* @return the actionIds
@@ -64,4 +59,9 @@ public class DistributionSetAssignmentResult extends AssignmentResult<Target> {
return actions;
}
@Override
public List<Target> getAssignedEntity() {
return targetManagement.findTargetByControllerID(assignedTargets);
}
}

View File

@@ -0,0 +1,598 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.exception.DistributionSetCreationFailedMissingMandatoryModuleException;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.EntityReadOnlyException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetFilter;
import org.eclipse.hawkbit.repository.model.DistributionSetMetadata;
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.model.Tag;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.DistributionSetFilter.DistributionSetFilterBuilder;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
/**
* Management service for {@link DistributionSet}s.
*
*/
public interface DistributionSetManagement {
// TODO rename/document the whole with details thing (document what the
// details are and maybe find a better name, e.g. with dependencies?)
/**
* Assigns {@link SoftwareModule} to existing {@link DistributionSet}.
*
* @param ds
* to assign and update
* @param softwareModules
* to get assigned
* @return the updated {@link DistributionSet}.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSet assignSoftwareModules(@NotNull DistributionSet ds, Set<SoftwareModule> softwareModules);
/**
* Assign a {@link DistributionSetTag} assignment to given
* {@link DistributionSet}s.
*
* @param dsIds
* to assign for
* @param tag
* to assign
* @return list of assigned ds
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
List<DistributionSet> assignTag(@NotEmpty Collection<Long> dsIds, @NotNull DistributionSetTag tag);
/**
* Count all {@link DistributionSet}s in the repository that are not marked
* as deleted.
*
* @return number of {@link DistributionSet}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Long countDistributionSetsAll();
/**
* Count all {@link DistributionSet}s in the repository that are not marked
* as deleted.
*
* @param type
* to look for
*
* @return number of {@link DistributionSet}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Long countDistributionSetsByType(@NotNull DistributionSetType type);
/**
* @return number of {@link DistributionSetType}s in the repository.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Long countDistributionSetTypesAll();
/**
* Creates a new {@link DistributionSet}.
*
* @param dSet
* {@link DistributionSet} to be created
* @return the new persisted {@link DistributionSet}
*
* @throws EntityAlreadyExistsException
* if a given entity already exists
* @throws DistributionSetCreationFailedMissingMandatoryModuleException
* is {@link DistributionSet} does not contain mandatory
* {@link SoftwareModule}s.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
DistributionSet createDistributionSet(@NotNull DistributionSet dSet);
/**
* creates a list of distribution set meta data entries.
*
* @param metadata
* the meta data entries to create or update
* @return the updated or created distribution set meta data entries
* @throws EntityAlreadyExistsException
* in case one of the meta data entry already exists for the
* specific key
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
List<DistributionSetMetadata> createDistributionSetMetadata(@NotEmpty Collection<DistributionSetMetadata> metadata);
/**
* creates or updates a single distribution set meta data entry.
*
* @param metadata
* the meta data entry to create or update
* @return the updated or created distribution set meta data entry
* @throws EntityAlreadyExistsException
* in case the meta data entry already exists for the specific
* key
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetMetadata createDistributionSetMetadata(@NotNull DistributionSetMetadata metadata);
/**
* Creates multiple {@link DistributionSet}s.
*
* @param distributionSets
* to be created
* @return the new {@link DistributionSet}s
* @throws EntityAlreadyExistsException
* if a given entity already exists
* @throws DistributionSetCreationFailedMissingMandatoryModuleException
* is {@link DistributionSet} does not contain mandatory
* {@link SoftwareModule}s.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
List<DistributionSet> createDistributionSets(@NotNull Collection<DistributionSet> distributionSets);
/**
* Creates new {@link DistributionSetType}.
*
* @param type
* to create
* @return created {@link Entity}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
DistributionSetType createDistributionSetType(@NotNull DistributionSetType type);
/**
* Creates multiple {@link DistributionSetType}s.
*
* @param types
* to create
* @return created {@link Entity}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
List<DistributionSetType> createDistributionSetTypes(@NotNull Collection<DistributionSetType> types);
/**
* <p>
* {@link DistributionSet} can be deleted/erased from the repository if they
* have never been assigned to any {@link UpdateAction} or {@link Target}.
* </p>
*
* <p>
* If they have been assigned that need to be marked as deleted which as a
* result means that they cannot be assigned anymore to any targets. (define
* e.g. findByDeletedFalse())
* </p>
*
* @param set
* to delete
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteDistributionSet(@NotNull DistributionSet set);
/**
* Deleted {@link DistributionSet}s by their IDs. That is either a soft
* delete of the entities have been linked to an {@link UpdateAction} before
* or a hard delete if not.
*
* @param distributionSetIDs
* to be deleted
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteDistributionSet(@NotEmpty Long... distributionSetIDs);
/**
* deletes a distribution set meta data entry.
*
* @param id
* the ID of the distribution set meta data to delete
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
void deleteDistributionSetMetadata(@NotNull final DistributionSet distributionSet, @NotNull final String key);
/**
* Deletes or mark as delete in case the type is in use.
*
* @param type
* to delete
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteDistributionSetType(@NotNull DistributionSetType type);
/**
* retrieves the distribution set for a given action.
*
* @param action
* the action associated with the distribution set
* @return the distribution set which is associated with the action
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DistributionSet findDistributionSetByAction(@NotNull Action action);
/**
* Find {@link DistributionSet} based on given ID without details, e.g.
* {@link DistributionSet#getAgentHub()}.
*
* @param distid
* to look for.
* @return {@link DistributionSet} or <code>null</code> if it does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DistributionSet findDistributionSetById(@NotNull Long distid);
/**
* Find {@link DistributionSet} based on given ID including (lazy loaded)
* details, e.g. {@link DistributionSet#getAgentHub()}.
*
* Note: for performance reasons it is recommended to use
* {@link #findDistributionSetById(Long)} if details are not necessary.
*
* @param distid
* to look for.
* @return {@link DistributionSet} or <code>null</code> if it does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DistributionSet findDistributionSetByIdWithDetails(@NotNull Long distid);
/**
* Find distribution set by name and version.
*
* @param distributionName
* name of {@link DistributionSet}; case insensitive
* @param version
* version of {@link DistributionSet}
* @return the page with the found {@link DistributionSet}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DistributionSet findDistributionSetByNameAndVersion(@NotEmpty String distributionName, @NotEmpty String version);
/**
* finds all meta data by the given distribution set id.
*
* @param distributionSetId
* the distribution set id to retrieve the meta data from
* @param pageable
* the page request to page the result
* @return a paged result of all meta data entries for a given distribution
* set id
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSetMetadata> findDistributionSetMetadataByDistributionSetId(@NotNull Long distributionSetId,
@NotNull Pageable pageable);
/**
* finds all meta data by the given distribution set id.
*
* @param distributionSetId
* the distribution set id to retrieve the meta data from
* @param rsqlParam
* rsql query string
* @param pageable
* the page request to page the result
* @return a paged result of all meta data entries for a given distribution
* set id
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSetMetadata> findDistributionSetMetadataByDistributionSetId(@NotNull Long distributionSetId,
@NotNull String rsqlParam, @NotNull Pageable pageable);
/**
* Retrieves {@link DistributionSet} List for overview purposes (no
* {@link SoftwareModule}s and {@link DistributionSetTag}s).
*
* Please use {@link #findDistributionSetListWithDetails(Iterable)} if
* details are required.
*
* @param dist
* List of {@link DistributionSet} IDs to be found
* @return the found {@link DistributionSet}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
List<DistributionSet> findDistributionSetsAll(Collection<Long> dist);
// TODO discuss: use enum instead of the true,false,null switch ?
/**
* finds all {@link DistributionSet}s.
*
* @param pageReq
* the pagination parameter
* @param deleted
* if TRUE, {@link DistributionSet}s marked as deleted are
* returned. If FALSE, on {@link DistributionSet}s with
* {@link DistributionSet#isDeleted()} == FALSE are returned.
* <code>null</code> if both are to be returned
* @param complete
* to <code>true</code> for returning only completed distribution
* sets or <code>false</code> for only incomplete ones nor
* <code>null</code> to return both.
* @param complete
* set to if <code>false</code> incomplete DS should also be
* shown.
*
*
* @return all found {@link DistributionSet}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSet> findDistributionSetsByDeletedAndOrCompleted(@NotNull Pageable pageReq, Boolean deleted,
Boolean complete);
/**
* finds all {@link DistributionSet}s.
*
* @param rsqlParam
* rsql query string
* @param pageReq
* the pagination parameter
* @param deleted
* if TRUE, {@link DistributionSet}s marked as deleted are
* returned. If FALSE, on {@link DistributionSet}s with
* {@link DistributionSet#isDeleted()} == FALSE are returned.
* <code>null</code> if both are to be returned
* @return all found {@link DistributionSet}s
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSet> findDistributionSetsAll(@NotNull String rsqlParam, @NotNull Pageable pageReq,
Boolean deleted);
/**
* method retrieves all {@link DistributionSet}s from the repository in the
* following order:
* <p>
* 1) {@link DistributionSet}s which have the given {@link Target} as
* {@link TargetStatus#getInstalledDistributionSet()}
* <p>
* 2) {@link DistributionSet}s which have the given {@link Target} as
* {@link Target#getAssignedDistributionSet()}
* <p>
* 3) {@link DistributionSet}s which have no connection to the given
* {@link Target} ordered by ID of the DistributionSet.
*
* @param pageable
* the page request to page the result set *
* @param distributionSetFilterBuilder
* has details of filters to be applied
* @param assignedOrInstalled
* the controllerID of the Target to be ordered by
* @return
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSet> findDistributionSetsAllOrderedByLinkTarget(@NotNull Pageable pageable,
@NotNull DistributionSetFilterBuilder distributionSetFilterBuilder, @NotEmpty String assignedOrInstalled);
/**
* retrieves {@link DistributionSet}s by filtering on the given parameters.
*
* @param pageable
* page parameter
* @param distributionSetFilter
* has details of filters to be applied.
* @return the page of found {@link DistributionSet}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSet> findDistributionSetsByFilters(@NotNull Pageable pageable,
@NotNull DistributionSetFilter distributionSetFilter);
/**
* @param id
* as {@link DistributionSetType#getId()}
* @return {@link DistributionSetType} if found or <code>null</code> if not
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DistributionSetType findDistributionSetTypeById(@NotNull Long id);
/**
* @param key
* as {@link DistributionSetType#getKey()}
* @return {@link DistributionSetType} if found or <code>null</code> if not
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DistributionSetType findDistributionSetTypeByKey(@NotNull String key);
/**
* @param name
* as {@link DistributionSetType#getName()}
* @return {@link DistributionSetType} if found or <code>null</code> if not
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DistributionSetType findDistributionSetTypeByName(@NotEmpty String name);
/**
* @param pageable
* parameter
* @return all {@link DistributionSetType}s in the repository.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSetType> findDistributionSetTypesAll(@NotNull Pageable pageable);
/**
* Generic predicate based query for {@link DistributionSetType}.
*
* @param rsqlParam
* rsql query string
* @param pageable
* parameter for paging
*
* @return the found {@link SoftwareModuleType}s
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSetType> findDistributionSetTypesAll(@NotNull String rsqlParam, @NotNull Pageable pageable);
/**
* finds a single distribution set meta data by its id.
*
* @param id
* the id of the distribution set meta data containing the meta
* data key and the ID of the distribution set
* @return the found DistributionSetMetadata or {@code null} if not exits
* @throws EntityNotFoundException
* in case the meta data does not exists for the given key
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DistributionSetMetadata findOne(@NotNull DistributionSet distributionSet, @NotNull String key);
/**
* Checks if a {@link DistributionSet} is currently in use by a target in
* the repository.
*
* @param distributionSet
* to check
*
* @return <code>true</code> if in use
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
boolean isDistributionSetInUse(@NotNull DistributionSet distributionSet);
/**
* {@link Entity} based method call for
* {@link #toggleTagAssignment(Collection, String)}.
*
* @param sets
* to toggle for
* @param tag
* to toggle
* @return {@link DistributionSetTagAssignmentResult} with all meta data of
* the assignment outcome.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetTagAssignmentResult toggleTagAssignment(@NotEmpty Collection<DistributionSet> sets,
@NotNull DistributionSetTag tag);
/**
* Toggles {@link DistributionSetTag} assignment to given
* {@link DistributionSet}s by means that if some (or all) of the targets in
* the list have the {@link Tag} not yet assigned, they will be. If all of
* theme have the tag already assigned they will be removed instead.
*
* @param dsIds
* to toggle for
* @param tagName
* to toggle
* @return {@link DistributionSetTagAssignmentResult} with all meta data of
* the assignment outcome.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetTagAssignmentResult toggleTagAssignment(@NotEmpty Collection<Long> dsIds, @NotNull String tagName);
/**
* Unassign all {@link DistributionSet} from a given
* {@link DistributionSetTag} .
*
* @param tag
* to unassign all ds
* @return list of unassigned ds
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
List<DistributionSet> unAssignAllDistributionSetsByTag(@NotNull DistributionSetTag tag);
/**
* Unassigns a {@link SoftwareModule} form an existing
* {@link DistributionSet}.
*
* @param ds
* to get unassigned form
* @param softwareModule
* to get unassigned
* @return the updated {@link DistributionSet}.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSet unassignSoftwareModule(@NotNull DistributionSet ds, @NotNull SoftwareModule softwareModule);
/**
* Unassign a {@link DistributionSetTag} assignment to given
* {@link DistributionSet}.
*
* @param dsId
* to unassign for
* @param distributionSetTag
* to unassign
* @return the unassigned ds or <null> if no ds is unassigned
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSet unAssignTag(@NotNull Long dsId, @NotNull DistributionSetTag distributionSetTag);
/**
* Updates existing {@link DistributionSet}.
*
* @param ds
* to update
* @return the saved {@link Entity}.
* @throws NullPointerException
* of {@link DistributionSet#getId()} is <code>null</code>
* @throw DataDependencyViolationException in case of illegal update
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSet updateDistributionSet(@NotNull DistributionSet ds);
/**
* updates a distribution set meta data value if corresponding entry exists.
*
* @param metadata
* the meta data entry to be updated
* @return the updated meta data entry
* @throws EntityNotFoundException
* in case the meta data entry does not exists and cannot be
* updated
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetMetadata updateDistributionSetMetadata(@NotNull DistributionSetMetadata metadata);
/**
* Updates existing {@link DistributionSetType}. However, keep in mind that
* is not possible to change the {@link DistributionSetTypeElement}s while
* the DS type is already in use.
*
* @param dsType
* to update
* @return updated {@link Entity}
*
* @throws EntityReadOnlyException
* if use tries to change the {@link DistributionSetTypeElement}
* s while the DS type is already in use.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetType updateDistributionSetType(@NotNull DistributionSetType dsType);
}

View File

@@ -0,0 +1,341 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.ActionStatus;
import org.eclipse.hawkbit.repository.model.BaseEntity;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetMetadata;
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.LocalArtifact;
import org.eclipse.hawkbit.repository.model.Rollout;
import org.eclipse.hawkbit.repository.model.RolloutGroup;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetFilterQuery;
import org.eclipse.hawkbit.repository.model.TargetTag;
import org.hibernate.validator.constraints.NotEmpty;
/**
* central {@link BaseEntity} generation service. Objects are created but not
* persisted.
*
*/
public interface EntityFactory {
/**
* Generates an empty {@link Action} without persisting it.
*
* @return {@link Action} object
*/
Action generateAction();
/**
* Generates an empty {@link ActionStatus} object without persisting it.
*
* @return {@link ActionStatus} object
*/
ActionStatus generateActionStatus();
/**
* Generates an {@link ActionStatus} object without persisting it.
*
* @param action
* the {@link ActionStatus} belongs to.
* @param status
* as reflected by this {@link ActionStatus}.
* @param occurredAt
* time in {@link TimeUnit#MILLISECONDS} GMT when the status
* change happened.
*
* @return {@link ActionStatus} object
*/
ActionStatus generateActionStatus(Action action, Status status, Long occurredAt);
/**
* Generates an {@link ActionStatus} object without persisting it.
*
* @param action
* the {@link ActionStatus} belongs to.
* @param status
* as reflected by this {@link ActionStatus}.
* @param occurredAt
* time in {@link TimeUnit#MILLISECONDS} GMT when the status
* change happened.
* @param messages
* optional comments
*
* @return {@link ActionStatus} object
*/
ActionStatus generateActionStatus(Action action, final Status status, Long occurredAt,
final Collection<String> messages);
/**
* Generates an {@link ActionStatus} object without persisting it.
*
* @param action
* the {@link ActionStatus} belongs to.
* @param status
* as reflected by this {@link ActionStatus}.
* @param occurredAt
* time in {@link TimeUnit#MILLISECONDS} GMT when the status
* change happened.
* @param message
* optional comment
*
* @return {@link ActionStatus} object
*/
ActionStatus generateActionStatus(Action action, Status status, Long occurredAt, final String message);
/**
* Generates an empty {@link DistributionSet} without persisting it.
*
* @return {@link DistributionSet} object
*/
DistributionSet generateDistributionSet();
/**
* Generates an {@link DistributionSet} without persisting it.
*
* @param name
* {@link DistributionSet#getName()}
* @param version
* {@link DistributionSet#getVersion()}
* @param description
* {@link DistributionSet#getDescription()}
* @param type
* {@link DistributionSet#getType()}
* @param moduleList
* {@link DistributionSet#getModules()}
*
* @return {@link DistributionSet} object
*/
DistributionSet generateDistributionSet(String name, String version, String description, DistributionSetType type,
Collection<SoftwareModule> moduleList);
/**
* Generates an empty {@link DistributionSetMetadata} element without
* persisting it.
*
* @return {@link DistributionSetMetadata} object
*/
DistributionSetMetadata generateDistributionSetMetadata();
/**
* Generates an {@link DistributionSetMetadata} element without persisting
* it.
*
* @param distributionSet
* {@link DistributionSetMetadata#getDistributionSet()}
* @param key
* {@link DistributionSetMetadata#getKey()}
* @param value
* {@link DistributionSetMetadata#getValue()}
*
* @return {@link DistributionSetMetadata} object
*/
DistributionSetMetadata generateDistributionSetMetadata(DistributionSet distributionSet, String key, String value);
/**
* Generates an empty {@link DistributionSetTag} without persisting it.
*
* @return {@link DistributionSetTag} object
*/
DistributionSetTag generateDistributionSetTag();
/**
* Generates a {@link DistributionSetTag} without persisting it.
*
* @param name
* of the tag
* @return {@link DistributionSetTag} object
*/
DistributionSetTag generateDistributionSetTag(String name);
/**
* Generates a {@link DistributionSetTag} without persisting it.
*
* @param name
* of the tag
* @param description
* of the tag
* @param colour
* of the tag
* @return {@link DistributionSetTag} object
*/
DistributionSetTag generateDistributionSetTag(String name, String description, String colour);
/**
* Generates an empty {@link DistributionSetType} without persisting it.
*
* @return {@link DistributionSetType} object
*/
DistributionSetType generateDistributionSetType();
/**
* Generates a {@link DistributionSetType} without persisting it.
*
* @param key
* {@link DistributionSetType#getKey()}
* @param name
* {@link DistributionSetType#getName()}
* @param description
* {@link DistributionSetType#getDescription()}
*
* @return {@link DistributionSetType} object
*/
DistributionSetType generateDistributionSetType(String key, String name, String description);
/**
* Generates an empty {@link Rollout} without persisting it.
*
* @return {@link Rollout} object
*/
Rollout generateRollout();
/**
* Generates an empty {@link RolloutGroup} without persisting it.
*
* @return {@link RolloutGroup} object
*/
RolloutGroup generateRolloutGroup();
/**
* Generates an empty {@link SoftwareModule} without persisting it.
*
* @return {@link SoftwareModule} object
*/
SoftwareModule generateSoftwareModule();
/**
* Generates a {@link SoftwareModule} without persisting it.
*
* @param type
* of the {@link SoftwareModule}
* @param name
* abstract name of the {@link SoftwareModule}
* @param version
* of the {@link SoftwareModule}
* @param description
* of the {@link SoftwareModule}
* @param vendor
* of the {@link SoftwareModule}
*
* @return {@link SoftwareModule} object
*/
SoftwareModule generateSoftwareModule(SoftwareModuleType type, String name, String version, String description,
String vendor);
/**
* Generates an empty {@link SoftwareModuleMetadata} pair without persisting
* it.
*
* @return {@link SoftwareModuleMetadata} object
*/
SoftwareModuleMetadata generateSoftwareModuleMetadata();
/**
* Generates a {@link SoftwareModuleMetadata} pair without persisting it.
*
* @param softwareModule
* {@link SoftwareModuleMetadata#getSoftwareModule()}
* @param key
* {@link SoftwareModuleMetadata#getKey()}
* @param value
* {@link SoftwareModuleMetadata#getValue()}
*
* @return {@link SoftwareModuleMetadata} object
*/
SoftwareModuleMetadata generateSoftwareModuleMetadata(SoftwareModule softwareModule, String key, String value);
/**
* Generates an empty {@link SoftwareModuleType} without persisting it.
*
* @return {@link SoftwareModuleType} object
*/
SoftwareModuleType generateSoftwareModuleType();
/**
* Generates a {@link SoftwareModuleType} without persisting it.
*
* @param key
* {@link SoftwareModuleType#getKey()}
* @param name
* {@link SoftwareModuleType#getName()}
* @param description
* {@link SoftwareModuleType#getDescription()}
* @param maxAssignments
* {@link SoftwareModuleType#getMaxAssignments()}
*
* @return {@link SoftwareModuleType} object
*/
SoftwareModuleType generateSoftwareModuleType(String key, String name, String description, int maxAssignments);
/**
* Generates an empty {@link Target} without persisting it.
*
* @param controllerID
* of the {@link Target}
*
* @return {@link Target} object
*/
Target generateTarget(@NotEmpty String controllerID);
/**
* Generates an empty {@link TargetFilterQuery} without persisting it.
*
* @return {@link TargetFilterQuery} object
*/
TargetFilterQuery generateTargetFilterQuery();
/**
* Generates an empty {@link TargetTag} without persisting it.
*
* @return {@link TargetTag} object
*/
TargetTag generateTargetTag();
/**
* Generates a {@link TargetTag} without persisting it.
*
* @param name
* of the tag
* @return {@link TargetTag} object
*/
TargetTag generateTargetTag(String name);
/**
* Generates a {@link TargetTag} without persisting it.
*
* @param name
* of the tag
* @param description
* of the tag
* @param colour
* of the tag
* @return {@link TargetTag} object
*/
TargetTag generateTargetTag(String name, String description, String colour);
/**
* Generates an empty {@link LocalArtifact} without persisting it.
*
* @return {@link LocalArtifact} object
*/
LocalArtifact generateLocalArtifact();
}

View File

@@ -14,13 +14,9 @@ import org.springframework.data.domain.Sort;
/**
* An implementation of the {@link PageRequest} which is offset based by means
* the offset is given and not the page number as in the original
* {@link PageRequest} implemntation where the offset is generated. Due that the
* REST-API is working with {@code offset} and {@code limit} parameter we need
* an offset based page request for JPA.
*
* @author Michael Hirsch
* @since 0.2.2
*
* {@link PageRequest} implementation where the offset is generated. Due that
* the REST-API is working with {@code offset} and {@code limit} parameter we
* need an offset based page request.
*/
public final class OffsetBasedPageRequest extends PageRequest {
@@ -66,4 +62,31 @@ public final class OffsetBasedPageRequest extends PageRequest {
return "OffsetBasedPageRequest [offset=" + offset + ", getPageSize()=" + getPageSize() + ", getPageNumber()="
+ getPageNumber() + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + offset;
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (!(obj instanceof OffsetBasedPageRequest)) {
return false;
}
final OffsetBasedPageRequest other = (OffsetBasedPageRequest) obj;
if (offset != other.offset) {
return false;
}
return true;
}
}

View File

@@ -0,0 +1,211 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.List;
import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.model.TargetInfo;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.repository.report.model.DataReportSeries;
import org.eclipse.hawkbit.repository.report.model.InnerOuterDataReportSeries;
import org.eclipse.hawkbit.repository.report.model.ListReportSeries;
import org.eclipse.hawkbit.repository.report.model.SeriesTime;
import org.springframework.security.access.prepost.PreAuthorize;
/**
* Service layer for generating hawkBit statistics and reports.
*
*/
public interface ReportManagement {
/**
* Data base format.
*
*
*
* @param <T>
*/
public interface DateType<T> {
/**
* @param s
* @return T
*/
T format(String s);
/**
* h2 format.
*
* @return String
*/
String h2Format();
/**
* mysql format.
*
* @return String
*/
String mySqlFormat();
}
/**
* Return DateTypes.
*/
public static final class DateTypes implements Serializable {
private static final long serialVersionUID = 1L;
private static final PerMonth PER_MONTH = new PerMonth();
private DateTypes() {
// Utility class
}
/**
* @return PerMonth
*/
public static PerMonth perMonth() {
return PER_MONTH;
}
}
/**
* Gives the date format based on DB H2 or mySql.
*
*
*
*/
public static final class PerMonth implements DateType<LocalDate>, Serializable {
private static final long serialVersionUID = 1L;
private static final String DATE_PATTERN = "yyyy-MM";
@Override
public LocalDate format(final String s) {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_PATTERN);
final YearMonth ym = YearMonth.parse(s, formatter);
return ym.atDay(1);
}
@Override
public String h2Format() {
return DATE_PATTERN;
}
@Override
public String mySqlFormat() {
return "%Y-%m";
}
}
/**
* Generates a report of the top x distribution set assigned usage as a list
* of {@link InnerOuterDataReportSeries} which is ideal for generate a donut
* chart out of it. The inner series contains the distribution set names and
* total count usage. The outer series contains each version usage and its
* usage count. {@code inner: ds1:5 -> outer: vers 0.0.0:3, vers 1.0.0:2}
* {@code inner: ds2:1 -> outer: vers 0.0.1:1}
*
* The top x entries are seperated within the series, the rest of the
* distribution sets usage are summarized to a "misc" series.
*
* @param topXEntries
* the top entries which should be shown, the rest distribution
* set entries are summarized as "misc"
* @return a list of inner and outer series of distribution set usage
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
List<InnerOuterDataReportSeries<String>> distributionUsageAssigned(int topXEntries);
/**
* Generates a report of the top x distribution set installed usage as a
* list of {@link InnerOuterDataReportSeries} which is ideal for generate a
* donut chart out of it. The inner series contains the distribution set
* names and total count usage. The outer series contains each version usage
* and its usage count.
* {@code inner: ds1:5 -> outer: vers 0.0.0:3, vers 1.0.0:2}
* {@code inner: ds2:1 -> outer: vers 0.0.1:1}
*
* The top x entries are seperated within the series, the rest of the
* distribution sets usage are summarized to a "misc" series.
*
* @param topXEntries
* the top entries which should be shown, the rest distribution
* set entries are summarized as "misc"
* @return a list of inner and outer series of distribution set usage
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
List<InnerOuterDataReportSeries<String>> distributionUsageInstalled(int topXEntries);
/**
* Generates report for feedback over period.
*
* @param dateType
* {@link PerMonth}
* @param from
* start date
* @param to
* end date
* @return <T> DataReportSeries<T> ListReportSeries list of action status
* count
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
<T extends Serializable> DataReportSeries<T> feedbackReceivedOverTime(@NotNull DateType<T> dateType,
@NotNull LocalDateTime from, @NotNull LocalDateTime to);
/**
* Generates report for target created over period.
*
* @param dateType
* {@link PerMonth}
* @param from
* start date
* @param to
* end date
* @return <T> DataReportSeries<T> ListReportSeries list of target created
* count
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
<T extends Serializable> DataReportSeries<T> targetsCreatedOverPeriod(@NotNull DateType<T> dateType,
@NotNull LocalDateTime from, @NotNull LocalDateTime to);
/**
* Generates a report as a {@link ListReportSeries} targets polled based on
* the {@link TargetInfo#getLastTargetQuery()} within an hour, day, week,
* month, year, more than a year, never.
*
* The order of the numbers within the {@link DataReportSeries} is the order
* hour, day, week, month, year, more than a year, never.
*
* @return a {@link DataReportSeries} which contains the number of targets
* which have not been polled in the last hour, day, ... year,more
* than a year, never.
*
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DataReportSeries<SeriesTime> targetsLastPoll();
/**
* Generates a report of all targets of their current update status count.
* For each {@link TargetUpdateStatus} an total count of targets which are
* in this status currently.
*
* @return a data report series which contains the target count for each
* target update status
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DataReportSeries<TargetUpdateStatus> targetStatus();
}

View File

@@ -0,0 +1,37 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository;
import org.eclipse.hawkbit.repository.model.ActionStatus;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
/**
* Repository constants.
*
*/
public final class RepositoryConstants {
/**
* Prefix that the server puts in front of
* {@link ActionStatus#getMessages()} if the message is generated by the
* server.
*/
public static final String SERVER_MESSAGE_PREFIX = "Update Server: ";
/**
* Number of {@link DistributionSetType}s that are generated as part of
* default tenant setup.
*/
public static final int DEFAULT_DS_TYPES_IN_TENANT = 2;
private RepositoryConstants() {
// Utility class.
}
}

View File

@@ -0,0 +1,153 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository;
import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException;
import org.eclipse.hawkbit.repository.model.Rollout;
import org.eclipse.hawkbit.repository.model.RolloutGroup;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetWithActionStatus;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
/**
* Repository management service for RolloutGroup.
*
*/
public interface RolloutGroupManagement {
/**
* Retrieves a page of {@link RolloutGroup}s filtered by a given
* {@link Rollout} with the detailed status.
*
* @param rolloutId
* the ID of the rollout to filter the {@link RolloutGroup}s
* @param pageable
* the page request to sort and limit the result
* @return a page of found {@link RolloutGroup}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
Page<RolloutGroup> findAllRolloutGroupsWithDetailedStatus(@NotNull Long rolloutId, @NotNull Pageable pageable);
/**
*
* Find all targets with action status by rollout group id. The action
* status might be {@code null} if for the target within the rollout no
* actions as been created, e.g. the target already had assigned the same
* distribution set we do not create an action for it but the target is in
* the result list of the rollout-group.
*
* @param pageRequest
* the page request to sort and limit the result
* @param rolloutGroup
* rollout group
* @return {@link TargetWithActionStatus} target with action status
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ_AND_TARGET_READ)
Page<TargetWithActionStatus> findAllTargetsWithActionStatus(@NotNull PageRequest pageRequest,
@NotNull RolloutGroup rolloutGroup);
/**
* Retrieves a single {@link RolloutGroup} by its ID.
*
* @param rolloutGroupId
* the ID of the rollout group to find
* @return the found {@link RolloutGroup} by its ID or {@code null} if it
* does not exists
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
RolloutGroup findRolloutGroupById(@NotNull Long rolloutGroupId);
/**
* Retrieves a page of {@link RolloutGroup}s filtered by a given
* {@link Rollout} and the an rsql filter.
*
* @param rollout
* the rollout to filter the {@link RolloutGroup}s
* @param rsqlParam
* the specification to filter the result set based on attributes
* of the {@link RolloutGroup}
* @param pageable
* the page request to sort and limit the result
* @return a page of found {@link RolloutGroup}s
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
Page<RolloutGroup> findRolloutGroupsAll(@NotNull Rollout rollout, @NotNull String rsqlParam,
@NotNull Pageable pageable);
/**
* Retrieves a page of {@link RolloutGroup}s filtered by a given
* {@link Rollout}.
*
* @param rolloutId
* the ID of the rollout to filter the {@link RolloutGroup}s
* @param pageable
* the page request to sort and limit the result
* @return a page of found {@link RolloutGroup}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
Page<RolloutGroup> findRolloutGroupsByRolloutId(@NotNull Long rolloutId, @NotNull Pageable pageable);
/**
* Get targets of specified rollout group.
*
* @param rolloutGroup
* rollout group
* @param page
* the page request to sort and limit the result
*
* @return Page<Target> list of targets of a rollout group
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ_AND_TARGET_READ)
Page<Target> findRolloutGroupTargets(@NotNull RolloutGroup rolloutGroup, @NotNull Pageable page);
/**
* Get targets of specified rollout group.
*
* @param rolloutGroup
* rollout group
* @param rsqlParam
* the specification for filtering the targets of a rollout group
* @param pageable
* the page request to sort and limit the result
*
* @return Page<Target> list of targets of a rollout group
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ_AND_TARGET_READ)
Page<Target> findRolloutGroupTargets(@NotNull RolloutGroup rolloutGroup, @NotNull String rsqlParam,
@NotNull Pageable pageable);
/**
* Get count of targets in different status in rollout group.
*
* @param rolloutGroupId
* rollout group id
* @return rolloutGroup with details of targets count for different statuses
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
RolloutGroup findRolloutGroupWithDetailedStatus(@NotNull Long rolloutGroupId);
}

View File

@@ -0,0 +1,344 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository;
import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.eventbus.event.RolloutGroupCreatedEvent;
import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException;
import org.eclipse.hawkbit.repository.exception.RolloutIllegalStateException;
import org.eclipse.hawkbit.repository.model.Rollout;
import org.eclipse.hawkbit.repository.model.Rollout.RolloutStatus;
import org.eclipse.hawkbit.repository.model.RolloutGroup;
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupStatus;
import org.eclipse.hawkbit.repository.model.RolloutGroupConditions;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.security.access.prepost.PreAuthorize;
/**
* RolloutManagement to control rollouts e.g. like creating, starting, resuming
* and pausing rollouts. This service secures all the functionality based on the
* {@link PreAuthorize} annotation on methods.
*/
public interface RolloutManagement {
/**
* Checking running rollouts. Rollouts which are checked updating the
* {@link Rollout#setLastCheck(long)} to indicate that the current instance
* is handling the specific rollout. This code should run as system-code.
*
* <pre>
* {@code
* SystemSecurityContext.runAsSystem(new Callable<Void>() {
* public Void call() throws Exception {
* //run system-code
* }
* });
* }
* </pre>
*
* This method is attend to be called by a scheduler.
* {@link RolloutScheduler}. And must be running in an transaction so it's
* splitted from the scheduler.
*
* Rollouts which are currently running are investigated, by means the
* error- and finish condition of running groups in this rollout are
* evaluated.
*
* @param delayBetweenChecks
* the time in milliseconds of the delay between the further and
* this check. This check is only applied if the last check is
* less than (lastcheck-delay).
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_SYSTEM_CODE)
void checkRunningRollouts(long delayBetweenChecks);
/**
* Counts all {@link Rollout}s in the repository.
*
* @return number of roll outs
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
Long countRolloutsAll();
/**
* Count rollouts by given text in name or description.
*
* @param searchText
* name or description
* @return total count rollouts for specified filter text.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
Long countRolloutsAllByFilters(@NotEmpty String searchText);
/**
* Persists a new rollout entity. The filter within the
* {@link Rollout#getTargetFilterQuery()} is used to retrieve the targets
* which are effected by this rollout to create. The targets will then be
* split up into groups. The size of the groups can be defined in the
* {@code groupSize} parameter.
*
* The rollout is not started. Only the preparation of the rollout is done,
* persisting and creating all the necessary groups. The Rollout and the
* groups are persisted in {@link RolloutStatus#READY} and
* {@link RolloutGroupStatus#READY} so they can be started
* {@link #startRollout(Rollout)}.
*
* @param rollout
* the rollout entity to create
* @param amountGroup
* the amount of groups to split the rollout into
* @param conditions
* the rolloutgroup conditions and actions which should be
* applied for each {@link RolloutGroup}
* @return the persisted rollout.
*
* @throws IllegalArgumentException
* in case the given groupSize is zero or lower.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE)
Rollout createRollout(@NotNull Rollout rollout, int amountGroup, @NotNull RolloutGroupConditions conditions);
/**
* Persists a new rollout entity. The filter within the
* {@link Rollout#getTargetFilterQuery()} is used to retrieve the targets
* which are effected by this rollout to create. The creation of the rollout
* will be done synchronously and will be returned. The targets will then be
* split up into groups. The size of the groups can be defined in the
* {@code groupSize} parameter.
*
* The creation of the rollout groups is executed asynchronously due it
* might take some time to split up the targets into groups. The creation of
* the {@link RolloutGroup} is published as event
* {@link RolloutGroupCreatedEvent}.
*
* The rollout is in status {@link RolloutStatus#CREATING} until all rollout
* groups has been created and the targets are split up, then the rollout
* will change the status to {@link RolloutStatus#READY}.
*
* The rollout is not started. Only the preparation of the rollout is done,
* persisting and creating all the necessary groups. The Rollout and the
* groups are persisted in {@link RolloutStatus#READY} and
* {@link RolloutGroupStatus#READY} so they can be started
* {@link #startRollout(Rollout)}.
*
* @param rollout
* the rollout to be created
* @param amountGroup
* the number of groups should be created for the rollout and
* split up the targets
* @param conditions
* the rolloutgroup conditions and actions which should be
* applied for each {@link RolloutGroup}
* @return the created rollout entity in state
* {@link RolloutStatus#CREATING}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE)
Rollout createRolloutAsync(@NotNull Rollout rollout, int amountGroup, @NotNull RolloutGroupConditions conditions);
/**
* Retrieves all rollouts.
*
* @param pageable
* the page request to sort and limit the result
* @return a page of found rollouts
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
Page<Rollout> findAll(@NotNull Pageable pageable);
/**
* Get count of targets in different status in rollout.
*
* @param pageable
* the page request to sort and limit the result
* @return a list of rollouts with details of targets count for different
* statuses
*
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
Page<Rollout> findAllRolloutsWithDetailedStatus(@NotNull Pageable pageable);
/**
* Retrieves all rollouts found by the given specification.
*
* @param rsqlParam
* the specification to filter rollouts
* @param pageable
* the page request to sort and limit the result
* @return a page of found rollouts
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
Page<Rollout> findAllWithDetailedStatusByPredicate(@NotNull String rsqlParam, @NotNull Pageable pageable);
/**
* Finds rollouts by given text in name or description.
*
* @param pageable
* the page request to sort and limit the result
* @param searchText
* search text which matches name or description of rollout
* @return the founded rollout or {@code null} if rollout with given ID does
* not exists
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
Slice<Rollout> findRolloutByFilters(@NotNull Pageable pageable, @NotEmpty String searchText);
/**
* Retrieves a specific rollout by its ID.
*
* @param rolloutId
* the ID of the rollout to retrieve
* @return the founded rollout or {@code null} if rollout with given ID does
* not exists
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
Rollout findRolloutById(@NotNull Long rolloutId);
/**
* Retrieves a specific rollout by its name.
*
* @param rolloutName
* the name of the rollout to retrieve
* @return the founded rollout or {@code null} if rollout with given name
* does not exists
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
Rollout findRolloutByName(@NotNull String rolloutName);
/**
* Get count of targets in different status in rollout.
*
* @param rolloutId
* rollout id
* @return rollout details of targets count for different statuses
*
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
Rollout findRolloutWithDetailedStatus(@NotNull Long rolloutId);
/***
* Get finished percentage details for a specified group which is in running
* state.
*
* @param rolloutId
* the ID of the {@link Rollout}
* @param rolloutGroup
* the ID of the {@link RolloutGroup}
* @return percentage finished
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
float getFinishedPercentForRunningGroup(@NotNull Long rolloutId, @NotNull RolloutGroup rolloutGroup);
/**
* Pauses a rollout which is currently running. The Rollout switches
* {@link RolloutStatus#PAUSED}. {@link RolloutGroup}s which are currently
* running will be untouched. {@link RolloutGroup}s which are
* {@link RolloutGroupStatus#SCHEDULED} will not be started and keep in
* {@link RolloutGroupStatus#SCHEDULED} state until the rollout is
* {@link RolloutManagement#resumeRollout(Rollout)}.
*
* Switching the rollout status to {@link RolloutStatus#PAUSED} is
* sufficient due the {@link #checkRunningRollouts(long)} will not check
* this rollout anymore.
*
* @param rollout
* the rollout to be paused.
*
* @throws RolloutIllegalStateException
* if given rollout is not in {@link RolloutStatus#RUNNING}.
* Only running rollouts can be paused.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_SYSTEM_CODE)
void pauseRollout(@NotNull Rollout rollout);
/**
* Resumes a paused rollout. The rollout switches back to
* {@link RolloutStatus#RUNNING} state which is then picked up again by the
* {@link #checkRunningRollouts(long)}.
*
* @param rollout
* the rollout to be resumed
* @throws RolloutIllegalStateException
* if given rollout is not in {@link RolloutStatus#PAUSED}. Only
* paused rollouts can be resumed.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_SYSTEM_CODE)
void resumeRollout(@NotNull Rollout rollout);
/**
* Starts a rollout which has been created. The rollout must be in
* {@link RolloutStatus#READY} state. The according actions will be created
* for each affected target in the rollout. The actions of the first group
* will be started immediately {@link RolloutGroupStatus#RUNNING} as the
* other groups will be {@link RolloutGroupStatus#SCHEDULED} state.
*
* The rollout itself will be then also in {@link RolloutStatus#RUNNING}.
*
* @param rollout
* the rollout to be started
*
* @return started rollout
*
* @throws RolloutIllegalStateException
* if given rollout is not in {@link RolloutStatus#READY}. Only
* ready rollouts can be started.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_SYSTEM_CODE)
Rollout startRollout(@NotNull Rollout rollout);
/**
* Starts a rollout asynchronously which has been created. The rollout must
* be in {@link RolloutStatus#READY} state. The according actions will be
* created asynchronously for each affected target in the rollout. The
* actions of the first group will be started immediately
* {@link RolloutGroupStatus#RUNNING} as the other groups will be
* {@link RolloutGroupStatus#SCHEDULED} state.
*
* The rollout itself will be then also in {@link RolloutStatus#RUNNING}.
*
* @param rollout
* the rollout to be started
*
* @return the started rollout
*
* @throws RolloutIllegalStateException
* if given rollout is not in {@link RolloutStatus#READY}. Only
* ready rollouts can be started.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_SYSTEM_CODE)
Rollout startRolloutAsync(@NotNull Rollout rollout);
/**
* Update rollout details.
*
* @param rollout
* rollout to be updated
*
* @return Rollout updated rollout
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE)
Rollout updateRollout(@NotNull Rollout rollout);
}

View File

@@ -18,12 +18,6 @@ import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties("hawkbit.rollout")
public class RolloutProperties {
private final Scheduler scheduler = new Scheduler();
public Scheduler getScheduler() {
return scheduler;
}
/**
* Rollout scheduler configuration.
*/
@@ -47,4 +41,10 @@ public class RolloutProperties {
}
private final Scheduler scheduler = new Scheduler();
public Scheduler getScheduler() {
return scheduler;
}
}

View File

@@ -0,0 +1,486 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository;
import java.util.Collection;
import java.util.List;
import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException;
import org.eclipse.hawkbit.repository.model.AssignedSoftwareModule;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.security.access.prepost.PreAuthorize;
/**
* Service for managing {@link SoftwareModule}s.
*
*/
public interface SoftwareManagement {
/**
* Counts {@link SoftwareModule}s with given
* {@link SoftwareModule#getName()} or {@link SoftwareModule#getVersion()}
* and {@link SoftwareModule#getType()} that are not marked as deleted.
*
* @param searchText
* to search for in name and version
* @param type
* to filter the result
* @return number of found {@link SoftwareModule}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Long countSoftwareModuleByFilters(String searchText, SoftwareModuleType type);
/**
* Count all {@link SoftwareModule}s in the repository that are not marked
* as deleted.
*
* @return number of {@link SoftwareModule}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Long countSoftwareModulesAll();
/**
* Counts {@link SoftwareModule}s with given {@link SoftwareModuleType}.
*
* @param type
* to count
* @return number of found {@link SoftwareModule}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Long countSoftwareModulesByType(@NotNull SoftwareModuleType type);
/**
* @return number of {@link SoftwareModuleType}s in the repository.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Long countSoftwareModuleTypesAll();
/**
* Create {@link SoftwareModule}s in the repository.
*
* @param swModules
* {@link SoftwareModule}s to create
* @return SoftwareModule
* @throws EntityAlreadyExistsException
* if a given entity already exists
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
List<SoftwareModule> createSoftwareModule(@NotNull Collection<SoftwareModule> swModules);
/**
*
* @param swModule
* SoftwareModule to create
* @return SoftwareModule
* @throws EntityAlreadyExistsException
* if a given entity already exists
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
SoftwareModule createSoftwareModule(@NotNull SoftwareModule swModule);
/**
* creates a list of software module meta data entries.
*
* @param metadata
* the meta data entries to create or update
* @return the updated or created software module meta data entries
* @throws EntityAlreadyExistsException
* in case one of the meta data entry already exists for the
* specific key
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
List<SoftwareModuleMetadata> createSoftwareModuleMetadata(@NotNull Collection<SoftwareModuleMetadata> metadata);
/**
* creates or updates a single software module meta data entry.
*
* @param metadata
* the meta data entry to create or update
* @return the updated or created software module meta data entry
* @throws EntityAlreadyExistsException
* in case the meta data entry already exists for the specific
* key
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
SoftwareModuleMetadata createSoftwareModuleMetadata(@NotNull SoftwareModuleMetadata metadata);
/**
* Creates multiple {@link SoftwareModuleType}s.
*
* @param types
* to create
* @return created {@link Entity}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
List<SoftwareModuleType> createSoftwareModuleType(@NotNull final Collection<SoftwareModuleType> types);
/**
* Creates new {@link SoftwareModuleType}.
*
* @param type
* to create
* @return created {@link Entity}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
SoftwareModuleType createSoftwareModuleType(@NotNull SoftwareModuleType type);
/**
* Deletes the given {@link SoftwareModule} {@link Entity}.
*
* @param bsm
* is the {@link SoftwareModule} to be deleted
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteSoftwareModule(@NotNull SoftwareModule bsm);
/**
* deletes a software module meta data entry.
*
* @param id
* the ID of the software module meta data to delete
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
void deleteSoftwareModuleMetadata(@NotNull SoftwareModule softwareModule, @NotNull String key);
/**
* Deletes {@link SoftwareModule}s which is any if the given ids.
*
* @param ids
* of the Software Modules to be deleted
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteSoftwareModules(@NotNull Collection<Long> ids);
/**
* Deletes or marks as delete in case the type is in use.
*
* @param type
* to delete
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteSoftwareModuleType(@NotNull SoftwareModuleType type);
/**
* @param pageable
* the page request to page the result set
* @param set
* to search for
* @return all {@link SoftwareModule}s that are assigned to given
* {@link DistributionSet}.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<SoftwareModule> findSoftwareModuleByAssignedTo(@NotNull Pageable pageable, @NotNull DistributionSet set);
/**
* @param pageable
* the page request to page the result set
* @param set
* to search for
* @param type
* to filter
* @return all {@link SoftwareModule}s that are assigned to given
* {@link DistributionSet} filtered by {@link SoftwareModuleType}.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<SoftwareModule> findSoftwareModuleByAssignedToAndType(@NotNull Pageable pageable, @NotNull DistributionSet set,
@NotNull SoftwareModuleType type);
/**
* Filter {@link SoftwareModule}s with given
* {@link SoftwareModule#getName()} or {@link SoftwareModule#getVersion()}
* and {@link SoftwareModule#getType()} that are not marked as deleted.
*
* @param pageable
* page parameter
* @param searchText
* to be filtered as "like" on {@link SoftwareModule#getName()}
* @param type
* to be filtered as "like" on {@link SoftwareModule#getType()}
* @return the page of found {@link SoftwareModule}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Slice<SoftwareModule> findSoftwareModuleByFilters(@NotNull Pageable pageable, String searchText,
SoftwareModuleType type);
/**
* Finds {@link SoftwareModule} by given id.
*
* @param id
* to search for
* @return the found {@link SoftwareModule}s or <code>null</code> if not
* found.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER)
SoftwareModule findSoftwareModuleById(@NotNull Long id);
/**
* retrieves {@link SoftwareModule} by their name AND version AND type..
*
* @param name
* of the {@link SoftwareModule}
* @param version
* of the {@link SoftwareModule}
* @param type
* of the {@link SoftwareModule}
* @return the found {@link SoftwareModule} or <code>null</code>
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
SoftwareModule findSoftwareModuleByNameAndVersion(@NotEmpty String name, @NotEmpty String version,
@NotNull SoftwareModuleType type);
/**
* finds a single software module meta data by its id.
*
* @param id
* the id of the software module meta data containing the meta
* data key and the ID of the software module
* @return the found SoftwareModuleMetadata or {@code null} if not exits
* @throws EntityNotFoundException
* in case the meta data does not exists for the given key
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
SoftwareModuleMetadata findSoftwareModuleMetadata(@NotNull SoftwareModule softwareModule, @NotEmpty String key);
/**
* finds all meta data by the given software module id.
*
* @param swId
* the software module id to retrieve the meta data from
* @param pageable
* the page request to page the result
* @return a paged result of all meta data entries for a given software
* module id
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(@NotNull Long swId,
@NotNull Pageable pageable);
/**
* finds all meta data by the given software module id.
*
* @param softwareModuleId
* the software module id to retrieve the meta data from
* @param spec
* the specification to filter the result
* @param pageable
* the page request to page the result
* @return a paged result of all meta data entries for a given software
* module id
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(@NotNull Long softwareModuleId,
@NotNull String rsqlParam, @NotNull Pageable pageable);
/**
* Filter {@link SoftwareModule}s with given
* {@link SoftwareModule#getName()} or {@link SoftwareModule#getVersion()}
* search text and {@link SoftwareModule#getType()} that are not marked as
* deleted and sort them by means of given distribution set related modules
* on top of the list.
*
* After that the modules are sorted by {@link SoftwareModule#getName()} and
* {@link SoftwareModule#getVersion()} in ascending order.
*
* @param pageable
* page parameter
* @param orderByDistributionId
* the ID of distribution set to be ordered on top
* @param searchText
* filtered as "like" on {@link SoftwareModule#getName()}
* @param type
* filtered as "equal" on {@link SoftwareModule#getType()}
* @return the page of found {@link SoftwareModule}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Slice<AssignedSoftwareModule> findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(
@NotNull Pageable pageable, @NotNull Long orderByDistributionId, String searchText,
SoftwareModuleType type);
/**
* Retrieves all software modules. Deleted ones are filtered.
*
* @param pageable
* pagination parameter
* @return the found {@link SoftwareModule}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Slice<SoftwareModule> findSoftwareModulesAll(@NotNull Pageable pageable);
/**
* Retrieves all software modules with a given list of ids
* {@link SoftwareModule#getId()}.
*
* @param ids
* to search for
* @return {@link List} of found {@link SoftwareModule}s
*/
List<SoftwareModule> findSoftwareModulesById(@NotEmpty Collection<Long> ids);
/**
* Retrieves all {@link SoftwareModule}s with a given specification.
*
* @param spec
* the specification to filter the software modules
* @param pageable
* pagination parameter
* @return the found {@link SoftwareModule}s
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<SoftwareModule> findSoftwareModulesByPredicate(@NotNull String rsqlParam, @NotNull Pageable pageable);
/**
* retrieves the {@link SoftwareModule}s by their {@link SoftwareModuleType}
* .
*
* @param pageable
* page parameters
* @param type
* to be filtered on
* @return the found {@link SoftwareModule}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Slice<SoftwareModule> findSoftwareModulesByType(@NotNull Pageable pageable, @NotNull SoftwareModuleType type);
/**
*
* @param id
* to search for
* @return {@link SoftwareModuleType} in the repository with given
* {@link SoftwareModuleType#getId()}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
SoftwareModuleType findSoftwareModuleTypeById(@NotNull Long id);
/**
*
* @param key
* to search for
* @return {@link SoftwareModuleType} in the repository with given
* {@link SoftwareModuleType#getKey()}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
SoftwareModuleType findSoftwareModuleTypeByKey(@NotNull String key);
/**
*
* @param name
* to search for
* @return all {@link SoftwareModuleType}s in the repository with given
* {@link SoftwareModuleType#getName()}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
SoftwareModuleType findSoftwareModuleTypeByName(@NotNull String name);
/**
* @param pageable
* parameter
* @return all {@link SoftwareModuleType}s in the repository.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<SoftwareModuleType> findSoftwareModuleTypesAll(@NotNull Pageable pageable);
/**
* Retrieves all {@link SoftwareModuleType}s with a given specification.
*
* @param spec
* the specification to filter the software modules types
* @param pageable
* pagination parameter
* @return the found {@link SoftwareModuleType}s
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<SoftwareModuleType> findSoftwareModuleTypesAll(@NotNull String rsqlParam, @NotNull Pageable pageable);
/**
* Retrieves software module including details (
* {@link SoftwareModule#getArtifacts()}).
*
* @param id
* parameter
* @param isDeleted
* parameter
* @return the found {@link SoftwareModule}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
SoftwareModule findSoftwareModuleWithDetails(@NotNull Long id);
/**
* Updates existing {@link SoftwareModule}. Update-able values are
* {@link SoftwareModule#getDescription()}
* {@link SoftwareModule#getVendor()}.
*
* @param sm
* to update
*
* @return the saved {@link Entity}.
*
* @throws NullPointerException
* of {@link SoftwareModule#getId()} is <code>null</code>
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
SoftwareModule updateSoftwareModule(@NotNull SoftwareModule sm);
/**
* updates a distribution set meta data value if corresponding entry exists.
*
* @param metadata
* the meta data entry to be updated
* @return the updated meta data entry
* @throws EntityNotFoundException
* in case the meta data entry does not exists and cannot be
* updated
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
SoftwareModuleMetadata updateSoftwareModuleMetadata(@NotNull SoftwareModuleMetadata metadata);
/**
* Updates existing {@link SoftwareModuleType}. Update-able value is
* {@link SoftwareModuleType#getDescription()} and
* {@link SoftwareModuleType#getColour()}.
*
* @param sm
* to update
* @return updated {@link Entity}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
SoftwareModuleType updateSoftwareModuleType(@NotNull SoftwareModuleType sm);
}

View File

@@ -0,0 +1,93 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository;
import java.util.List;
import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.model.TenantMetaData;
import org.eclipse.hawkbit.repository.report.model.SystemUsageReport;
import org.eclipse.hawkbit.tenancy.TenantAware;
import org.springframework.security.access.prepost.PreAuthorize;
/**
* Central system management operations of the update server.
*
*/
public interface SystemManagement {
/**
* Checks if a specific tenant exists. The tenant will not be created lazy.
*
* @return {@code true} in case the tenant exits or {@code false} if not
*/
String currentTenant();
/**
* Deletes all data related to a given tenant.
*
* @param tenant
* to delete
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_SYSTEM_ADMIN + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_SYSTEM_CODE)
void deleteTenant(@NotNull String tenant);
/**
*
* @return list of all tenant names in the system.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_SYSTEM_ADMIN + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_SYSTEM_CODE)
List<String> findTenants();
/**
* Calculated system usage statistics, both overall for the entire system
* and per tenant;
*
* @return SystemUsageReport of the current system
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_SYSTEM_ADMIN)
SystemUsageReport getSystemUsageStatistics();
/**
* @return {@link TenantMetaData} of {@link TenantAware#getCurrentTenant()}
*/
TenantMetaData getTenantMetadata();
/**
* Returns {@link TenantMetaData} of given and current tenant. Creates for
* new tenants also two {@link SoftwareModuleType} (os and app) and
* {@link RepositoryConstants#DEFAULT_DS_TYPES_IN_TENANT} {@link DistributionSetType}s
* (os and os_app).
*
* DISCLAIMER: this variant is used during initial login (where the tenant
* is not yet in the session). Please user {@link #getTenantMetadata()} for
* regular requests.
*
* @param tenant
* to retrieve data for
* @return {@link TenantMetaData} of given tenant
*/
TenantMetaData getTenantMetadata(@NotNull String tenant);
/**
* Update call for {@link TenantMetaData}.
*
* @param metaData
* to update
* @return updated {@link TenantMetaData} entity
*/
TenantMetaData updateTenantMetadata(@NotNull TenantMetaData metaData);
}

View File

@@ -0,0 +1,248 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository;
import java.util.Collection;
import java.util.List;
import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.eclipse.hawkbit.repository.model.Tag;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetTag;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
/**
* Management service for {@link Tag}s.
*
*/
public interface TagManagement {
/**
* count {@link TargetTag}s.
*
* @return size of {@link TargetTag}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
long countTargetTags();
/**
* Creates a {@link DistributionSet}.
*
* @param distributionSetTag
* to be created.
* @return the new {@link DistributionSet}
* @throws EntityAlreadyExistsException
* if distributionSetTag already exists
*
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
DistributionSetTag createDistributionSetTag(@NotNull DistributionSetTag distributionSetTag);
/**
* Creates multiple {@link DistributionSetTag}s.
*
* @param distributionSetTags
* to be created
* @return the new {@link DistributionSetTag}
* @throws EntityAlreadyExistsException
* if a given entity already exists
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
List<DistributionSetTag> createDistributionSetTags(@NotNull Collection<DistributionSetTag> distributionSetTags);
/**
* Creates a new {@link TargetTag}.
*
* @param targetTag
* to be created
*
* @return the new created {@link TargetTag}
*
* @throws EntityAlreadyExistsException
* if given object already exists
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET)
TargetTag createTargetTag(@NotNull TargetTag targetTag);
/**
* created multiple {@link TargetTag}s.
*
* @param targetTags
* to be created
* @return the new created {@link TargetTag}s
*
* @throws EntityAlreadyExistsException
* if given object has already an ID.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET)
List<TargetTag> createTargetTags(@NotNull Collection<TargetTag> targetTags);
/**
* Deletes {@link DistributionSetTag} by given
* {@link DistributionSetTag#getName()}.
*
* @param tagName
* to be deleted
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteDistributionSetTag(@NotEmpty String tagName);
/**
* Deletes {@link TargetTag} with given name.
*
* @param targetTagName
* tag name of the {@link TargetTag} to be deleted
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_TARGET)
void deleteTargetTag(@NotEmpty String targetTagName);
/**
*
* @return all {@link DistributionSetTag}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
List<DistributionSetTag> findAllDistributionSetTags();
/**
* returns all {@link DistributionSetTag}s.
*
* @param pageReq
* page parameter
* @return all {@link DistributionSetTag}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSetTag> findAllDistributionSetTags(@NotNull Pageable pageReq);
/**
* Retrieves all DistributionSet tags based on the given specification.
*
* @param rsqlParam
* rsql query string
* @param pageable
* pagination parameter
* @return the found {@link DistributionSetTag}s, never {@code null}
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSetTag> findAllDistributionSetTags(@NotNull String rsqlParam, @NotNull Pageable pageable);
/**
* @return all {@link TargetTag}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
List<TargetTag> findAllTargetTags();
/**
* returns all {@link TargetTag}s.
*
* @param pageable
* page parameter
*
* @return all {@link TargetTag}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<TargetTag> findAllTargetTags(@NotNull Pageable pageable);
/**
* Retrieves all target tags based on the given specification.
*
* @param rsqlParam
* rsql query string
* @param pageable
* pagination parameter
* @return the found {@link Target}s, never {@code null}
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<TargetTag> findAllTargetTags(@NotNull String rsqlParam, @NotNull Pageable pageable);
/**
* Find {@link DistributionSet} based on given name.
*
* @param name
* to look for.
* @return {@link DistributionSet} or <code>null</code> if it does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DistributionSetTag findDistributionSetTag(@NotEmpty String name);
/**
* Finds {@link DistributionSetTag} by given id.
*
* @param id
* to search for
* @return the found {@link DistributionSetTag}s or <code>null</code> if not
* found.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
DistributionSetTag findDistributionSetTagById(@NotNull Long id);
/**
* Find {@link TargetTag} based on given Name.
*
* @param name
* to look for.
* @return {@link TargetTag} or <code>null</code> if it does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
TargetTag findTargetTag(@NotEmpty String name);
/**
* Finds {@link TargetTag} by given id.
*
* @param id
* to search for
* @return the found {@link TargetTag}s or <code>null</code> if not found.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
TargetTag findTargetTagById(@NotNull Long id);
/**
* Updates an existing {@link DistributionSetTag}.
*
* @param distributionSetTag
* to be updated
* @return the updated {@link DistributionSet}
* @throws NullPointerException
* of {@link DistributionSetTag#getName()} is <code>null</code>
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetTag updateDistributionSetTag(@NotNull DistributionSetTag distributionSetTag);
/**
* updates the {@link TargetTag}.
*
* @param targetTag
* the {@link TargetTag} with updated values
* @return the updated {@link TargetTag}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET)
TargetTag updateTargetTag(@NotNull TargetTag targetTag);
}

View File

@@ -0,0 +1,117 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository;
import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException;
import org.eclipse.hawkbit.repository.model.TargetFilterQuery;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
/**
* Management service for {@link TargetFilterQuery}s.
*
*/
public interface TargetFilterQueryManagement {
/**
* creating new {@link TargetFilterQuery}.
*
* @param customTargetFilter
* @return the created {@link TargetFilterQuery}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET)
TargetFilterQuery createTargetFilterQuery(@NotNull TargetFilterQuery customTargetFilter);
/**
* Delete target filter query.
*
* @param targetFilterQueryId
* IDs of target filter query to be deleted
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_TARGET)
void deleteTargetFilterQuery(@NotNull Long targetFilterQueryId);
/**
* Verifies provided filter syntax.
*
* @param query
* to verify
*
* @return <code>true</code> if syntax is valid
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
boolean verifyTargetFilterQuerySyntax(String query);
/**
*
* Retrieves all target filter query{@link TargetFilterQuery}.
*
* @param pageable
* pagination parameter
* @return the found {@link TargetFilterQuery}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<TargetFilterQuery> findAllTargetFilterQuery(@NotNull Pageable pageable);
/**
* Retrieves all target filter query which {@link TargetFilterQuery}.
*
*
* @param pageable
* pagination parameter
* @param name
* target filter query name
* @return the page with the found {@link TargetFilterQuery}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<TargetFilterQuery> findTargetFilterQueryByFilters(@NotNull Pageable pageable, String name);
/**
* Find target filter query by id.
*
* @param targetFilterQueryId
* Target filter query id
* @return the found {@link TargetFilterQuery}
*
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
TargetFilterQuery findTargetFilterQueryById(@NotNull Long targetFilterQueryId);
/**
* Find target filter query by name.
*
* @param targetFilterQueryName
* Target filter query name
* @return the found {@link TargetFilterQuery}
*
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
TargetFilterQuery findTargetFilterQueryByName(@NotNull String targetFilterQueryName);
/**
* updates the {@link TargetFilterQuery}.
*
* @param targetFilterQuery
* to be updated
* @return the updated {@link TargetFilterQuery}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET)
TargetFilterQuery updateTargetFilterQuery(@NotNull TargetFilterQuery targetFilterQuery);
}

View File

@@ -0,0 +1,617 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository;
import java.net.URI;
import java.util.Collection;
import java.util.List;
import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.Tag;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetFilterQuery;
import org.eclipse.hawkbit.repository.model.TargetIdName;
import org.eclipse.hawkbit.repository.model.TargetInfo;
import org.eclipse.hawkbit.repository.model.TargetTag;
import org.eclipse.hawkbit.repository.model.TargetTagAssignmentResult;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.security.access.prepost.PreAuthorize;
/**
* Management service for {@link Target}s.
*
*/
public interface TargetManagement {
/**
* Assign a {@link TargetTag} assignment to given {@link Target}s.
*
* @param targetIds
* to assign for
* @param tag
* to assign
* @return list of assigned targets
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET)
List<Target> assignTag(@NotEmpty Collection<String> targetIds, @NotNull TargetTag tag);
/**
* Counts number of targets with given
* {@link Target#getAssignedDistributionSet()}.
*
* @param distId
* to search for
*
* @return number of found {@link Target}s.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Long countTargetByAssignedDistributionSet(@NotNull Long distId);
/**
* Count {@link Target}s for all the given filter parameters.
*
* @param status
* find targets having on of these {@link TargetUpdateStatus}s.
* Set to <code>null</code> in case this is not required.
* @param searchText
* to find targets having the text anywhere in name or
* description. Set <code>null</code> in case this is not
* required.
* @param installedOrAssignedDistributionSetId
* to find targets having the {@link DistributionSet} as
* installed or assigned. Set to <code>null</code> in case this
* is not required.
* @param tagNames
* to find targets which are having any one in this tag names.
* Set <code>null</code> in case this is not required.
* @param selectTargetWithNoTag
* flag to select targets with no tag assigned
*
* @return the found number {@link Target}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Long countTargetByFilters(Collection<TargetUpdateStatus> status, String searchText,
Long installedOrAssignedDistributionSetId, Boolean selectTargetWithNoTag, String... tagNames);
/**
* Counts number of targets with given
* {@link TargetInfo#getInstalledDistributionSet()}.
*
* @param distId
* to search for
* @return number of found {@link Target}s.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Long countTargetByInstalledDistributionSet(@NotNull Long distId);
/**
* Count {@link TargetFilterQuery}s for given target filter query.
*
* @param targetFilterQuery
* {link TargetFilterQuery}
* @return the found number {@link TargetFilterQuery}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Long countTargetByTargetFilterQuery(@NotEmpty String targetFilterQuery);
/**
* Count {@link TargetFilterQuery}s for given filter parameter.
*
* @param targetFilterQuery
* {link TargetFilterQuery}
* @return the found number {@link TargetFilterQuery}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Long countTargetByTargetFilterQuery(@NotNull TargetFilterQuery targetFilterQuery);
/**
* Counts all {@link Target}s in the repository.
*
* @return number of targets
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Long countTargetsAll();
/**
* creating a new {@link Target}.
*
* @param target
* to be created
* @return the created {@link Target}
*
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER)
Target createTarget(@NotNull Target target);
/**
* creating new {@link Target}s including poll status data. useful
* especially in plug and play scenarios.
*
* @param target
* to be created *
* @param status
* of the target
* @param lastTargetQuery
* if a plug and play case
* @param address
* if a plug and play case
*
* @throws EntityAlreadyExistsException
* if {@link Target} with given {@link Target#getControllerId()}
* already exists.
*
* @return created {@link Target}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER)
Target createTarget(@NotNull Target target, @NotNull TargetUpdateStatus status, Long lastTargetQuery, URI address);
/**
* creates multiple {@link Target}s. If some of the given {@link Target}s
* already exists in the DB a {@link EntityAlreadyExistsException} is
* thrown. {@link Target}s contain all objects of the parameter targets,
* including duplicates.
*
* @param targets
* to be created.
* @return the created {@link Target}s
*
* @throws EntityAlreadyExistsException
* of one of the given targets already exist.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET)
List<Target> createTargets(@NotNull Collection<Target> targets);
/**
* creating a new {@link Target} including poll status data. useful
* especially in plug and play scenarios.
*
* @param targets
* to be created *
* @param status
* of the target
* @param lastTargetQuery
* if a plug and play case
* @param address
* if a plug and play case
*
* @return newly created target
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET)
List<Target> createTargets(@NotNull Collection<Target> targets, @NotNull TargetUpdateStatus status,
Long lastTargetQuery, URI address);
/**
* Deletes all targets with the given IDs.
*
* @param targetIDs
* the technical IDs of the targets to be deleted
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_TARGET)
void deleteTargets(@NotEmpty Long... targetIDs);
/**
* finds all {@link Target#getControllerId()} which are currently in the
* database.
*
* @return all IDs of all {@link Target} in the system
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
List<TargetIdName> findAllTargetIds();
/**
* Finds all targets for all the given parameters but returns not the full
* target but {@link TargetIdName}.
*
* @param pageRequest
* the pageRequest to enhance the query for paging and sorting
*
* @param filterByStatus
* find targets having this {@link TargetUpdateStatus}s. Set to
* <code>null</code> in case this is not required.
* @param filterBySearchText
* to find targets having the text anywhere in name or
* description. Set <code>null</code> in case this is not
* required.
* @param installedOrAssignedDistributionSetId
* to find targets having the {@link DistributionSet} as
* installed or assigned. Set to <code>null</code> in case this
* is not required.
* @param filterByTagNames
* to find targets which are having any one in this tag names.
* Set <code>null</code> in case this is not required.
* @param selectTargetWithNoTag
* flag to select targets with no tag assigned
*
* @return the found {@link TargetIdName}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
List<TargetIdName> findAllTargetIdsByFilters(@NotNull Pageable pageRequest,
Collection<TargetUpdateStatus> filterByStatus, String filterBySearchText,
Long installedOrAssignedDistributionSetId, Boolean selectTargetWithNoTag, String... filterByTagNames);
/**
* Finds all targets for all the given parameter {@link TargetFilterQuery}
* and returns not the full target but {@link TargetIdName}.
*
* @param pageRequest
* the pageRequest to enhance the query for paging and sorting
* @param targetFilterQuery
* {@link TargetFilterQuery}
* @return the found {@link TargetIdName}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
List<TargetIdName> findAllTargetIdsByTargetFilterQuery(@NotNull Pageable pageRequest,
@NotNull TargetFilterQuery targetFilterQuery);
/**
* retrieves {@link Target}s by the assigned {@link DistributionSet} without
* details, i.e. NO {@link Target#getTags()} and {@link Target#getActions()}
* possible.
*
*
* @param distributionSetID
* the ID of the {@link DistributionSet}
* @param pageReq
* page parameter
* @return the found {@link Target}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_READ_TARGET)
Page<Target> findTargetByAssignedDistributionSet(@NotNull Long distributionSetID, @NotNull Pageable pageReq);
/**
* Retrieves {@link Target}s by the assigned {@link DistributionSet} without
* details, i.e. NO {@link Target#getTags()} and {@link Target#getActions()}
* possible including additional filtering based on the given {@code spec}.
*
* @param distributionSetID
* the ID of the {@link DistributionSet}
* @param rsqlParam
* the specification to filter the result set
* @param pageReq
* page parameter
* @return the found {@link Target}s, never {@code null}
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_READ_TARGET)
Page<Target> findTargetByAssignedDistributionSet(@NotNull Long distributionSetID, @NotNull String rsqlParam,
@NotNull Pageable pageReq);
/**
* Find {@link Target} based on given ID returns found Target without
* details, i.e. NO {@link Target#getTags()} and {@link Target#getActions()}
* possible.
*
* @param controllerIDs
* to look for.
* @return List of found{@link Target}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
List<Target> findTargetByControllerID(@NotEmpty Collection<String> controllerIDs);
/**
* Find {@link Target} based on given ID returns found Target without
* details, i.e. NO {@link Target#getTags()} and {@link Target#getActions()}
* possible.
*
* @param controllerId
* to look for.
* @return {@link Target} or <code>null</code> if it does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Target findTargetByControllerID(@NotEmpty String controllerId);
/**
* Find {@link Target} based on given ID returns found Target with details,
* i.e. {@link Target#getTags()} and {@link Target#getActions()} are
* possible.
*
* Note: try to use {@link #findTargetByControllerID(String)} as much as
* possible.
*
* @param controllerId
* to look for.
* @return {@link Target} or <code>null</code> if it does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Target findTargetByControllerIDWithDetails(@NotEmpty String controllerId);
/**
* Filter {@link Target}s for all the given parameters. If all parameters
* except pageable are null, all available {@link Target}s are returned.
*
* @param pageable
* page parameters
* @param status
* find targets having this {@link TargetUpdateStatus}s. Set to
* <code>null</code> in case this is not required.
* @param searchText
* to find targets having the text anywhere in name or
* description. Set <code>null</code> in case this is not
* required.
* @param installedOrAssignedDistributionSetId
* to find targets having the {@link DistributionSet} as
* installed or assigned. Set to <code>null</code> in case this
* is not required.
* @param tagNames
* to find targets which are having any one in this tag names.
* Set <code>null</code> in case this is not required.
* @param selectTargetWithNoTag
* flag to select targets with no tag assigned
*
* @return the found {@link Target}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Slice<Target> findTargetByFilters(@NotNull Pageable pageable, Collection<TargetUpdateStatus> status,
String searchText, Long installedOrAssignedDistributionSetId, Boolean selectTargetWithNoTag,
String... tagNames);
/**
* retrieves {@link Target}s by the installed {@link DistributionSet}without
* details, i.e. NO {@link Target#getTags()} and {@link Target#getActions()}
* possible.
*
* @param distributionSetID
* the ID of the {@link DistributionSet}
* @param pageReq
* page parameter
* @return the found {@link Target}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_READ_TARGET)
Page<Target> findTargetByInstalledDistributionSet(@NotNull Long distributionSetID, @NotNull Pageable pageReq);
/**
* retrieves {@link Target}s by the installed {@link DistributionSet}without
* details, i.e. NO {@link Target#getTags()} and {@link Target#getActions()}
* possible including additional filtering based on the given {@code spec}.
*
* @param distributionSetId
* the ID of the {@link DistributionSet}
* @param rsqlParam
* the specification to filter the result
* @param pageable
* page parameter
* @return the found {@link Target}s, never {@code null}
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_READ_TARGET)
Page<Target> findTargetByInstalledDistributionSet(@NotNull Long distributionSetId, @NotNull String rsqlParam,
@NotNull Pageable pageable);
/**
* Retrieves the {@link Target} which have a certain
* {@link TargetUpdateStatus} without details, i.e. NO
* {@link Target#getTags()} and {@link Target#getActions()} possible.
*
* @param pageable
* page parameter
* @param status
* the {@link TargetUpdateStatus} to be filtered on
* @return the found {@link Target}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<Target> findTargetByUpdateStatus(@NotNull Pageable pageable, @NotNull TargetUpdateStatus status);
/**
* Retrieves all targets without details, i.e. NO {@link Target#getTags()}
* and {@link Target#getActions()} possible
*
* @param pageable
* pagination parameter
* @return the found {@link Target}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Slice<Target> findTargetsAll(@NotNull Pageable pageable);
/**
* Retrieves all targets without details, i.e. NO {@link Target#getTags()}
* and {@link Target#getActions()} possible based on
* {@link TargetFilterQuery#getQuery()}
*
* @param targetFilterQuery
* in string notation
* @param pageable
* pagination parameter
*
* @return the found {@link Target}s, never {@code null}
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<Target> findTargetsAll(@NotNull String targetFilterQuery, @NotNull Pageable pageable);
/**
* Retrieves all targets without details, i.e. NO {@link Target#getTags()}
* and {@link Target#getActions()} possible based on
* {@link TargetFilterQuery#getQuery()}
*
* @param targetFilterQuery
* the specification for the query
* @param pageable
* pagination parameter
*
* @return the found {@link Target}s, never {@code null}
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Slice<Target> findTargetsAll(@NotNull TargetFilterQuery targetFilterQuery, @NotNull Pageable pageable);
/**
* method retrieves all {@link Target}s from the repo in the following
* order:
* <p>
* 1) {@link Target}s which have the given {@link DistributionSet} as
* {@link Target#getTargetInfo()}
* {@link TargetInfo#getInstalledDistributionSet()}
* <p>
* 2) {@link Target}s which have the given {@link DistributionSet} as
* {@link Target#getAssignedDistributionSet()}
* <p>
* 3) {@link Target}s which have no connection to the given
* {@link DistributionSet}.
*
* @param pageable
* the page request to page the result set
* @param orderByDistributionId
* {@link DistributionSet#getId()} to be ordered by
* @param filterByDistributionId
* {@link DistributionSet#getId()} to be filter the result. Set
* to <code>null</code> in case this is not required.
* @param filterByStatus
* find targets having this {@link TargetUpdateStatus}s. Set to
* <code>null</code> in case this is not required.
* @param filterBySearchText
* to find targets having the text anywhere in name or
* description. Set <code>null</code> in case this is not
* required.
* @param installedOrAssignedDistributionSetId
* to find targets having the {@link DistributionSet} as
* installed or assigned. Set to <code>null</code> in case this
* is not required.
* @param filterByTagNames
* to find targets which are having any one in this tag names.
* Set <code>null</code> in case this is not required.
* @param selectTargetWithNoTag
* flag to select targets with no tag assigned
* @return a paged result {@link Page} of the {@link Target}s in a defined
* order.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Slice<Target> findTargetsAllOrderByLinkedDistributionSet(@NotNull Pageable pageable,
@NotNull Long orderByDistributionId, Long filterByDistributionId,
Collection<TargetUpdateStatus> filterByStatus, String filterBySearchText, Boolean selectTargetWithNoTag,
String... filterByTagNames);
/**
* retrieves a list of {@link Target}s by their controller ID with details,
* i.e. {@link Target#getTags()} are possible.
*
* Note: try to use {@link #findTargetByControllerID(String)} as much as
* possible.
*
* @param controllerIDs
* {@link Target}s Names parameter
* @return the found {@link Target}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
List<Target> findTargetsByControllerIDsWithTags(@NotNull List<String> controllerIDs);
/**
* Find targets by tag name.
*
* @param tagName
* tag name
* @return list of matching targets
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
List<Target> findTargetsByTag(@NotEmpty String tagName);
/**
* Toggles {@link TargetTag} assignment to given {@link Target}s by means
* that if some (or all) of the targets in the list have the {@link Tag} not
* yet assigned, they will be. If all of theme have the tag already assigned
* they will be removed instead.
*
* @param targetIds
* to toggle for
* @param tagName
* to toggle
* @return TagAssigmentResult with all meta data of the assignment outcome.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET)
TargetTagAssignmentResult toggleTagAssignment(@NotEmpty Collection<String> targetIds, @NotEmpty String tagName);
/**
* {@link Target} based method call for
* {@link #toggleTagAssignment(Collection, String)}.
*
* @param targets
* to toggle for
* @param tag
* to toggle
* @return TagAssigmentResult with all meta data of the assignment outcome.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET)
TargetTagAssignmentResult toggleTagAssignment(@NotEmpty Collection<Target> targets, @NotNull TargetTag tag);
/**
* Un-assign all {@link Target} from a given {@link TargetTag} .
*
* @param tag
* to un-assign all targets
* @return list of unassigned targets
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET)
List<Target> unAssignAllTargetsByTag(@NotNull TargetTag tag);
/**
* Un-assign a {@link TargetTag} assignment to given {@link Target}.
*
* @param controllerID
* to un-assign for
* @param targetTag
* to un-assign
* @return the unassigned target or <null> if no target is unassigned
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET)
Target unAssignTag(@NotEmpty String controllerID, @NotNull TargetTag targetTag);
/**
* updates the {@link Target}.
*
* @param target
* to be updated
* @return the updated {@link Target}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER)
Target updateTarget(@NotNull Target target);
/**
* updates multiple {@link Target}s.
*
* @param targets
* to be updated
* @return the updated {@link Target}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER)
List<Target> updateTargets(@NotNull Collection<Target> targets);
}

View File

@@ -0,0 +1,145 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.model.TenantConfiguration;
import org.eclipse.hawkbit.repository.model.TenantConfigurationValue;
import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey;
import org.eclipse.hawkbit.tenancy.configuration.validator.TenantConfigurationValidatorException;
import org.springframework.core.convert.ConversionFailedException;
import org.springframework.core.env.Environment;
import org.springframework.security.access.prepost.PreAuthorize;
/**
* Management service for tenant configurations.
*
*/
public interface TenantConfigurationManagement {
/**
* Adds or updates a specific configuration for a specific tenant.
*
*
* @param configurationKey
* the key of the configuration
* @param value
* the configuration value which will be written into the
* database.
* @return the configuration value which was just written into the database.
* @throws TenantConfigurationValidatorException
* if the {@code propertyType} and the value in general does not
* match the expected type and format defined by the Key
* @throws ConversionFailedException
* if the property cannot be converted to the given
*/
@PreAuthorize(value = SpringEvalExpressions.HAS_AUTH_TENANT_CONFIGURATION)
<T> TenantConfigurationValue<T> addOrUpdateConfiguration(TenantConfigurationKey configurationKey, T value);
/**
* Build the tenant configuration by the given key
*
* @param configurationKey
* the key
* @param propertyType
* the property type
* @param tenantConfiguration
* the configuration
* @return <null> if no default value is set and no database value available
* or returns the tenant configuration value
*/
@PreAuthorize(value = SpringEvalExpressions.HAS_AUTH_TENANT_CONFIGURATION + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_SYSTEM_CODE)
<T> TenantConfigurationValue<T> buildTenantConfigurationValueByKey(TenantConfigurationKey configurationKey,
Class<T> propertyType, TenantConfiguration tenantConfiguration);
/**
* Deletes a specific configuration for the current tenant. Does nothing in
* case there is no tenant specific configuration value.
*
* @param configurationKey
* the configuration key to be deleted
*/
@PreAuthorize(value = SpringEvalExpressions.HAS_AUTH_TENANT_CONFIGURATION)
void deleteConfiguration(TenantConfigurationKey configurationKey);
/**
* Retrieves a configuration value from the e.g. tenant overwritten
* configuration values or in case the tenant does not a have a specific
* configuration the global default value hold in the {@link Environment}.
*
* @param configurationKey
* the key of the configuration
* @return the converted configuration value either from the tenant specific
* configuration stored or from the fall back default values or
* {@code null} in case key has not been configured and not default
* value exists
* @throws TenantConfigurationValidatorException
* if the {@code propertyType} and the value in general does not
* match the expected type and format defined by the Key
* @throws ConversionFailedException
* if the property cannot be converted to the given
* {@code propertyType}
*/
@PreAuthorize(value = SpringEvalExpressions.HAS_AUTH_TENANT_CONFIGURATION + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_SYSTEM_CODE)
<T> TenantConfigurationValue<T> getConfigurationValue(TenantConfigurationKey configurationKey);
/**
* Retrieves a configuration value from the e.g. tenant overwritten
* configuration values or in case the tenant does not a have a specific
* configuration the global default value hold in the {@link Environment}.
*
* @param <T>
* the type of the configuration value
* @param configurationKey
* the key of the configuration
* @param propertyType
* the type of the configuration value, e.g. {@code String.class}
* , {@code Integer.class}, etc
* @return the converted configuration value either from the tenant specific
* configuration stored or from the fallback default values or
* {@code null} in case key has not been configured and not default
* value exists
* @throws TenantConfigurationValidatorException
* if the {@code propertyType} and the value in general does not
* match the expected type and format defined by the Key
* @throws ConversionFailedException
* if the property cannot be converted to the given
* {@code propertyType}
*/
@PreAuthorize(value = SpringEvalExpressions.HAS_AUTH_TENANT_CONFIGURATION + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_SYSTEM_CODE)
<T> TenantConfigurationValue<T> getConfigurationValue(TenantConfigurationKey configurationKey,
Class<T> propertyType);
/**
* returns the global configuration property either defined in the property
* file or an default value otherwise.
*
* @param <T>
* the type of the configuration value
* @param configurationKey
* the key of the configuration
* @param propertyType
* the type of the configuration value, e.g. {@code String.class}
* , {@code Integer.class}, etc
* @return the global configured value
* @throws TenantConfigurationValidatorException
* if the {@code propertyType} and the value in the property
* file or the default value does not match the expected type
* and format defined by the Key
* @throws ConversionFailedException
* if the property cannot be converted to the given
* {@code propertyType}
*/
@PreAuthorize(value = SpringEvalExpressions.HAS_AUTH_TENANT_CONFIGURATION + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_SYSTEM_CODE)
<T> T getGlobalConfigurationValue(TenantConfigurationKey configurationKey, Class<T> propertyType);
}

View File

@@ -0,0 +1,34 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.report.model.TenantUsage;
import org.springframework.security.access.prepost.PreAuthorize;
/**
* Management service for statistics of a single tenant.
*
*/
@FunctionalInterface
public interface TenantStatsManagement {
/**
* Service for stats of a single tenant. Opens a new transaction and as a
* result can an be used for multiple tenants, i.e. to allow in one session
* to collect data of all tenants in the system.
*
* @param tenant
* to collect for
* @return collected statistics
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_SYSTEM_ADMIN)
TenantUsage getStatsOfTenant(String tenant);
}

View File

@@ -6,8 +6,10 @@
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.eventbus.event;
package org.eclipse.hawkbit.repository.eventbus.event;
import org.eclipse.hawkbit.eventbus.event.AbstractDistributedEvent;
import org.eclipse.hawkbit.eventbus.event.EntityEvent;
import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity;
/**

View File

@@ -6,7 +6,7 @@
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.eventbus.event;
package org.eclipse.hawkbit.repository.eventbus.event;
import java.util.Arrays;
import java.util.List;

View File

@@ -6,7 +6,7 @@
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.eventbus.event;
package org.eclipse.hawkbit.repository.eventbus.event;
import java.util.Map;

View File

@@ -6,7 +6,7 @@
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.eventbus.event;
package org.eclipse.hawkbit.repository.eventbus.event;
import org.eclipse.hawkbit.repository.model.Action;

View File

@@ -6,7 +6,7 @@
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.eventbus.event;
package org.eclipse.hawkbit.repository.eventbus.event;
import java.util.Map;

View File

@@ -6,7 +6,7 @@
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.eventbus.event;
package org.eclipse.hawkbit.repository.eventbus.event;
import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult;

View File

@@ -6,7 +6,7 @@
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.eventbus.event;
package org.eclipse.hawkbit.repository.eventbus.event;
import java.util.List;

View File

@@ -6,7 +6,7 @@
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.eventbus.event;
package org.eclipse.hawkbit.repository.eventbus.event;
import org.eclipse.hawkbit.repository.model.DistributionSetTag;

View File

@@ -6,7 +6,7 @@
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.eventbus.event;
package org.eclipse.hawkbit.repository.eventbus.event;
import org.eclipse.hawkbit.repository.model.DistributionSetTag;

View File

@@ -6,11 +6,12 @@
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.eventbus.event;
package org.eclipse.hawkbit.repository.eventbus.event;
import java.io.Serializable;
import java.util.List;
import org.eclipse.hawkbit.eventbus.event.Event;
import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity;
/**

View File

@@ -6,7 +6,7 @@
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.eventbus.event;
package org.eclipse.hawkbit.repository.eventbus.event;
import org.eclipse.hawkbit.eventbus.event.AbstractEvent;

View File

@@ -6,7 +6,9 @@
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.eventbus.event;
package org.eclipse.hawkbit.repository.eventbus.event;
import org.eclipse.hawkbit.eventbus.event.AbstractEvent;
/**
* Event declaration for the UI to notify the UI that a rollout has been

View File

@@ -6,7 +6,9 @@
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.eventbus.event;
package org.eclipse.hawkbit.repository.eventbus.event;
import org.eclipse.hawkbit.eventbus.event.AbstractDistributedEvent;
/**
* Event definition which is been published in case a rollout group has been

View File

@@ -6,7 +6,7 @@
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.eventbus.event;
package org.eclipse.hawkbit.repository.eventbus.event;
import java.util.Map;

Some files were not shown because too many files have changed in this diff Show More