diff --git a/.gitignore b/.gitignore index 8cd3d476e..e49219859 100644 --- a/.gitignore +++ b/.gitignore @@ -53,3 +53,5 @@ local.properties # Maven maven.properties /*/maven.properties + +hawkbit-repository/hawkbit-repository-jpa/.springBeans diff --git a/examples/hawkbit-custom-theme-example/pom.xml b/examples/hawkbit-custom-theme-example/pom.xml index 7caa99ba2..875db18e3 100644 --- a/examples/hawkbit-custom-theme-example/pom.xml +++ b/examples/hawkbit-custom-theme-example/pom.xml @@ -79,6 +79,11 @@ hawkbit-http-security ${project.version} + + org.eclipse.hawkbit + hawkbit-repository-jpa + ${project.version} + diff --git a/examples/hawkbit-custom-theme-example/src/main/java/org/eclipse/hawkbit/app/Start.java b/examples/hawkbit-custom-theme-example/src/main/java/org/eclipse/hawkbit/app/Start.java index abf2740fa..7f80eb05b 100644 --- a/examples/hawkbit-custom-theme-example/src/main/java/org/eclipse/hawkbit/app/Start.java +++ b/examples/hawkbit-custom-theme-example/src/main/java/org/eclipse/hawkbit/app/Start.java @@ -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. diff --git a/examples/hawkbit-device-simulator/pom.xml b/examples/hawkbit-device-simulator/pom.xml index 1b1bc5fdc..3c3df9486 100644 --- a/examples/hawkbit-device-simulator/pom.xml +++ b/examples/hawkbit-device-simulator/pom.xml @@ -116,10 +116,6 @@ org.springframework.boot spring-boot-autoconfigure - - org.springframework.boot - spring-boot-autoconfigure - com.google.guava guava @@ -127,12 +123,10 @@ com.netflix.feign feign-jackson - 8.14.1 com.netflix.feign feign-core - 8.12.1 com.jayway.jsonpath diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DeviceSimulatorUpdater.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DeviceSimulatorUpdater.java index 34c5f548e..0931f6f3e 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DeviceSimulatorUpdater.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DeviceSimulatorUpdater.java @@ -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)) { diff --git a/examples/hawkbit-example-app/pom.xml b/examples/hawkbit-example-app/pom.xml index 957ba8d6a..f501d5529 100644 --- a/examples/hawkbit-example-app/pom.xml +++ b/examples/hawkbit-example-app/pom.xml @@ -92,6 +92,11 @@ hawkbit-http-security ${project.version} + + org.eclipse.hawkbit + hawkbit-repository-jpa + ${project.version} + diff --git a/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/Start.java b/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/Start.java index 4a3e6028a..95fb39147 100644 --- a/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/Start.java +++ b/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/Start.java @@ -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 { diff --git a/examples/hawkbit-example-mgmt-simulator/.gitignore b/examples/hawkbit-example-mgmt-simulator/.gitignore index 4b9b73073..b5c3eb864 100644 --- a/examples/hawkbit-example-mgmt-simulator/.gitignore +++ b/examples/hawkbit-example-mgmt-simulator/.gitignore @@ -1,3 +1,4 @@ /target/ /bin/ /.apt_generated/ +/.springBeans diff --git a/hawkbit-artifact-repository-mongo/src/main/java/org/eclipse/hawkbit/artifact/repository/ArtifactStore.java b/hawkbit-artifact-repository-mongo/src/main/java/org/eclipse/hawkbit/artifact/repository/ArtifactStore.java index 5f12498ff..aa9ff3409 100644 --- a/hawkbit-artifact-repository-mongo/src/main/java/org/eclipse/hawkbit/artifact/repository/ArtifactStore.java +++ b/hawkbit-artifact-repository-mongo/src/main/java/org/eclipse/hawkbit/artifact/repository/ArtifactStore.java @@ -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); diff --git a/hawkbit-autoconfigure/pom.xml b/hawkbit-autoconfigure/pom.xml index 7ad0e0911..044e6aece 100644 --- a/hawkbit-autoconfigure/pom.xml +++ b/hawkbit-autoconfigure/pom.xml @@ -46,7 +46,7 @@ org.eclipse.hawkbit - hawkbit-repository + hawkbit-repository-jpa ${project.version} true diff --git a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/eventbus/EventBusAutoConfiguration.java b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/eventbus/EventBusAutoConfiguration.java index 37e72880c..d4cc32825 100644 --- a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/eventbus/EventBusAutoConfiguration.java +++ b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/eventbus/EventBusAutoConfiguration.java @@ -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; diff --git a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/repository/JpaRepositoryAutoConfiguration.java b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/repository/JpaRepositoryAutoConfiguration.java new file mode 100644 index 000000000..dd6ead86b --- /dev/null +++ b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/repository/JpaRepositoryAutoConfiguration.java @@ -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 { + +} diff --git a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityAutoConfiguration.java b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityAutoConfiguration.java index d74b27dc8..5009ba74f 100644 --- a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityAutoConfiguration.java +++ b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityAutoConfiguration.java @@ -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; diff --git a/hawkbit-core/src/main/java/org/eclipse/hawkbit/tenancy/configuration/TenantConfigurationKey.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/tenancy/configuration/TenantConfigurationKey.java index 402185be3..d68e963be 100644 --- a/hawkbit-core/src/main/java/org/eclipse/hawkbit/tenancy/configuration/TenantConfigurationKey.java +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/tenancy/configuration/TenantConfigurationKey.java @@ -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 Class getDataType() { + return (Class) dataType; } /** diff --git a/hawkbit-ddi-resource/pom.xml b/hawkbit-ddi-resource/pom.xml index f3eb5c2c7..cb85f8c8c 100644 --- a/hawkbit-ddi-resource/pom.xml +++ b/hawkbit-ddi-resource/pom.xml @@ -38,7 +38,7 @@ org.eclipse.hawkbit - hawkbit-repository + hawkbit-repository-api ${project.version} @@ -48,6 +48,18 @@ + + org.eclipse.hawkbit + hawkbit-repository-test + ${project.version} + test + + + org.eclipse.hawkbit + hawkbit-repository-jpa + ${project.version} + test + org.eclipse.hawkbit hawkbit-rest-core @@ -93,7 +105,7 @@ org.eclipse.hawkbit - hawkbit-repository + hawkbit-repository-jpa ${project.version} tests test diff --git a/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactStoreController.java b/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactStoreController.java index 9c51cf8f4..85a326f9a 100644 --- a/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactStoreController.java +++ b/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactStoreController.java @@ -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 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; } diff --git a/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootController.java b/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootController.java index 3bf70ccfd..20d1b2e29 100644 --- a/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootController.java +++ b/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootController.java @@ -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> 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()); diff --git a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactDownloadTest.java b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactDownloadTest.java index 6c3bdea4e..b3828582c 100644 --- a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactDownloadTest.java +++ b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactDownloadTest.java @@ -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 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 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 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); @@ -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 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 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 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 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); diff --git a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiCancelActionTest.java b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiCancelActionTest.java index 9913d5e51..821c8b8ad 100644 --- a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiCancelActionTest.java +++ b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiCancelActionTest.java @@ -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 toAssign = new ArrayList(); @@ -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 toAssign = new ArrayList(); @@ -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 toAssign = new ArrayList(); 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 toAssign = new ArrayList(); toAssign.add(target); diff --git a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiConfigDataTest.java b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiConfigDataTest.java index 4a86cfe8c..395e2284c 100644 --- a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiConfigDataTest.java +++ b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiConfigDataTest.java @@ -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 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 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 diff --git a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiDeploymentBaseTest.java b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiDeploymentBaseTest.java index eb3ed8844..33d470b3d 100644 --- a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiDeploymentBaseTest.java +++ b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiDeploymentBaseTest.java @@ -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 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 actionStatusMessages = actionStatusRepository - .findAll(new PageRequest(0, 100, Direction.DESC, "id")); - assertThat(actionStatusMessages).hasSize(3); + final Iterable 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 saved = deploymentManagement - .assignDistributionSet(ds.getId(), ActionType.SOFT, Action.NO_FORCE_TIME, savedTarget.getControllerId()) - .getAssignedEntity(); + List 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 actionStatusMessages = actionStatusRepository - .findAll(new PageRequest(0, 100, Direction.DESC, "id")); - assertThat(actionStatusMessages).hasSize(3); + final List 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 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 actionStatusMessages = actionStatusRepository - .findAll(new PageRequest(0, 100, Direction.DESC, "id")); - assertThat(actionStatusMessages).hasSize(3); + final Iterable 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 toAssign = new ArrayList(); + final List 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 toAssign = new ArrayList(); + final List 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 toAssign = new ArrayList(); + final List 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 actionStatusMessages = actionStatusRepository.findAll(new Sort(Direction.DESC, "id")); + Iterable 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 toAssign = new ArrayList(); + List 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 actionStatusMessages = actionStatusRepository.findAll(); + final Iterable 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 toAssign = new ArrayList(); + final List 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()) diff --git a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootControllerTest.java b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootControllerTest.java index 8041e8b36..135754604 100644 --- a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootControllerTest.java +++ b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootControllerTest.java @@ -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 toAssign = new ArrayList(); + final List toAssign = new ArrayList<>(); toAssign.add(savedTarget); savedTarget = deploymentManagement.assignDistributionSet(ds, toAssign).getAssignedEntity().iterator().next(); final Action savedAction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0); diff --git a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DosFilterTest.java b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DosFilterTest.java new file mode 100644 index 000000000..d63d9efc1 --- /dev/null +++ b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DosFilterTest.java @@ -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 toAssign = new ArrayList<>(); + toAssign.add(target); + + final Iterable saved = deploymentManagement.assignDistributionSet(ds, toAssign).getAssignedEntity(); + assertThat(deploymentManagement.findActiveActionsByTarget(target)).hasSize(1); + + final Action uaction = deploymentManagement.findActiveActionsByTarget(target).get(0); + + return uaction.getId(); + } + +} diff --git a/hawkbit-dmf-amqp/pom.xml b/hawkbit-dmf-amqp/pom.xml index 127103b91..c2ed7c213 100644 --- a/hawkbit-dmf-amqp/pom.xml +++ b/hawkbit-dmf-amqp/pom.xml @@ -23,10 +23,10 @@ org.eclipse.hawkbit - hawkbit-repository + hawkbit-repository-api ${project.version} - + org.eclipse.hawkbit hawkbit-core ${project.version} @@ -41,6 +41,10 @@ hawkbit-dmf-api ${project.version} + + org.springframework.boot + spring-boot-autoconfigure + org.springframework.amqp spring-rabbit @@ -73,6 +77,12 @@ + + org.eclipse.hawkbit + hawkbit-repository-test + ${project.version} + test + com.h2database h2 @@ -90,9 +100,9 @@ org.eclipse.hawkbit - hawkbit-repository + hawkbit-repository-jpa ${project.version} - tests + test ru.yandex.qatools.allure diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherService.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherService.java index dae5772e6..b643be322 100644 --- a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherService.java +++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherService.java @@ -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); diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerService.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerService.java index f26d7f3f7..107850fc1 100644 --- a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerService.java +++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerService.java @@ -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; + } + } diff --git a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/AmqpTestConfiguration.java b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/AmqpTestConfiguration.java index a1dd54710..c9be9ffa6 100644 --- a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/AmqpTestConfiguration.java +++ b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/AmqpTestConfiguration.java @@ -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. diff --git a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherServiceTest.java b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherServiceTest.java index 9164e655d..5faaa74f0 100644 --- a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherServiceTest.java +++ b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherServiceTest.java @@ -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 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()); } diff --git a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerServiceTest.java b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerServiceTest.java index 3051e4e22..a0515a871 100644 --- a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerServiceTest.java +++ b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerServiceTest.java @@ -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 actionList = new ArrayList<>(); actionList.add(action); @@ -409,7 +419,7 @@ public class AmqpMessageHandlerServiceTest { private List createSoftwareModuleList() { final List 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 { diff --git a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/util/PropertyBasedArtifactUrlHandlerTest.java b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/util/PropertyBasedArtifactUrlHandlerTest.java index f9a2ea316..c67d6cf47 100644 --- a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/util/PropertyBasedArtifactUrlHandlerTest.java +++ b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/util/PropertyBasedArtifactUrlHandlerTest.java @@ -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); } } diff --git a/hawkbit-dmf-amqp/src/test/resources/application-test.properties b/hawkbit-dmf-amqp/src/test/resources/application-test.properties new file mode 100644 index 000000000..79b1fe78f --- /dev/null +++ b/hawkbit-dmf-amqp/src/test/resources/application-test.properties @@ -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= diff --git a/hawkbit-dmf-amqp/src/test/resources/logback.xml b/hawkbit-dmf-amqp/src/test/resources/logback.xml new file mode 100644 index 000000000..30060d1c6 --- /dev/null +++ b/hawkbit-dmf-amqp/src/test/resources/logback.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/ActionStatus.java b/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/ActionStatus.java index c31ab83f3..2c38a771c 100644 --- a/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/ActionStatus.java +++ b/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/ActionStatus.java @@ -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; } diff --git a/hawkbit-http-security/pom.xml b/hawkbit-http-security/pom.xml index a9b8a4080..bb77df454 100644 --- a/hawkbit-http-security/pom.xml +++ b/hawkbit-http-security/pom.xml @@ -22,7 +22,7 @@ org.eclipse.hawkbit - hawkbit-repository + hawkbit-repository-api ${project.version} diff --git a/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremodule/MgmtSoftwareModule.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremodule/MgmtSoftwareModule.java index ec4a48e89..08b723198 100644 --- a/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremodule/MgmtSoftwareModule.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremodule/MgmtSoftwareModule.java @@ -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; diff --git a/hawkbit-mgmt-resource/pom.xml b/hawkbit-mgmt-resource/pom.xml index 160299651..007c6789b 100644 --- a/hawkbit-mgmt-resource/pom.xml +++ b/hawkbit-mgmt-resource/pom.xml @@ -23,9 +23,9 @@ org.eclipse.hawkbit - hawkbit-repository + hawkbit-repository-api ${project.version} - + org.eclipse.hawkbit hawkbit-mgmt-api @@ -47,6 +47,18 @@ + + org.eclipse.hawkbit + hawkbit-repository-test + ${project.version} + test + + + org.eclipse.hawkbit + hawkbit-repository-jpa + ${project.version} + test + org.eclipse.hawkbit hawkbit-rest-core @@ -90,13 +102,6 @@ spring-security-config test - - org.eclipse.hawkbit - hawkbit-repository - ${project.version} - tests - test - org.eclipse.hawkbit hawkbit-http-security diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetMapper.java index 6d2d890b2..4a0f8d90e 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetMapper.java @@ -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 dsFromRequest(final Iterable sets, - final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement) { + final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement, + final EntityFactory entityFactory) { final List 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 fromRequestDsMetadata(final DistributionSet ds, - final List metadata) { + final List metadata, final EntityFactory entityFactory) { final List 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; } diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResource.java index 17f4c3303..e99a33c5f 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResource.java @@ -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 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 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 createdDSets = this.distributionSetManagement.createDistributionSets( - MgmtDistributionSetMapper.dsFromRequest(sets, this.softwareManagement, this.distributionSetManagement)); + final Iterable 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 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 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 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. 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 created = this.distributionSetManagement - .createDistributionSetMetadata(MgmtDistributionSetMapper.fromRequestDsMetadata(ds, metadataRest)); + final List created = this.distributionSetManagement.createDistributionSetMetadata( + MgmtDistributionSetMapper.fromRequestDsMetadata(ds, metadataRest, entityFactory)); return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDsMetadata(created), HttpStatus.CREATED); } diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResource.java index 907bbb574..18ec162ca 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResource.java @@ -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> 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 findTargetPage = this.tagManagement - .findAllDistributionSetTags(RSQLUtility.parse(rsqlParam, TagFields.class), pageable); + final Page 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 createdTags = this.tagManagement - .createDistributionSetTags(MgmtTagMapper.mapDistributionSetTagFromRequest(tags)); + .createDistributionSetTags(MgmtTagMapper.mapDistributionSetTagFromRequest(entityFactory, tags)); return new ResponseEntity<>(MgmtTagMapper.toResponseDistributionSetTag(createdTags), HttpStatus.CREATED); } diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeMapper.java index d3046f149..5c139027c 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeMapper.java @@ -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 smFromRequest(final SoftwareManagement softwareManagement, + static List smFromRequest(final EntityFactory entityFactory, + final SoftwareManagement softwareManagement, final Iterable smTypesRest) { final List 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 -> { diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResource.java index baa6f2955..d69e4d8d4 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResource.java @@ -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> 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 findModuleTypessAll; Long countModulesAll; if (rsqlParam != null) { - findModuleTypessAll = distributionSetManagement.findDistributionSetTypesByPredicate( - RSQLUtility.parse(rsqlParam, DistributionSetTypeFields.class), pageable); + findModuleTypessAll = distributionSetManagement.findDistributionSetTypesAll(rsqlParam, pageable); countModulesAll = ((Page) findModuleTypessAll).getTotalElements(); } else { findModuleTypessAll = distributionSetManagement.findDistributionSetTypesAll(pageable); @@ -125,7 +126,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR @RequestBody final List distributionSetTypes) { final List createdSoftwareModules = distributionSetManagement.createDistributionSetTypes( - MgmtDistributionSetTypeMapper.smFromRequest(softwareManagement, distributionSetTypes)); + MgmtDistributionSetTypeMapper.smFromRequest(entityFactory, softwareManagement, distributionSetTypes)); return new ResponseEntity<>(MgmtDistributionSetTypeMapper.toTypesResponse(createdSoftwareModules), HttpStatus.CREATED); diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutMapper.java index 4dcaf0bf1..7467a45b0 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutMapper.java @@ -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); diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResource.java index 37d5c6fdc..7144316b8 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResource.java @@ -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> 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 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 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 rolloutGroupTargets; if (rsqlParam != null) { - final Specification rsqlSpecification = RSQLUtility.parse(rsqlParam, TargetFields.class); - rolloutGroupTargets = this.rolloutGroupManagement.findRolloutGroupTargets(rolloutGroup, rsqlSpecification, + rolloutGroupTargets = this.rolloutGroupManagement.findRolloutGroupTargets(rolloutGroup, rsqlParam, pageable); } else { final Page pageTargets = this.rolloutGroupManagement.findRolloutGroupTargets(rolloutGroup, diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleMapper.java index 5ca100ca9..adc19df0a 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleMapper.java @@ -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 fromRequestSwMetadata(final SoftwareModule sw, - final List metadata) { + static List fromRequestSwMetadata(final EntityFactory entityFactory, + final SoftwareModule sw, final List metadata) { final List 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 smFromRequest(final Iterable smsRest, - final SoftwareManagement softwareManagement) { + static List smFromRequest(final EntityFactory entityFactory, + final Iterable smsRest, final SoftwareManagement softwareManagement) { final List 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; } diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResource.java index 75abe57f4..b4f1e8adb 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResource.java @@ -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 uploadArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId, @RequestParam("file") final MultipartFile file, @@ -139,8 +139,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi { final Slice findModulesAll; Long countModulesAll; if (rsqlParam != null) { - findModulesAll = softwareManagement - .findSoftwareModulesByPredicate(RSQLUtility.parse(rsqlParam, SoftwareModuleFields.class), pageable); + findModulesAll = softwareManagement.findSoftwareModulesByPredicate(rsqlParam, pageable); countModulesAll = ((Page) findModulesAll).getTotalElements(); } else { findModulesAll = softwareManagement.findSoftwareModulesAll(pageable); @@ -163,8 +162,8 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi { public ResponseEntity> createSoftwareModules( @RequestBody final List softwareModules) { LOG.debug("creating {} softwareModules", softwareModules.size()); - final Iterable createdSoftwareModules = softwareManagement - .createSoftwareModule(MgmtSoftwareModuleMapper.smFromRequest(softwareModules, softwareManagement)); + final Iterable 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 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 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. ok(MgmtSoftwareModuleMapper.toResponseSwMetadata(findOne)); } @@ -242,8 +240,8 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi { public ResponseEntity 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 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 metadataRest) { final SoftwareModule sw = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null); - final List created = softwareManagement - .createSoftwareModuleMetadata(MgmtSoftwareModuleMapper.fromRequestSwMetadata(sw, metadataRest)); + final List created = softwareManagement.createSoftwareModuleMetadata( + MgmtSoftwareModuleMapper.fromRequestSwMetadata(entityFactory, sw, metadataRest)); return new ResponseEntity<>(MgmtSoftwareModuleMapper.toResponseSwMetadata(created), HttpStatus.CREATED); diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeMapper.java index 5b16436a9..565af7eb8 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeMapper.java @@ -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 smFromRequest(final Iterable smTypesRest) { + static List smFromRequest(final EntityFactory entityFactory, + final Iterable smTypesRest) { final List 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 toTypesResponse(final List types) { diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResource.java index deba883f6..353cf16e5 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResource.java @@ -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> 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 findModuleTypessAll; Long countModulesAll; if (rsqlParam != null) { - findModuleTypessAll = this.softwareManagement.findSoftwareModuleTypesByPredicate( - RSQLUtility.parse(rsqlParam, SoftwareModuleTypeFields.class), pageable); + findModuleTypessAll = this.softwareManagement.findSoftwareModuleTypesAll(rsqlParam, pageable); countModulesAll = ((Page) findModuleTypessAll).getTotalElements(); } else { findModuleTypessAll = this.softwareManagement.findSoftwareModuleTypesAll(pageable); @@ -112,8 +113,8 @@ public class MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRes public ResponseEntity> createSoftwareModuleTypes( @RequestBody final List softwareModuleTypes) { - final List createdSoftwareModules = this.softwareManagement - .createSoftwareModuleType(MgmtSoftwareModuleTypeMapper.smFromRequest(softwareModuleTypes)); + final List createdSoftwareModules = this.softwareManagement.createSoftwareModuleType( + MgmtSoftwareModuleTypeMapper.smFromRequest(entityFactory, softwareModuleTypes)); return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toTypesResponse(createdSoftwareModules), HttpStatus.CREATED); diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSystemManagementResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSystemManagementResource.java index 46e51f2ee..3392d2659 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSystemManagementResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSystemManagementResource.java @@ -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; diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSystemResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSystemResource.java index 24a3f275e..fb9218d31 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSystemResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSystemResource.java @@ -123,3 +123,4 @@ public class MgmtSystemResource implements MgmtSystemRestApi { } } + diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTagMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTagMapper.java index 3ab2016ec..bac21c2a5 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTagMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTagMapper.java @@ -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 mapTargeTagFromRequest(final Iterable tags) { + static List mapTargeTagFromRequest(final EntityFactory entityFactory, + final Iterable tags) { final List 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 mapDistributionSetTagFromRequest(final Iterable tags) { + static List mapDistributionSetTagFromRequest(final EntityFactory entityFactory, + final Iterable tags) { final List 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; } diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetMapper.java index afb941bc1..f00998d29 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetMapper.java @@ -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 fromRequest(final Iterable targetsRest) { + static List fromRequest(final EntityFactory entityFactory, + final Iterable targetsRest) { final List 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; diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResource.java index 4a7c760e3..cc7bbcde6 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResource.java @@ -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 getTarget(@PathVariable("targetId") final String targetId) { final Target findTarget = findTargetWithExceptionIfNotFound(targetId); @@ -93,8 +93,7 @@ public class MgmtTargetResource implements MgmtTargetRestApi { final Slice findTargetsAll; final Long countTargetsAll; if (rsqlParam != null) { - final Page findTargetPage = this.targetManagement - .findTargetsAll(RSQLUtility.parse(rsqlParam, TargetFields.class), pageable); + final Page findTargetPage = this.targetManagement.findTargetsAll(rsqlParam, pageable); countTargetsAll = findTargetPage.getTotalElements(); findTargetsAll = findTargetPage; } else { @@ -110,7 +109,7 @@ public class MgmtTargetResource implements MgmtTargetRestApi { public ResponseEntity> createTargets(@RequestBody final List targets) { LOG.debug("creating {} targets", targets.size()); final Iterable 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 activeActions; final Long totalActionCount; if (rsqlParam != null) { - final Specification 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 statusList = this.deploymentManagement.findActionStatusByAction( - new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting), action, true); + final Page statusList = this.deploymentManagement.findActionStatusByActionWithMessages( + new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting), action); return new ResponseEntity<>( new PagedList<>(MgmtTargetMapper.toActionStatusRestResponse(statusList.getContent()), diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResource.java index 2bafecd8b..c765c18cd 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResource.java @@ -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> 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 findTargetPage = this.tagManagement - .findAllTargetTags(RSQLUtility.parse(rsqlParam, TagFields.class), pageable); + final Page findTargetPage = this.tagManagement.findAllTargetTags(rsqlParam, pageable); countTargetsAll = findTargetPage.getTotalElements(); findTargetsAll = findTargetPage; @@ -96,7 +97,7 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi { public ResponseEntity> createTargetTags(@RequestBody final List tags) { LOG.debug("creating {} target tags", tags.size()); final List createdTargetTags = this.tagManagement - .createTargetTags(MgmtTagMapper.mapTargeTagFromRequest(tags)); + .createTargetTags(MgmtTagMapper.mapTargeTagFromRequest(entityFactory, tags)); return new ResponseEntity<>(MgmtTagMapper.toResponse(createdTargetTags), HttpStatus.CREATED); } diff --git a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResourceTest.java index 8cfef095e..ad72aa55d 100644 --- a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResourceTest.java +++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResourceTest.java @@ -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 smIDs = new ArrayList(); - SoftwareModule sm = new SoftwareModule(osType, "Dysnomia ", "15,772", null, null); + final DistributionSet disSet = testdataFactory.createDistributionSetWithNoSoftwareModules("Eris", "560a"); + final List 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 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 smID2s = new ArrayList(); - SoftwareModule sm2 = new SoftwareModule(appType, "Deimos", "1,262", null, null); + final List 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 smIDs = new ArrayList(); - SoftwareModule sm = new SoftwareModule(osType, "Europa", "3,551", null, null); + final List 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 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 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 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 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 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; diff --git a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java index dcd78513b..ad6be0854 100644 --- a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java +++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java @@ -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 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 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++; diff --git a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadResourceTest.java index 17f23f888..16cc82e75 100644 --- a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadResourceTest.java +++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadResourceTest.java @@ -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())); } diff --git a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java index 09281721c..ff49542ce 100644 --- a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java +++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java @@ -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 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); diff --git a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java index a63dd754f..e7397dd49 100644 --- a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java +++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java @@ -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 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 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++; diff --git a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java index b69558e59..363b12cde 100644 --- a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java +++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java @@ -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 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 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++; diff --git a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResourceTest.java index c8d33edc9..6e50d1103 100644 --- a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResourceTest.java +++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResourceTest.java @@ -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 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 targets = new ArrayList<>(); targets.add(target); - final Iterator sets = TestDataUtil - .generateDistributionSets(2, softwareManagement, distributionSetManagement).iterator(); + final Iterator 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 actions = actionRepository.findAll(pageRequest).getContent(); + // two updates, one cancellation + final List 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 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 diff --git a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/SMRessourceMisingMongoDbConnectionTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/SMRessourceMisingMongoDbConnectionTest.java index 15d22c703..de0411006 100644 --- a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/SMRessourceMisingMongoDbConnectionTest.java +++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/SMRessourceMisingMongoDbConnectionTest.java @@ -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); } diff --git a/hawkbit-mgmt-resource/src/test/resources/application-test.properties b/hawkbit-mgmt-resource/src/test/resources/application-test.properties index 92506caa4..cd98bb23f 100644 --- a/hawkbit-mgmt-resource/src/test/resources/application-test.properties +++ b/hawkbit-mgmt-resource/src/test/resources/application-test.properties @@ -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 diff --git a/hawkbit-mgmt-resource/src/test/resources/log4j2.xml b/hawkbit-mgmt-resource/src/test/resources/log4j2.xml deleted file mode 100644 index 98ea99ac9..000000000 --- a/hawkbit-mgmt-resource/src/test/resources/log4j2.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/hawkbit-mgmt-resource/src/test/resources/logback.xml b/hawkbit-mgmt-resource/src/test/resources/logback.xml new file mode 100644 index 000000000..30060d1c6 --- /dev/null +++ b/hawkbit-mgmt-resource/src/test/resources/logback.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/hawkbit-repository/.gitignore b/hawkbit-repository/.gitignore new file mode 100644 index 000000000..6a3b2b405 --- /dev/null +++ b/hawkbit-repository/.gitignore @@ -0,0 +1 @@ +/.springBeans diff --git a/hawkbit-repository/hawkbit-repository-api/pom.xml b/hawkbit-repository/hawkbit-repository-api/pom.xml new file mode 100644 index 000000000..050a9a070 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + + org.eclipse.hawkbit + hawkbit-repository + 0.2.0-SNAPSHOT + + hawkbit-repository-api + hawkBit :: Repository API + + + + org.eclipse.hawkbit + hawkbit-security-core + ${project.version} + + + javax.validation + validation-api + + + org.hibernate + hibernate-validator + + + cz.jirutka.rsql + rsql-parser + + + org.springframework.hateoas + spring-hateoas + + + org.springframework.boot + spring-boot-configuration-processor + true + + + \ No newline at end of file diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/ArtifactManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/ArtifactManagement.java new file mode 100644 index 000000000..167b6019f --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/ArtifactManagement.java @@ -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 true 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 true 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 true 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 null 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 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 findLocalArtifactByFilename(@NotNull String filename); + + /** + * Get local artifact for a base software module. + * + * @param pageReq + * Pageable + * @param swId + * software module id + * @return Page + */ + @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) + Page 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 null 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); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/Constants.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/Constants.java new file mode 100644 index 000000000..9a1e442b0 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/Constants.java @@ -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. + } +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java new file mode 100644 index 000000000..531da8819 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java @@ -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 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 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 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); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/DeploymentManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/DeploymentManagement.java new file mode 100644 index 000000000..9dc5f74c8 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/DeploymentManagement.java @@ -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 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 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 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 null 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 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 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 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 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 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 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 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 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 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 true if {@link ActionStatus#getMessages()} + * need to be fetched. + * @return the corresponding {@link Page} of {@link ActionStatus} + */ + @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) + Page 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 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 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 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 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 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 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 null 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 findActionStatusAll(@NotNull Pageable pageable); +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetAssignmentResult.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/DistributionSetAssignmentResult.java similarity index 99% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetAssignmentResult.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/DistributionSetAssignmentResult.java index 85e707652..f21763883 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetAssignmentResult.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/DistributionSetAssignmentResult.java @@ -51,11 +51,6 @@ public class DistributionSetAssignmentResult extends AssignmentResult { this.actions = actions; this.targetManagement = targetManagement; } - - @Override - public List getAssignedEntity() { - return targetManagement.findTargetByControllerID(assignedTargets); - } /** * @return the actionIds @@ -64,4 +59,9 @@ public class DistributionSetAssignmentResult extends AssignmentResult { return actions; } + @Override + public List getAssignedEntity() { + return targetManagement.findTargetByControllerID(assignedTargets); + } + } diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java new file mode 100644 index 000000000..a2e7e5213 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java @@ -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 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 assignTag(@NotEmpty Collection 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 createDistributionSetMetadata(@NotEmpty Collection 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 createDistributionSets(@NotNull Collection 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 createDistributionSetTypes(@NotNull Collection types); + + /** + *

+ * {@link DistributionSet} can be deleted/erased from the repository if they + * have never been assigned to any {@link UpdateAction} or {@link Target}. + *

+ * + *

+ * 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()) + *

+ * + * @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 null 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 null 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 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 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 findDistributionSetsAll(Collection 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. + * null if both are to be returned + * @param complete + * to true for returning only completed distribution + * sets or false for only incomplete ones nor + * null to return both. + * @param complete + * set to if false incomplete DS should also be + * shown. + * + * + * @return all found {@link DistributionSet}s + */ + @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) + Page 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. + * null 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 findDistributionSetsAll(@NotNull String rsqlParam, @NotNull Pageable pageReq, + Boolean deleted); + + /** + * method retrieves all {@link DistributionSet}s from the repository in the + * following order: + *

+ * 1) {@link DistributionSet}s which have the given {@link Target} as + * {@link TargetStatus#getInstalledDistributionSet()} + *

+ * 2) {@link DistributionSet}s which have the given {@link Target} as + * {@link Target#getAssignedDistributionSet()} + *

+ * 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 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 findDistributionSetsByFilters(@NotNull Pageable pageable, + @NotNull DistributionSetFilter distributionSetFilter); + + /** + * @param id + * as {@link DistributionSetType#getId()} + * @return {@link DistributionSetType} if found or null 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 null 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 null 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 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 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 true 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 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 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 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 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 null + * @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); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/EntityFactory.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/EntityFactory.java new file mode 100644 index 000000000..7542cd2ce --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/EntityFactory.java @@ -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 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 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(); + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/OffsetBasedPageRequest.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/OffsetBasedPageRequest.java similarity index 70% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/OffsetBasedPageRequest.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/OffsetBasedPageRequest.java index 753ec6963..bf7807db0 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/OffsetBasedPageRequest.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/OffsetBasedPageRequest.java @@ -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; + } + } diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/ReportManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/ReportManagement.java new file mode 100644 index 000000000..a27154868 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/ReportManagement.java @@ -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 + */ + public interface DateType { + /** + * @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, 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> 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> distributionUsageInstalled(int topXEntries); + + /** + * Generates report for feedback over period. + * + * @param dateType + * {@link PerMonth} + * @param from + * start date + * @param to + * end date + * @return DataReportSeries ListReportSeries list of action status + * count + */ + @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) + DataReportSeries feedbackReceivedOverTime(@NotNull DateType 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 DataReportSeries ListReportSeries list of target created + * count + */ + @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) + DataReportSeries targetsCreatedOverPeriod(@NotNull DateType 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 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 targetStatus(); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RepositoryConstants.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RepositoryConstants.java new file mode 100644 index 000000000..f2cd3f9f6 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RepositoryConstants.java @@ -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. + } + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RolloutGroupManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RolloutGroupManagement.java new file mode 100644 index 000000000..512b9af3c --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RolloutGroupManagement.java @@ -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 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 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 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 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 list of targets of a rollout group + */ + @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ_AND_TARGET_READ) + Page 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 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 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); +} \ No newline at end of file diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RolloutManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RolloutManagement.java new file mode 100644 index 000000000..2c6e85dda --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RolloutManagement.java @@ -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. + * + *

+     * {@code
+     *  SystemSecurityContext.runAsSystem(new Callable() {
+     *     public Void call() throws Exception {
+     *        //run system-code
+     *     }
+     * });
+     *  }
+     * 
+ * + * 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 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 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 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 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); + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutProperties.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RolloutProperties.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutProperties.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RolloutProperties.java index 2384fa480..9b3a37093 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutProperties.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RolloutProperties.java @@ -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; + } + } diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/SoftwareManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/SoftwareManagement.java new file mode 100644 index 000000000..0934e871e --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/SoftwareManagement.java @@ -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 createSoftwareModule(@NotNull Collection 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 createSoftwareModuleMetadata(@NotNull Collection 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 createSoftwareModuleType(@NotNull final Collection 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 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 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 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 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 null 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 null + */ + @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 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 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 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 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 findSoftwareModulesById(@NotEmpty Collection 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 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 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 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 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 null + */ + @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); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/SystemManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/SystemManagement.java new file mode 100644 index 000000000..039e4ae13 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/SystemManagement.java @@ -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 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); + +} \ No newline at end of file diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TagManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TagManagement.java new file mode 100644 index 000000000..1b80444b5 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TagManagement.java @@ -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 createDistributionSetTags(@NotNull Collection 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 createTargetTags(@NotNull Collection 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 findAllDistributionSetTags(); + + /** + * returns all {@link DistributionSetTag}s. + * + * @param pageReq + * page parameter + * @return all {@link DistributionSetTag}s + */ + @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) + Page 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 findAllDistributionSetTags(@NotNull String rsqlParam, @NotNull Pageable pageable); + + /** + * @return all {@link TargetTag}s + */ + @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) + List findAllTargetTags(); + + /** + * returns all {@link TargetTag}s. + * + * @param pageable + * page parameter + * + * @return all {@link TargetTag}s + */ + @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) + Page 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 findAllTargetTags(@NotNull String rsqlParam, @NotNull Pageable pageable); + + /** + * Find {@link DistributionSet} based on given name. + * + * @param name + * to look for. + * @return {@link DistributionSet} or null 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 null 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 null 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 null 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 null + */ + @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); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagement.java new file mode 100644 index 000000000..d748ed470 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagement.java @@ -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 true 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 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 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); +} \ No newline at end of file diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TargetManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TargetManagement.java new file mode 100644 index 000000000..9054127ef --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TargetManagement.java @@ -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 assignTag(@NotEmpty Collection 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 null in case this is not required. + * @param searchText + * to find targets having the text anywhere in name or + * description. Set null in case this is not + * required. + * @param installedOrAssignedDistributionSetId + * to find targets having the {@link DistributionSet} as + * installed or assigned. Set to null in case this + * is not required. + * @param tagNames + * to find targets which are having any one in this tag names. + * Set null 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 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 createTargets(@NotNull Collection 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 createTargets(@NotNull Collection 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 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 + * null in case this is not required. + * @param filterBySearchText + * to find targets having the text anywhere in name or + * description. Set null in case this is not + * required. + * @param installedOrAssignedDistributionSetId + * to find targets having the {@link DistributionSet} as + * installed or assigned. Set to null in case this + * is not required. + * @param filterByTagNames + * to find targets which are having any one in this tag names. + * Set null 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 findAllTargetIdsByFilters(@NotNull Pageable pageRequest, + Collection 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 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 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 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 findTargetByControllerID(@NotEmpty Collection 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 null 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 null 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 + * null in case this is not required. + * @param searchText + * to find targets having the text anywhere in name or + * description. Set null in case this is not + * required. + * @param installedOrAssignedDistributionSetId + * to find targets having the {@link DistributionSet} as + * installed or assigned. Set to null in case this + * is not required. + * @param tagNames + * to find targets which are having any one in this tag names. + * Set null 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 findTargetByFilters(@NotNull Pageable pageable, Collection 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 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 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 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 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 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 findTargetsAll(@NotNull TargetFilterQuery targetFilterQuery, @NotNull Pageable pageable); + + /** + * method retrieves all {@link Target}s from the repo in the following + * order: + *

+ * 1) {@link Target}s which have the given {@link DistributionSet} as + * {@link Target#getTargetInfo()} + * {@link TargetInfo#getInstalledDistributionSet()} + *

+ * 2) {@link Target}s which have the given {@link DistributionSet} as + * {@link Target#getAssignedDistributionSet()} + *

+ * 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 null in case this is not required. + * @param filterByStatus + * find targets having this {@link TargetUpdateStatus}s. Set to + * null in case this is not required. + * @param filterBySearchText + * to find targets having the text anywhere in name or + * description. Set null in case this is not + * required. + * @param installedOrAssignedDistributionSetId + * to find targets having the {@link DistributionSet} as + * installed or assigned. Set to null in case this + * is not required. + * @param filterByTagNames + * to find targets which are having any one in this tag names. + * Set null 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 findTargetsAllOrderByLinkedDistributionSet(@NotNull Pageable pageable, + @NotNull Long orderByDistributionId, Long filterByDistributionId, + Collection 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 findTargetsByControllerIDsWithTags(@NotNull List controllerIDs); + + /** + * Find targets by tag name. + * + * @param tagName + * tag name + * @return list of matching targets + */ + @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) + List 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 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 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 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 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 updateTargets(@NotNull Collection targets); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TenantConfigurationManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TenantConfigurationManagement.java new file mode 100644 index 000000000..734704f05 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TenantConfigurationManagement.java @@ -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) + TenantConfigurationValue 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 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) + TenantConfigurationValue buildTenantConfigurationValueByKey(TenantConfigurationKey configurationKey, + Class 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) + TenantConfigurationValue 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 + * 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) + TenantConfigurationValue getConfigurationValue(TenantConfigurationKey configurationKey, + Class propertyType); + + /** + * returns the global configuration property either defined in the property + * file or an default value otherwise. + * + * @param + * 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 getGlobalConfigurationValue(TenantConfigurationKey configurationKey, Class propertyType); +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TenantStatsManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TenantStatsManagement.java new file mode 100644 index 000000000..6d390c03c --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TenantStatsManagement.java @@ -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); + +} \ No newline at end of file diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/AbstractBaseEntityEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/AbstractBaseEntityEvent.java similarity index 88% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/AbstractBaseEntityEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/AbstractBaseEntityEvent.java index d27669ade..d13e89ee7 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/AbstractBaseEntityEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/AbstractBaseEntityEvent.java @@ -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; /** diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/AbstractEntityBulkEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/AbstractEntityBulkEvent.java similarity index 96% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/AbstractEntityBulkEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/AbstractEntityBulkEvent.java index 56f3e585a..f8d43d6cd 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/AbstractEntityBulkEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/AbstractEntityBulkEvent.java @@ -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; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/AbstractPropertyChangeEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/AbstractPropertyChangeEvent.java similarity index 97% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/AbstractPropertyChangeEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/AbstractPropertyChangeEvent.java index 795f6ff88..97cf13b66 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/AbstractPropertyChangeEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/AbstractPropertyChangeEvent.java @@ -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; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/ActionCreatedEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/ActionCreatedEvent.java similarity index 93% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/ActionCreatedEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/ActionCreatedEvent.java index 5efdca2a9..73188b85e 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/ActionCreatedEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/ActionCreatedEvent.java @@ -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; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/ActionPropertyChangeEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/ActionPropertyChangeEvent.java similarity index 94% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/ActionPropertyChangeEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/ActionPropertyChangeEvent.java index 822f9bbeb..84487547e 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/ActionPropertyChangeEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/ActionPropertyChangeEvent.java @@ -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; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/DistributionSetTagAssigmentResultEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/DistributionSetTagAssigmentResultEvent.java similarity index 94% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/DistributionSetTagAssigmentResultEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/DistributionSetTagAssigmentResultEvent.java index e10b9a51f..d723251da 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/DistributionSetTagAssigmentResultEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/DistributionSetTagAssigmentResultEvent.java @@ -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; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/DistributionSetTagCreatedBulkEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/DistributionSetTagCreatedBulkEvent.java similarity index 95% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/DistributionSetTagCreatedBulkEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/DistributionSetTagCreatedBulkEvent.java index fb7c4a862..2fc08c272 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/DistributionSetTagCreatedBulkEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/DistributionSetTagCreatedBulkEvent.java @@ -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; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/DistributionSetTagDeletedEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/DistributionSetTagDeletedEvent.java similarity index 93% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/DistributionSetTagDeletedEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/DistributionSetTagDeletedEvent.java index b909390d1..f2f134a3a 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/DistributionSetTagDeletedEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/DistributionSetTagDeletedEvent.java @@ -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; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/DistributionSetTagUpdateEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/DistributionSetTagUpdateEvent.java similarity index 93% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/DistributionSetTagUpdateEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/DistributionSetTagUpdateEvent.java index 2825322f9..d74872b01 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/DistributionSetTagUpdateEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/DistributionSetTagUpdateEvent.java @@ -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; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/EntityBulkEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/EntityBulkEvent.java similarity index 91% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/EntityBulkEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/EntityBulkEvent.java index eac1b6bb9..0102fda47 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/EntityBulkEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/EntityBulkEvent.java @@ -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; /** diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/RolloutChangeEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/RolloutChangeEvent.java similarity index 95% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/RolloutChangeEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/RolloutChangeEvent.java index 8f15602b5..2ff739726 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/RolloutChangeEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/RolloutChangeEvent.java @@ -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; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/RolloutGroupChangeEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/RolloutGroupChangeEvent.java similarity index 92% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/RolloutGroupChangeEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/RolloutGroupChangeEvent.java index cbda44ef5..5c36ab61f 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/RolloutGroupChangeEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/RolloutGroupChangeEvent.java @@ -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 diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/RolloutGroupCreatedEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/RolloutGroupCreatedEvent.java similarity index 94% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/RolloutGroupCreatedEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/RolloutGroupCreatedEvent.java index 465ff6088..41f08c91d 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/RolloutGroupCreatedEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/RolloutGroupCreatedEvent.java @@ -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 diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/RolloutGroupPropertyChangeEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/RolloutGroupPropertyChangeEvent.java similarity index 94% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/RolloutGroupPropertyChangeEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/RolloutGroupPropertyChangeEvent.java index 6caa46547..887a1c2ff 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/RolloutGroupPropertyChangeEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/RolloutGroupPropertyChangeEvent.java @@ -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; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/RolloutPropertyChangeEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/RolloutPropertyChangeEvent.java similarity index 94% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/RolloutPropertyChangeEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/RolloutPropertyChangeEvent.java index 5f72307df..9287a0fb3 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/RolloutPropertyChangeEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/RolloutPropertyChangeEvent.java @@ -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; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetAssignDistributionSetEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/TargetAssignDistributionSetEvent.java similarity index 95% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetAssignDistributionSetEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/TargetAssignDistributionSetEvent.java index 68b3f1289..077e05462 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetAssignDistributionSetEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/TargetAssignDistributionSetEvent.java @@ -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.net.URI; import java.util.Collection; +import org.eclipse.hawkbit.eventbus.event.AbstractEvent; import org.eclipse.hawkbit.repository.model.SoftwareModule; /** diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetCreatedEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/TargetCreatedEvent.java similarity index 93% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetCreatedEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/TargetCreatedEvent.java index 7e89565b1..446f21856 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetCreatedEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/TargetCreatedEvent.java @@ -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.Target; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetInfoUpdateEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/TargetInfoUpdateEvent.java similarity index 93% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetInfoUpdateEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/TargetInfoUpdateEvent.java index 563bb4bdc..1e7e29719 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetInfoUpdateEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/TargetInfoUpdateEvent.java @@ -6,8 +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.EntityEvent; import org.eclipse.hawkbit.repository.model.TargetInfo; /** diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetTagAssigmentResultEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/TargetTagAssigmentResultEvent.java similarity index 94% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetTagAssigmentResultEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/TargetTagAssigmentResultEvent.java index 6bdc3aebd..b846a80da 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetTagAssigmentResultEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/TargetTagAssigmentResultEvent.java @@ -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.TargetTagAssignmentResult; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetTagCreatedBulkEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/TargetTagCreatedBulkEvent.java similarity index 95% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetTagCreatedBulkEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/TargetTagCreatedBulkEvent.java index c66a5150e..950c351e0 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetTagCreatedBulkEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/TargetTagCreatedBulkEvent.java @@ -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; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetTagDeletedEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/TargetTagDeletedEvent.java similarity index 93% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetTagDeletedEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/TargetTagDeletedEvent.java index 040fbc19a..ebf6c73c9 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetTagDeletedEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/TargetTagDeletedEvent.java @@ -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.TargetTag; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetTagUpdateEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/TargetTagUpdateEvent.java similarity index 93% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetTagUpdateEvent.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/TargetTagUpdateEvent.java index 4562063aa..f87443235 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetTagUpdateEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/eventbus/event/TargetTagUpdateEvent.java @@ -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.TargetTag; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/ArtifactDeleteFailedException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ArtifactDeleteFailedException.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/ArtifactDeleteFailedException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ArtifactDeleteFailedException.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/ArtifactUploadFailedException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ArtifactUploadFailedException.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/ArtifactUploadFailedException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ArtifactUploadFailedException.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/CancelActionNotAllowedException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/CancelActionNotAllowedException.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/CancelActionNotAllowedException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/CancelActionNotAllowedException.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/ConcurrentModificationException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ConcurrentModificationException.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/ConcurrentModificationException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ConcurrentModificationException.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/DistributionSetCreationFailedMissingMandatoryModuleException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/DistributionSetCreationFailedMissingMandatoryModuleException.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/DistributionSetCreationFailedMissingMandatoryModuleException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/DistributionSetCreationFailedMissingMandatoryModuleException.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/DistributionSetTypeUndefinedException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/DistributionSetTypeUndefinedException.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/DistributionSetTypeUndefinedException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/DistributionSetTypeUndefinedException.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/EntityAlreadyExistsException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/EntityAlreadyExistsException.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/EntityAlreadyExistsException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/EntityAlreadyExistsException.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/EntityLockedException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/EntityLockedException.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/EntityLockedException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/EntityLockedException.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/EntityNotFoundException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/EntityNotFoundException.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/EntityNotFoundException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/EntityNotFoundException.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/EntityReadOnlyException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/EntityReadOnlyException.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/EntityReadOnlyException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/EntityReadOnlyException.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/ForceQuitActionNotAllowedException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ForceQuitActionNotAllowedException.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/ForceQuitActionNotAllowedException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ForceQuitActionNotAllowedException.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/GridFSDBFileNotFoundException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/GridFSDBFileNotFoundException.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/GridFSDBFileNotFoundException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/GridFSDBFileNotFoundException.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/IncompleteDistributionSetException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/IncompleteDistributionSetException.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/IncompleteDistributionSetException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/IncompleteDistributionSetException.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/InsufficientPermissionException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/InsufficientPermissionException.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/InsufficientPermissionException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/InsufficientPermissionException.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/InvalidMD5HashException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/InvalidMD5HashException.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/InvalidMD5HashException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/InvalidMD5HashException.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/InvalidSHA1HashException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/InvalidSHA1HashException.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/InvalidSHA1HashException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/InvalidSHA1HashException.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/rsql/RSQLParameterSyntaxException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/RSQLParameterSyntaxException.java similarity index 97% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/rsql/RSQLParameterSyntaxException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/RSQLParameterSyntaxException.java index aa43f1bbb..268ab02ba 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/rsql/RSQLParameterSyntaxException.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/RSQLParameterSyntaxException.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.rsql; +package org.eclipse.hawkbit.repository.exception; import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.SpServerRtException; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/rsql/RSQLParameterUnsupportedFieldException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/RSQLParameterUnsupportedFieldException.java similarity index 97% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/rsql/RSQLParameterUnsupportedFieldException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/RSQLParameterUnsupportedFieldException.java index e95368acb..df58ecc8b 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/rsql/RSQLParameterUnsupportedFieldException.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/RSQLParameterUnsupportedFieldException.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.rsql; +package org.eclipse.hawkbit.repository.exception; import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.SpServerRtException; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/RolloutIllegalStateException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/RolloutIllegalStateException.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/RolloutIllegalStateException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/RolloutIllegalStateException.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/TenantNotExistException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/TenantNotExistException.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/TenantNotExistException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/TenantNotExistException.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/ToManyAttributeEntriesException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ToManyAttributeEntriesException.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/ToManyAttributeEntriesException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ToManyAttributeEntriesException.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/ToManyStatusEntriesException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ToManyStatusEntriesException.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/ToManyStatusEntriesException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ToManyStatusEntriesException.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/UnsupportedSoftwareModuleForThisDistributionSetException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/UnsupportedSoftwareModuleForThisDistributionSetException.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/exception/UnsupportedSoftwareModuleForThisDistributionSetException.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/UnsupportedSoftwareModuleForThisDistributionSetException.java diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Action.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Action.java new file mode 100644 index 000000000..c2b96905e --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Action.java @@ -0,0 +1,224 @@ +/** + * 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.model; + +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * Operations to be executed by the target. Usually a software update. Other + * supported actions are the cancellation of a running update action or a + * refresh request for target attributes. + * + */ +public interface Action extends TenantAwareBaseEntity { + + /** + * @return the distributionSet + */ + DistributionSet getDistributionSet(); + + /** + * @param distributionSet + * the distributionSet to set + */ + void setDistributionSet(DistributionSet distributionSet); + + /** + * @return true when action is in state + * {@link Status#CANCELING} or {@link Status#CANCELED}, false + * otherwise + */ + default boolean isCancelingOrCanceled() { + return Status.CANCELING.equals(getStatus()) || Status.CANCELED.equals(getStatus()); + } + + /** + * @return current {@link Status#DOWNLOAD} progress if known by the update + * server. + */ + int getDownloadProgressPercent(); + + /** + * @return current {@link Status} of the {@link Action}. + */ + Status getStatus(); + + /** + * @param status + * of the {@link Action} + */ + void setStatus(Status status); + + /** + * @return true if {@link Action} is still running. + */ + boolean isActive(); + + /** + * @return the {@link ActionType} + */ + ActionType getActionType(); + + /** + * @return list of {@link ActionStatus} entries. + */ + List getActionStatus(); + + /** + * @param target + * of this {@link Action} + */ + void setTarget(Target target); + + /** + * @return {@link Target} of this {@link Action}. + */ + Target getTarget(); + + /** + * @return time in {@link TimeUnit#MILLISECONDS} after which + * {@link #isForced()} switches to true in case of + * {@link ActionType#TIMEFORCED}. + */ + long getForcedTime(); + + /** + * @return rolloutGroup related to this {@link Action}. + */ + RolloutGroup getRolloutGroup(); + + /** + * @return rollout related to this {@link Action}. + */ + Rollout getRollout(); + + /** + * checks if the {@link #getForcedTime()} is hit by the given + * {@code hitTimeMillis}, by means if the given milliseconds are greater + * than the forcedTime. + * + * @param hitTimeMillis + * the milliseconds, mostly the + * {@link System#currentTimeMillis()} + * @return {@code true} if this {@link #getActionType()} is in + * {@link ActionType#TIMEFORCED} and the given {@code hitTimeMillis} + * is greater than the {@link #getForcedTime()} otherwise + * {@code false} + */ + default boolean isHitAutoForceTime(final long hitTimeMillis) { + if (ActionType.TIMEFORCED.equals(getActionType())) { + return hitTimeMillis >= getForcedTime(); + } + return false; + } + + /** + * @return {@code true} if either the {@link #getActionType()} is + * {@link ActionType#FORCED} or {@link ActionType#TIMEFORCED} but + * then if the {@link #getForcedTime()} has been exceeded otherwise + * always {@code false} + */ + default boolean isForce() { + switch (getActionType()) { + case FORCED: + return true; + case TIMEFORCED: + return isHitAutoForceTime(System.currentTimeMillis()); + default: + return false; + } + } + + /** + * @return true when action is forced, false otherwise + */ + default boolean isForced() { + return ActionType.FORCED.equals(getActionType()); + } + + /** + * Action status as reported by the controller. + * + * Be aware that JPA is persisting the ordinal number of the enum by means + * the ordered number in the enum. So don't re-order the enums within the + * Status enum declaration! + * + */ + public enum Status { + /** + * Action is finished successfully for this target. + */ + FINISHED, + + /** + * Action has failed for this target. + */ + ERROR, + + /** + * Action is still running but with warnings. + */ + WARNING, + + /** + * Action is still running for this target. + */ + RUNNING, + + /** + * Action has been canceled for this target. + */ + CANCELED, + + /** + * Action is in canceling state and waiting for controller confirmation. + */ + CANCELING, + + /** + * Action has been send to the target. + */ + RETRIEVED, + + /** + * Action requests download by this target which has now started. + */ + DOWNLOAD, + + /** + * Action is in waiting state, e.g. the action is scheduled in a rollout + * but not yet activated. + */ + SCHEDULED; + } + + /** + * The action type for this action relation. + * + */ + public enum ActionType { + /** + * Forced action execution. Target is advised to executed immediately. + */ + FORCED, + + /** + * Soft action execution. Target is advised to execute when it fits. + */ + SOFT, + + /** + * {@link #SOFT} action execution until + * {@link Action#isHitAutoForceTime(long)} is reached, {@link #FORCED} + * after that. + */ + TIMEFORCED; + } +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/ActionStatus.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/ActionStatus.java new file mode 100644 index 000000000..f3ca66887 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/ActionStatus.java @@ -0,0 +1,78 @@ +/** + * 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.model; + +import java.util.List; +import java.util.concurrent.TimeUnit; + +import org.eclipse.hawkbit.repository.model.Action.Status; + +/** + * Status information of an {@link Action} which can be provided by the + * {@link Target} or is added by the update server itself. This can be the start + * of the {@link Action} life cycle, the end and update notifications in + * between. + * + */ +public interface ActionStatus extends TenantAwareBaseEntity { + + /** + * @return time in {@link TimeUnit#MILLISECONDS} when the status was + * reported. + */ + Long getOccurredAt(); + + /** + * @param occurredAt + * time in {@link TimeUnit#MILLISECONDS} when the status was + * reported. + */ + void setOccurredAt(Long occurredAt); + + /** + * Adds message including splitting in case it exceeds 512 length. + * + * @param message + * to add + */ + void addMessage(String message); + + /** + * @return list of message entries that can be added to the + * {@link ActionStatus}. + */ + List getMessages(); + + /** + * @return {@link Action} this {@link ActionStatus} belongs to. + */ + Action getAction(); + + /** + * @param action + * this {@link ActionStatus} belongs to. + */ + void setAction(Action action); + + /** + * @return the {@link Status} of this {@link ActionStatus}. Caused + * potentially a transition change of the {@link #getAction()} if + * different from the previous {@link ActionStatus#getStatus()}. + */ + Status getStatus(); + + /** + * @param status + * of this {@link ActionStatus}. May cause a transition change of + * the {@link #getAction()} if different from the previous + * {@link ActionStatus#getStatus()}. + */ + void setStatus(Status status); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/ActionWithStatusCount.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/ActionWithStatusCount.java new file mode 100644 index 000000000..268c37853 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/ActionWithStatusCount.java @@ -0,0 +1,48 @@ +/** + * 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.model; + +/** + * View for querying {@link Action} include the count of the action's + * {@link ActionStatus} entries. + * + */ +public interface ActionWithStatusCount { + + /** + * @return {@link Action} + */ + Action getAction(); + + /** + * @return {@link DistributionSet} ID. + */ + Long getDsId(); + + /** + * @return {@link DistributionSet} name. + */ + String getDsName(); + + /** + * @return {@link DistributionSet} version. + */ + String getDsVersion(); + + /** + * @return number of {@link ActionStatus} entries + */ + Long getActionStatusCount(); + + /** + * @return name of the {@link Rollout}. + */ + String getRolloutName(); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Artifact.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Artifact.java new file mode 100644 index 000000000..cc726839d --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Artifact.java @@ -0,0 +1,42 @@ +/** + * 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.model; + +import com.google.common.io.BaseEncoding; + +/** + * Binaries for a {@link SoftwareModule} Note: the decision which artifacts have + * to be downloaded are done on the device side. e.g. Full Package, Signatures, + * binary deltas + * + */ +public interface Artifact extends TenantAwareBaseEntity { + + /** + * @return {@link SoftwareModule} this {@link Artifact} belongs to. + */ + SoftwareModule getSoftwareModule(); + + /** + * @return MD5 hash of the artifact. + */ + String getMd5Hash(); + + /** + * @return SHA-1 hash of the artifact in {@link BaseEncoding#base16()} + * format. + */ + String getSha1Hash(); + + /** + * @return size of the artifact in bytes. + */ + Long getSize(); + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/CustomSoftwareModule.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/AssignedSoftwareModule.java similarity index 79% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/CustomSoftwareModule.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/AssignedSoftwareModule.java index 34aa8345a..b23b3f0fe 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/CustomSoftwareModule.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/AssignedSoftwareModule.java @@ -14,7 +14,7 @@ import java.io.Serializable; * Use to display software modules for the selected distribution. * */ -public class CustomSoftwareModule implements Serializable { +public class AssignedSoftwareModule implements Serializable { private static final long serialVersionUID = 6144585781451168439L; @@ -31,22 +31,28 @@ public class CustomSoftwareModule implements Serializable { * as true if the software module is assigned and false if not * assigned. */ - public CustomSoftwareModule(final SoftwareModule softwareModule, final boolean assigned) { + public AssignedSoftwareModule(final SoftwareModule softwareModule, final boolean assigned) { this.softwareModule = softwareModule; this.assigned = assigned; } + /** + * @return {@link SoftwareModule} + */ public SoftwareModule getSoftwareModule() { return softwareModule; } + /** + * @return true if assigned + */ public boolean isAssigned() { return assigned; } @Override public String toString() { - return "CustomSoftwareModule [softwareModule=" + softwareModule + ", assigned=" + assigned + "]"; + return "AssignedSoftwareModule [softwareModule=" + softwareModule + ", assigned=" + assigned + "]"; } @Override @@ -66,10 +72,10 @@ public class CustomSoftwareModule implements Serializable { if (obj == null) { return false; } - if (!(obj instanceof CustomSoftwareModule)) { + if (!(obj instanceof AssignedSoftwareModule)) { return false; } - final CustomSoftwareModule other = (CustomSoftwareModule) obj; + final AssignedSoftwareModule other = (AssignedSoftwareModule) obj; if (assigned != other.assigned) { return false; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/AssignmentResult.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/AssignmentResult.java similarity index 80% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/AssignmentResult.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/AssignmentResult.java index 2dea94f33..9468c8a88 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/AssignmentResult.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/AssignmentResult.java @@ -12,6 +12,9 @@ import java.util.List; /** * Generic assignment result bean. + * + * @param + * type of the assigned and unassigned {@link BaseEntity}s. * */ public class AssignmentResult { @@ -19,7 +22,6 @@ public class AssignmentResult { private final int total; private final int assigned; private final int alreadyAssigned; - private final int unassigned; private final List assignedEntity; private final List unassignedEntity; @@ -47,28 +49,45 @@ public class AssignmentResult { this.assignedEntity = assignedEntity; this.unassignedEntity = unassignedEntity; } - + + /** + * @return number of newly assigned elements. + */ public int getAssigned() { return assigned; } - + + /** + * @return total number (assigned and already assigned). + */ public int getTotal() { return total; } - + + /** + * @return number of already assigned/ignored elements. + */ public int getAlreadyAssigned() { return alreadyAssigned; } - + /** + * @return number of unsassigned elements + */ public int getUnassigned() { return unassigned; } + /** + * @return {@link List} of assigned entity. + */ public List getAssignedEntity() { return assignedEntity; } - + + /** + * @return {@link List} of unassigned entity. + */ public List getUnassignedEntity() { return unassignedEntity; } diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/BaseEntity.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/BaseEntity.java new file mode 100644 index 000000000..2a9948bc5 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/BaseEntity.java @@ -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 + */ +package org.eclipse.hawkbit.repository.model; + +import java.io.Serializable; +import java.util.concurrent.TimeUnit; + +import org.springframework.hateoas.Identifiable; + +/** + * Core information of all entities. + * + */ +public interface BaseEntity extends Serializable, Identifiable { + + /** + * @return time in {@link TimeUnit#MILLISECONDS} when the {@link BaseEntity} + * was created. + */ + Long getCreatedAt(); + + /** + * @return user that created the {@link BaseEntity}. + */ + String getCreatedBy(); + + /** + * @return time in {@link TimeUnit#MILLISECONDS} when the {@link BaseEntity} + * was last time changed. + */ + Long getLastModifiedAt(); + + /** + * @return user that updated the {@link BaseEntity} last. + */ + String getLastModifiedBy(); + + /** + * @return version of the {@link BaseEntity}. + */ + long getOptLockRevision(); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSet.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSet.java new file mode 100644 index 000000000..5747b38f3 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSet.java @@ -0,0 +1,132 @@ +/** + * 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.model; + +import java.util.List; +import java.util.Set; + +import org.eclipse.hawkbit.repository.DistributionSetManagement; + +/** + * A {@link DistributionSet} defines a meta package that combines a set of + * {@link SoftwareModule}s which have to be or are provisioned to a + * {@link Target}. + * + *

+ * A {@link Target} has exactly one target {@link DistributionSet} assigned. + *

+ * + */ +public interface DistributionSet extends NamedVersionedEntity { + + /** + * @return {@link Set} of assigned {@link DistributionSetTag}s. + */ + Set getTags(); + + /** + * @return true if the set is deleted and only kept for history + * purposes. + */ + boolean isDeleted(); + + /** + * @return immutable {@link List} of {@link DistributionSetMetadata} + * elements. See {@link DistributionSetManagement} to alter. + */ + List getMetadata(); + + /** + * @return true if {@link DistributionSet} contains a mandatory + * migration step, i.e. unfinished {@link Action}s will kept active + * and not automatically canceled if overridden by a newer update. + */ + boolean isRequiredMigrationStep(); + + /** + * @param deleted + * to true if {@link DistributionSet} is no longer + * be usage but kept for history purposes. + * @return updated {@link DistributionSet} + */ + DistributionSet setDeleted(boolean deleted); + + /** + * @param isRequiredMigrationStep + * to true if {@link DistributionSet} contains a + * mandatory migration step, i.e. unfinished {@link Action}s will + * kept active and not automatically canceled if overridden by a + * newer update. + * + * @return updated {@link DistributionSet} + */ + DistributionSet setRequiredMigrationStep(boolean isRequiredMigrationStep); + + /** + * @return the assignedTargets + */ + List getAssignedTargets(); + + /** + * @return the installedTargets + */ + List getInstalledTargets(); + + /** + * + * @return unmodifiableSet of {@link SoftwareModule}. + */ + Set getModules(); + + /** + * @param softwareModule + * @return true if the module was added and false + * if it already existed in the set + * + */ + boolean addModule(SoftwareModule softwareModule); + + /** + * Removed given {@link SoftwareModule} from this DS instance. + * + * @param softwareModule + * to remove + * @return true if element was found and removed + */ + boolean removeModule(SoftwareModule softwareModule); + + /** + * Searches through modules for the given type. + * + * @param type + * to search for + * @return SoftwareModule of given type or null if not in the + * list. + */ + SoftwareModule findFirstModuleByType(SoftwareModuleType type); + + /** + * @return type of the {@link DistributionSet}. + */ + DistributionSetType getType(); + + /** + * @param type + * of the {@link DistributionSet}. + */ + void setType(DistributionSetType type); + + /** + * @return true if all defined + * {@link DistributionSetType#getMandatoryModuleTypes()} of + * {@link #getType()} are present in this {@link DistributionSet}. + */ + boolean isComplete(); + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetFilter.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetFilter.java similarity index 97% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetFilter.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetFilter.java index a545209e4..c095d0f7e 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetFilter.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetFilter.java @@ -6,45 +6,14 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.model; import java.util.Collection; -import org.eclipse.hawkbit.repository.model.DistributionSetType; - /** * Holds distribution set filter parameters. - * - * - * */ public final class DistributionSetFilter { - private final Boolean isDeleted; - private final Boolean isComplete; - private final DistributionSetType type; - private final String searchText; - private final Boolean selectDSWithNoTag; - private final Collection tagNames; - private final String assignedTargetId; - private final String installedTargetId; - - /** - * Parametric constructor. - * - * @param builder - * DistributionSetFilterBuilder - */ - public DistributionSetFilter(final DistributionSetFilterBuilder builder) { - this.isDeleted = builder.isDeleted; - this.isComplete = builder.isComplete; - this.type = builder.type; - this.searchText = builder.searchText; - this.selectDSWithNoTag = builder.selectDSWithNoTag; - this.tagNames = builder.tagNames; - this.assignedTargetId = builder.assignedTargetId; - this.installedTargetId = builder.installedTargetId; - } - /** * * Distribution set filter builder. @@ -71,8 +40,13 @@ public final class DistributionSetFilter { return new DistributionSetFilter(this); } - public DistributionSetFilterBuilder setIsDeleted(final Boolean isDeleted) { - this.isDeleted = isDeleted; + public DistributionSetFilterBuilder setAssignedTargetId(final String assignedTargetId) { + this.assignedTargetId = assignedTargetId; + return this; + } + + public DistributionSetFilterBuilder setInstalledTargetId(final String installedTargetId) { + this.installedTargetId = installedTargetId; return this; } @@ -81,8 +55,8 @@ public final class DistributionSetFilter { return this; } - public DistributionSetFilterBuilder setType(final DistributionSetType type) { - this.type = type; + public DistributionSetFilterBuilder setIsDeleted(final Boolean isDeleted) { + this.isDeleted = isDeleted; return this; } @@ -101,28 +75,53 @@ public final class DistributionSetFilter { return this; } - public DistributionSetFilterBuilder setAssignedTargetId(final String assignedTargetId) { - this.assignedTargetId = assignedTargetId; - return this; - } - - public DistributionSetFilterBuilder setInstalledTargetId(final String installedTargetId) { - this.installedTargetId = installedTargetId; + public DistributionSetFilterBuilder setType(final DistributionSetType type) { + this.type = type; return this; } } + private final Boolean isDeleted; + private final Boolean isComplete; + private final DistributionSetType type; + private final String searchText; + private final Boolean selectDSWithNoTag; + private final Collection tagNames; + private final String assignedTargetId; - public Boolean getIsDeleted() { - return isDeleted; + private final String installedTargetId; + + /** + * Parametric constructor. + * + * @param builder + * DistributionSetFilterBuilder + */ + public DistributionSetFilter(final DistributionSetFilterBuilder builder) { + this.isDeleted = builder.isDeleted; + this.isComplete = builder.isComplete; + this.type = builder.type; + this.searchText = builder.searchText; + this.selectDSWithNoTag = builder.selectDSWithNoTag; + this.tagNames = builder.tagNames; + this.assignedTargetId = builder.assignedTargetId; + this.installedTargetId = builder.installedTargetId; + } + + public String getAssignedTargetId() { + return assignedTargetId; + } + + public String getInstalledTargetId() { + return installedTargetId; } public Boolean getIsComplete() { return isComplete; } - public DistributionSetType getType() { - return type; + public Boolean getIsDeleted() { + return isDeleted; } public String getSearchText() { @@ -137,12 +136,8 @@ public final class DistributionSetFilter { return tagNames; } - public String getAssignedTargetId() { - return assignedTargetId; - } - - public String getInstalledTargetId() { - return installedTargetId; + public DistributionSetType getType() { + return type; } } diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetMetadata.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetMetadata.java new file mode 100644 index 000000000..87a62e9ba --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetMetadata.java @@ -0,0 +1,22 @@ +/** + * 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.model; + +/** + * {@link MetaData} of a {@link DistributionSet}. + * + */ +public interface DistributionSetMetadata extends MetaData { + + /** + * @return {@link DistributionSet} of this {@link MetaData} entry. + */ + DistributionSet getDistributionSet(); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTag.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTag.java new file mode 100644 index 000000000..05089d138 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTag.java @@ -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.repository.model; + +import java.util.List; + +/** + * {@link Tag} of a {@link DistributionSet}. + * + */ +public interface DistributionSetTag extends Tag { + + /** + * @return {@link List} of {@link DistributionSet}s this {@link Tag} is + * assigned to. + */ + List getAssignedToDistributionSet(); + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTagAssignmentResult.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTagAssignmentResult.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTagAssignmentResult.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTagAssignmentResult.java diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetType.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetType.java new file mode 100644 index 000000000..cf5da40b2 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetType.java @@ -0,0 +1,173 @@ +/** + * 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.model; + +import java.util.Set; + +/** + * A {@link DistributionSetType} is an abstract definition for + * {@link DistributionSet} that defines what {@link SoftwareModule}s can be + * added (optional) to {@link DistributionSet} of that type or have to added + * (mandatory) in order to be considered complete. Only complete DS can be + * assigned to a {@link Target}. + * + */ +public interface DistributionSetType extends NamedEntity { + + /** + * @return true if the type is deleted and only kept for + * history purposes. + */ + boolean isDeleted(); + + /** + * @return set of {@link SoftwareModuleType}s that need to be in a + * {@link DistributionSet} of this type to be + * {@link DistributionSet#isComplete()}. + */ + Set getMandatoryModuleTypes(); + + /** + * @return set of optional {@link SoftwareModuleType}s that can be in a + * {@link DistributionSet} of this type. + */ + Set getOptionalModuleTypes(); + + /** + * Checks if the given {@link SoftwareModuleType} is in this + * {@link DistributionSetType}. + * + * @param softwareModuleType + * search for + * @return true if found + */ + default boolean containsModuleType(final SoftwareModuleType softwareModuleType) { + return containsMandatoryModuleType(softwareModuleType) || containsOptionalModuleType(softwareModuleType); + } + + /** + * Checks if the given {@link SoftwareModuleType} is in + * {@link #getMandatoryModuleTypes()}. + * + * @param softwareModuleType + * search for + * @return true if found + */ + default boolean containsMandatoryModuleType(final SoftwareModuleType softwareModuleType) { + return containsMandatoryModuleType(softwareModuleType.getId()); + } + + /** + * Checks if the given {@link SoftwareModuleType} is in + * {@link #getMandatoryModuleTypes()}. + * + * @param softwareModuleTypeId + * search for by {@link SoftwareModuleType#getId()} + * @return true if found + */ + default boolean containsMandatoryModuleType(final Long softwareModuleTypeId) { + return getMandatoryModuleTypes().stream().filter(element -> element.getId().equals(softwareModuleTypeId)) + .findFirst().isPresent(); + } + + /** + * Checks if the given {@link SoftwareModuleType} is in + * {@link #getOptionalModuleTypes()}. + * + * @param softwareModuleType + * search for + * @return true if found + */ + default boolean containsOptionalModuleType(final SoftwareModuleType softwareModuleType) { + return containsOptionalModuleType(softwareModuleType.getId()); + } + + /** + * Checks if the given {@link SoftwareModuleType} is in + * {@link #getOptionalModuleTypes()}. + * + * @param softwareModuleTypeId + * search by {@link SoftwareModuleType#getId()} + * @return true if found + */ + default boolean containsOptionalModuleType(final Long softwareModuleTypeId) { + return getOptionalModuleTypes().stream().filter(element -> element.getId().equals(softwareModuleTypeId)) + .findFirst().isPresent(); + } + + /** + * Compares the modules of this {@link DistributionSetType} and the given + * one. + * + * @param dsType + * to compare with + * @return true if the lists are identical. + */ + boolean areModuleEntriesIdentical(DistributionSetType dsType); + + /** + * Adds {@link SoftwareModuleType} that is optional for the + * {@link DistributionSet}. + * + * @param smType + * to add + * @return updated instance + */ + DistributionSetType addOptionalModuleType(SoftwareModuleType smType); + + /** + * Adds {@link SoftwareModuleType} that is mandatory for the + * {@link DistributionSet}. + * + * @param smType + * to add + * @return updated instance + */ + DistributionSetType addMandatoryModuleType(SoftwareModuleType smType); + + /** + * Removes {@link SoftwareModuleType} from the list. + * + * @param smTypeId + * to remove + * @return updated instance + */ + DistributionSetType removeModuleType(Long smTypeId); + + /** + * @return business key of this {@link DistributionSetType}. + */ + String getKey(); + + /** + * @param key + * of this {@link DistributionSetType}. + */ + void setKey(String key); + + /** + * @param distributionSet + * to check for completeness + * @return true if the all mandatory software module types are + * in the system. + */ + boolean checkComplete(DistributionSet distributionSet); + + /** + * @return get color code to by used in management UI views. + */ + String getColour(); + + /** + * @param colour + * code to by used in management UI views. + */ + void setColour(final String colour); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifact.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifact.java new file mode 100644 index 000000000..7e1a965e7 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifact.java @@ -0,0 +1,41 @@ +/** + * 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.model; + +import java.net.URL; + +/** + * External artifact representation with all the necessary information to + * generate an artifact {@link URL} at runtime. + * + */ +public interface ExternalArtifact extends Artifact { + + /** + * @return {@link ExternalArtifactProvider} of this {@link Artifact}. + */ + ExternalArtifactProvider getExternalArtifactProvider(); + + /** + * @return generated download {@link URL}. + */ + String getUrl(); + + /** + * @return suffix for {@link URL} generation. + */ + String getUrlSuffix(); + + /** + * @param urlSuffix + * the urlSuffix to set + */ + void setUrlSuffix(String urlSuffix); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifactProvider.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifactProvider.java new file mode 100644 index 000000000..139327096 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifactProvider.java @@ -0,0 +1,41 @@ +/** + * 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.model; + +/** + * External repositories for artifact storage. The update server provides URLs + * for the targets to download from these external resources but does not access + * them itself. + * + */ +public interface ExternalArtifactProvider extends NamedEntity { + + /** + * @return prefix for url generation + */ + String getBasePath(); + + /** + * @return default for {@link ExternalArtifact#getUrlSuffix()}. + */ + String getDefaultSuffix(); + + /** + * @param basePath + * prefix for url generation + */ + void setBasePath(String basePath); + + /** + * @param defaultSuffix + * for {@link ExternalArtifact#getUrlSuffix()}. + */ + void setDefaultSuffix(String defaultSuffix); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/LocalArtifact.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/LocalArtifact.java new file mode 100644 index 000000000..9aeb791c4 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/LocalArtifact.java @@ -0,0 +1,28 @@ +/** + * 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.model; + +import org.eclipse.hawkbit.artifact.repository.ArtifactRepository; + +/** + * Tenant specific locally stored artifact representation that is used by + * {@link SoftwareModule}s . It contains all information that is provided by the + * user while all update server generated information related to the artifact + * (hash, length) is stored directly with the binary itself in the + * {@link ArtifactRepository}. + * + */ +public interface LocalArtifact extends Artifact { + + /** + * @return the filename that was provided during upload. + */ + String getFilename(); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/MetaData.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/MetaData.java new file mode 100644 index 000000000..68b7349f9 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/MetaData.java @@ -0,0 +1,39 @@ +/** + * 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.model; + +import java.io.Serializable; + +/** + * Meta data for entities, a (key/value) store. + * + */ +public interface MetaData extends Serializable { + + /** + * @return the key + */ + String getKey(); + + /** + * @param key + */ + void setKey(String key); + + /** + * @return the value + */ + String getValue(); + + /** + * @param value + */ + void setValue(String value); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/NamedEntity.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/NamedEntity.java new file mode 100644 index 000000000..4d3f3e419 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/NamedEntity.java @@ -0,0 +1,39 @@ +/** + * 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.model; + +/** + * Entities that have a name and description. + * + */ +public interface NamedEntity extends TenantAwareBaseEntity { + + /** + * @return the description of the entity. + */ + String getDescription(); + + /** + * @return the name of the entity. + */ + String getName(); + + /** + * @param description + * of the entity. + */ + void setDescription(String description); + + /** + * @param name + * of the entity. + */ + void setName(String name); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/NamedVersionedEntity.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/NamedVersionedEntity.java new file mode 100644 index 000000000..b66115082 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/NamedVersionedEntity.java @@ -0,0 +1,28 @@ +/** + * 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.model; + +/** + * Entities that have a name and a description. + * + */ +public interface NamedVersionedEntity extends NamedEntity { + + /** + * @return the version of entity. + */ + String getVersion(); + + /** + * @param version + * of the entity. + */ + void setVersion(String version); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/PollStatus.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/PollStatus.java new file mode 100644 index 000000000..876020dbd --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/PollStatus.java @@ -0,0 +1,68 @@ +/** + * 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.model; + +import java.time.LocalDateTime; + +/** + * The poll time object which holds all the necessary information around the + * target poll time, e.g. the last poll time, the next poll time and the overdue + * poll time. + * + */ +public class PollStatus { + private final LocalDateTime lastPollDate; + private final LocalDateTime nextPollDate; + private final LocalDateTime overdueDate; + private final LocalDateTime currentDate; + + public PollStatus(final LocalDateTime lastPollDate, final LocalDateTime nextPollDate, + final LocalDateTime overdueDate, final LocalDateTime currentDate) { + this.lastPollDate = lastPollDate; + this.nextPollDate = nextPollDate; + this.overdueDate = overdueDate; + this.currentDate = currentDate; + } + + /** + * calculates if the target poll time is overdue and the target has not been + * polled in the configured poll time interval. + * + * @return {@code true} if the current time is after the poll time overdue + * date otherwise {@code false}. + */ + public boolean isOverdue() { + return currentDate.isAfter(overdueDate); + } + + /** + * @return the lastPollDate + */ + public LocalDateTime getLastPollDate() { + return lastPollDate; + } + + public LocalDateTime getNextPollDate() { + return nextPollDate; + } + + public LocalDateTime getOverdueDate() { + return overdueDate; + } + + public LocalDateTime getCurrentDate() { + return currentDate; + } + + @Override + public String toString() { + return "PollTime [lastPollDate=" + lastPollDate + ", nextPollDate=" + nextPollDate + ", overdueDate=" + + overdueDate + ", currentDate=" + currentDate + "]"; + } +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/RepositoryModelConstants.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/RepositoryModelConstants.java new file mode 100644 index 000000000..66806915a --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/RepositoryModelConstants.java @@ -0,0 +1,27 @@ +/** + * 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.model; + +/** + * Repository model constants. + * + */ +public final class RepositoryModelConstants { + + /** + * indicating that target action has no force time which is only needed in + * case of {@link Action.ActionType#TIMEFORCED}. + */ + public static final Long NO_FORCE_TIME = 0L; + + private RepositoryModelConstants() { + // Utility class. + } + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Rollout.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Rollout.java new file mode 100644 index 000000000..37185a8e2 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Rollout.java @@ -0,0 +1,159 @@ +/** + * 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.model; + +import java.util.List; +import java.util.concurrent.TimeUnit; + +import org.eclipse.hawkbit.repository.model.Action.ActionType; +import org.eclipse.hawkbit.repository.model.TotalTargetCountStatus.Status; + +/** + * Software update operations in large scale IoT scenarios with hundred of + * thousands of devices require special handling. + * + * That includes secure handling of large volumes of devices at rollout creation + * time. Monitoring of the rollout progress. Emergency rollout shutdown in case + * of problems on to many devices and reporting capabilities for a complete + * understanding of the rollout progress at each point in time. + * + */ +public interface Rollout extends NamedEntity { + + /** + * @return {@link DistributionSet} that is rolled out + */ + DistributionSet getDistributionSet(); + + /** + * @param distributionSet + * that is rolled out + */ + void setDistributionSet(DistributionSet distributionSet); + + /** + * @return list of deployment groups of the rollout. + */ + List getRolloutGroups(); + + /** + * @return rsql query that identifies the targets that are part of this + * rollout. + */ + String getTargetFilterQuery(); + + /** + * @param targetFilterQuery + * that identifies the targets that are part of this rollout. + */ + void setTargetFilterQuery(String targetFilterQuery); + + /** + * @return status of the rollout + */ + RolloutStatus getStatus(); + + /** + * @return {@link ActionType} of the rollout. + */ + ActionType getActionType(); + + /** + * @param actionType + * of the rollout. + */ + void setActionType(ActionType actionType); + + /** + * @return time in {@link TimeUnit#MILLISECONDS} after which + * {@link #isForced()} switches to true in case of + * {@link ActionType#TIMEFORCED}. + */ + long getForcedTime(); + + /** + * @param forcedTime + * in {@link TimeUnit#MILLISECONDS} after which + * {@link #isForced()} switches to true in case of + * {@link ActionType#TIMEFORCED}. + */ + void setForcedTime(long forcedTime); + + /** + * @return number of {@link Target}s in this rollout. + */ + long getTotalTargets(); + + /** + * @return number of {@link RolloutGroup}s. + */ + int getRolloutGroupsCreated(); + + /** + * @return all states with the respective target count in that + * {@link Status}. + */ + TotalTargetCountStatus getTotalTargetCountStatus(); + + /** + * + * State machine for rollout. + * + */ + public enum RolloutStatus { + + /** + * Rollouts is being created. + */ + CREATING, + + /** + * Rollout is ready to start. + */ + READY, + + /** + * Rollout is paused. + */ + PAUSED, + + /** + * Rollout is starting. + */ + STARTING, + + /** + * Rollout is stopped. + */ + STOPPED, + + /** + * Rollout is running. + */ + RUNNING, + + /** + * Rollout is finished. + */ + FINISHED, + + /** + * Rollout could not be created due to errors, might be a database + * problem during asynchronous creating. + */ + ERROR_CREATING, + + /** + * Rollout could not be started due to errors, might be database problem + * during asynchronous starting. + */ + ERROR_STARTING; + } + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroup.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroup.java new file mode 100644 index 000000000..3180fdb6a --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroup.java @@ -0,0 +1,284 @@ +/** + * 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.model; + +/** + * The core functionality of a {@link Rollout} is the cascading processing of + * (sub) deployment groups. The group defines under which conditions the + * following group is processed. + * + */ +public interface RolloutGroup extends NamedEntity { + + /** + * @return the corresponding {@link Rollout} of this group + */ + Rollout getRollout(); + + /** + * @param rollout + * sets the {@link Rollout} for this group + */ + void setRollout(Rollout rollout); + + /** + * @return the current {@link RolloutGroupStatus} for this group + */ + RolloutGroupStatus getStatus(); + + /** + * @param status + * the {@link RolloutGroupStatus} to set for this group + */ + void setStatus(RolloutGroupStatus status); + + /** + * @return the parent group of this group, in case the group is the root + * group it does not have a parent and so return {@code null} + */ + RolloutGroup getParent(); + + /** + * @return the {@link RolloutGroupSuccessCondition} for this group to + * indicate when a group is successful + */ + RolloutGroupSuccessCondition getSuccessCondition(); + + /** + * @param successCondition + * the {@link RolloutGroupSuccessCondition} to be set for this + * group to indicate when a group is successfully and a next + * group might be started + */ + void setSuccessCondition(RolloutGroupSuccessCondition successCondition); + + /** + * @return a String representation of the expression to be evaluated by the + * {@link RolloutGroupSuccessCondition} to indicate if the condition + * is true, might be {@code null} if no expression must be set for + * the {@link RolloutGroupSuccessCondition} + */ + String getSuccessConditionExp(); + + /** + * @param successConditionExp + * sets a String represented expression which is evaluated by the + * {@link RolloutGroupSuccessCondition}, might be {@code null} if + * the set {@link RolloutGroupSuccessCondition} can handle + * {@code null} value + */ + void setSuccessConditionExp(String successConditionExp); + + /** + * @return the {@link RolloutGroupErrorCondition} for this group to indicate + * when a group should marked as failed + */ + RolloutGroupErrorCondition getErrorCondition(); + + /** + * + * @param errorCondition + * the {@link RolloutGroupErrorCondition} to be set for this + * group to indicate when a group is marked as failed and the + * corresponding {@link RolloutGroupErrorAction} should be + * executed + */ + void setErrorCondition(RolloutGroupErrorCondition errorCondition); + + /** + * @return a String representation of the expression to be evaluated by the + * {@link RolloutGroupErrorCondition} to indicate if the condition + * is true, might be {@code null} if no expression must be set for + * the {@link RolloutGroupErrorCondition} + */ + String getErrorConditionExp(); + + /** + * @param errorExp + * sets a String represented expression which is evaluated by the + * {@link RolloutGroupErrorCondition}, might be {@code null} if + * the set {@link RolloutGroupErrorCondition} can handle + * {@code null} value + */ + void setErrorConditionExp(String errorExp); + + /** + * @return a {@link RolloutGroupErrorAction} which is executed when the + * given {@link RolloutGroupErrorCondition} is met, might be + * {@code null} if no error action is set + */ + RolloutGroupErrorAction getErrorAction(); + + /** + * @param errorAction + * the {@link RolloutGroupErrorAction} to be set which should be + * executed if the {@link RolloutGroupErrorCondition} is met, + * might be {@code null} if no error action should be executed + */ + void setErrorAction(RolloutGroupErrorAction errorAction); + + /** + * @return a String representation of the expression to be evaluated by the + * {@link RolloutGroupErrorAction} might be {@code null} if no + * expression must be set for the {@link RolloutGroupErrorAction} + */ + String getErrorActionExp(); + + /** + * @param errorActionExp + * sets a String represented expression which is evaluated by the + * {@link RolloutGroupErrorAction}, might be {@code null} if the + * set {@link RolloutGroupErrorAction} can handle {@code null} + * value + */ + void setErrorActionExp(String errorActionExp); + + /** + * @return the {@link RolloutGroupSuccessAction} which is executed if the + * {@link RolloutGroupSuccessCondition} is met + */ + RolloutGroupSuccessAction getSuccessAction(); + + /** + * @return a String representation of the expression to be evaluated by the + * {@link RolloutGroupSuccessAction} might be {@code null} if no + * expression must be set for the {@link RolloutGroupSuccessAction} + */ + String getSuccessActionExp(); + + /** + * @return the total amount of targets containing in this group + */ + long getTotalTargets(); + + /** + * @return the totalTargetCountStatus + */ + TotalTargetCountStatus getTotalTargetCountStatus(); + + /** + * @param totalTargetCountStatus + * the totalTargetCountStatus to set + */ + void setTotalTargetCountStatus(TotalTargetCountStatus totalTargetCountStatus); + + /** + * Rollout goup state machine. + * + */ + public enum RolloutGroupStatus { + + /** + * Ready to start the group. + */ + READY, + + /** + * Group is scheduled and started sometime, e.g. trigger of group + * before. + */ + SCHEDULED, + + /** + * Group is finished. + */ + FINISHED, + + /** + * Group is finished and has errors. + */ + ERROR, + + /** + * Group is running. + */ + RUNNING; + } + + /** + * The condition to evaluate if an group is success state. + */ + public enum RolloutGroupSuccessCondition { + THRESHOLD("thresholdRolloutGroupSuccessCondition"); + + private final String beanName; + + private RolloutGroupSuccessCondition(final String beanName) { + this.beanName = beanName; + } + + /** + * @return the beanName + */ + public String getBeanName() { + return beanName; + } + } + + /** + * The condition to evaluate if an group is in error state. + */ + public enum RolloutGroupErrorCondition { + THRESHOLD("thresholdRolloutGroupErrorCondition"); + + private final String beanName; + + private RolloutGroupErrorCondition(final String beanName) { + this.beanName = beanName; + } + + /** + * @return the beanName + */ + public String getBeanName() { + return beanName; + } + } + + /** + * The actions executed when the {@link RolloutGroup#errorCondition} is hit. + */ + public enum RolloutGroupErrorAction { + PAUSE("pauseRolloutGroupAction"); + + private final String beanName; + + private RolloutGroupErrorAction(final String beanName) { + this.beanName = beanName; + } + + /** + * @return the beanName + */ + public String getBeanName() { + return beanName; + } + } + + /** + * The actions executed when the {@link RolloutGroup#successCondition} is + * hit. + */ + public enum RolloutGroupSuccessAction { + NEXTGROUP("startNextRolloutGroupAction"); + + private final String beanName; + + private RolloutGroupSuccessAction(final String beanName) { + this.beanName = beanName; + } + + /** + * @return the beanName + */ + public String getBeanName() { + return beanName; + } + } +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroupConditionBuilder.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroupConditionBuilder.java new file mode 100644 index 000000000..7ef8c8a19 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroupConditionBuilder.java @@ -0,0 +1,91 @@ +/** + * 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.model; + +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; + +/** + * Builder to build easily the {@link RolloutGroupConditions}. + * + */ +public class RolloutGroupConditionBuilder { + private final RolloutGroupConditions conditions = new RolloutGroupConditions(); + + /** + * @return completed {@link RolloutGroupConditions}. + */ + public RolloutGroupConditions build() { + return conditions; + } + + /** + * Sets the finish condition and expression on the builder. + * + * @param condition + * the finish condition + * @param expression + * the finish expression + * @return the builder itself + */ + public RolloutGroupConditionBuilder successCondition(final RolloutGroupSuccessCondition condition, + final String expression) { + conditions.setSuccessCondition(condition); + conditions.setSuccessConditionExp(expression); + return this; + } + + /** + * Sets the success action and expression on the builder. + * + * @param action + * the success action + * @param expression + * the error expression + * @return the builder itself + */ + public RolloutGroupConditionBuilder successAction(final RolloutGroupSuccessAction action, final String expression) { + conditions.setSuccessAction(action); + conditions.setSuccessActionExp(expression); + return this; + } + + /** + * Sets the error condition and expression on the builder. + * + * @param condition + * the error condition + * @param expression + * the error expression + * @return the builder itself + */ + public RolloutGroupConditionBuilder errorCondition(final RolloutGroupErrorCondition condition, + final String expression) { + conditions.setErrorCondition(condition); + conditions.setErrorConditionExp(expression); + return this; + } + + /** + * Sets the error action and expression on the builder. + * + * @param action + * the error action + * @param expression + * the error expression + * @return the builder itself + */ + public RolloutGroupConditionBuilder errorAction(final RolloutGroupErrorAction action, final String expression) { + conditions.setErrorAction(action); + conditions.setErrorActionExp(expression); + return this; + } +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroupConditions.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroupConditions.java new file mode 100644 index 000000000..618e93c4e --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroupConditions.java @@ -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.model; + +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; + +/** + * Object which holds all {@link RolloutGroup} conditions together which can + * easily built. + */ +public class RolloutGroupConditions { + private RolloutGroupSuccessCondition successCondition; + private String successConditionExp; + private RolloutGroupSuccessAction successAction; + private String successActionExp; + private RolloutGroupErrorCondition errorCondition; + private String errorConditionExp; + private RolloutGroupErrorAction errorAction; + private String errorActionExp; + + public RolloutGroupSuccessCondition getSuccessCondition() { + return successCondition; + } + + public void setSuccessCondition(final RolloutGroupSuccessCondition finishCondition) { + successCondition = finishCondition; + } + + public String getSuccessConditionExp() { + return successConditionExp; + } + + public void setSuccessConditionExp(final String finishConditionExp) { + successConditionExp = finishConditionExp; + } + + public RolloutGroupSuccessAction getSuccessAction() { + return successAction; + } + + public void setSuccessAction(final RolloutGroupSuccessAction successAction) { + this.successAction = successAction; + } + + public String getSuccessActionExp() { + return successActionExp; + } + + public void setSuccessActionExp(final String successActionExp) { + this.successActionExp = successActionExp; + } + + public RolloutGroupErrorCondition getErrorCondition() { + return errorCondition; + } + + public void setErrorCondition(final RolloutGroupErrorCondition errorCondition) { + this.errorCondition = errorCondition; + } + + public String getErrorConditionExp() { + return errorConditionExp; + } + + public void setErrorConditionExp(final String errorConditionExp) { + this.errorConditionExp = errorConditionExp; + } + + public RolloutGroupErrorAction getErrorAction() { + return errorAction; + } + + public void setErrorAction(final RolloutGroupErrorAction errorAction) { + this.errorAction = errorAction; + } + + public String getErrorActionExp() { + return errorActionExp; + } + + public void setErrorActionExp(final String errorActionExp) { + this.errorActionExp = errorActionExp; + } +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModule.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModule.java new file mode 100644 index 000000000..3c3a24fd0 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModule.java @@ -0,0 +1,111 @@ +/** + * 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.model; + +import java.util.List; +import java.util.Optional; + +public interface SoftwareModule extends NamedVersionedEntity { + + /** + * @param artifact + * is added to the assigned {@link Artifact}s. + */ + void addArtifact(LocalArtifact artifact); + + /** + * @param artifact + * is added to the assigned {@link Artifact}s. + */ + void addArtifact(ExternalArtifact artifact); + + /** + * @param artifactId + * to look for + * @return found {@link Artifact} + */ + Optional getLocalArtifact(Long artifactId); + + /** + * @param fileName + * to look for + * @return found {@link Artifact} + */ + Optional getLocalArtifactByFilename(String fileName); + + /** + * @return the artifacts + */ + List getArtifacts(); + + /** + * @return local artifacts only + */ + List getLocalArtifacts(); + + /** + * @return the vendor of this software module + */ + String getVendor(); + + /** + * @param vendor + * the vendor of this software module to set + */ + void setVendor(String vendor); + + /** + * @param artifact + * is removed from the assigned {@link LocalArtifact}s. + */ + void removeArtifact(LocalArtifact artifact); + + /** + * @param artifact + * is removed from the assigned {@link ExternalArtifact}s. + */ + void removeArtifact(ExternalArtifact artifact); + + /** + * @return the type of the software module + */ + SoftwareModuleType getType(); + + /** + * @return {@code true} if this software module is marked as deleted + * otherwise {@code false} + */ + boolean isDeleted(); + + /** + * Marks or un-marks this software module as deleted. + * + * @param deleted + * {@code true} if the software module should be marked as + * deleted otherwise {@code false} + */ + void setDeleted(boolean deleted); + + /** + * @param type + * the module type for this software module + */ + void setType(SoftwareModuleType type); + + /** + * @return immutable list of meta data elements. + */ + List getMetadata(); + + /** + * @return the assignedTo + */ + List getAssignedTo(); + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleIdName.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleIdName.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleIdName.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleIdName.java diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleMetadata.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleMetadata.java new file mode 100644 index 000000000..ebfea9c28 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleMetadata.java @@ -0,0 +1,28 @@ +/** + * 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.model; + +/** + * {@link MetaData} element of a {@link SoftwareModule}. + * + */ +public interface SoftwareModuleMetadata extends MetaData { + + /** + * @return {@link SoftwareModule} this entry belongs to. + */ + SoftwareModule getSoftwareModule(); + + /** + * @param softwareModule + * this entry belongs to. + */ + void setSoftwareModule(SoftwareModule softwareModule); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleType.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleType.java new file mode 100644 index 000000000..4bd52f3f0 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleType.java @@ -0,0 +1,60 @@ +/** + * 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.model; + +/** + * {@link SoftwareModuleType} is an abstract definition used in + * {@link DistributionSetType}s and includes additional {@link SoftwareModule} + * specific information. + * + */ +public interface SoftwareModuleType extends NamedEntity { + + /** + * @return business key of this {@link SoftwareModuleType}. + */ + String getKey(); + + /** + * @param key + * of this {@link SoftwareModuleType}. + */ + void setKey(String key); + + /** + * @return maximum assignments of an {@link SoftwareModule} of this type to + * a {@link DistributionSet}. + */ + int getMaxAssignments(); + + /** + * @param maxAssignments + * of an {@link SoftwareModule} of this type to a + * {@link DistributionSet}. + */ + void setMaxAssignments(int maxAssignments); + + /** + * @return true if the type is deleted and only kept for + * history purposes. + */ + boolean isDeleted(); + + /** + * @return get color code to by used in management UI views. + */ + String getColour(); + + /** + * @param colour + * code to by used in management UI views. + */ + void setColour(final String colour); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Tag.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Tag.java new file mode 100644 index 000000000..bfade80e8 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Tag.java @@ -0,0 +1,27 @@ +/** + * 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.model; + +/** + * {@link Tag} entry. + * + */ +public interface Tag extends NamedEntity { + + /** + * @return colour code of the tag used in Management UI. + */ + String getColour(); + + /** + * @param colour + */ + void setColour(String colour); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Target.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Target.java new file mode 100644 index 000000000..56ab89ad3 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Target.java @@ -0,0 +1,61 @@ +/** + * 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.model; + +import java.util.List; +import java.util.Set; + +/** + *

+ * The {@link Target} is the target of all provisioning operations. It contains + * the currently installed {@link DistributionSet} (i.e. current state). In + * addition it holds the target {@link DistributionSet} that has to be + * provisioned next (i.e. target state). + *

+ */ +public interface Target extends NamedEntity { + + /** + * @return currently assigned {@link DistributionSet}. + */ + DistributionSet getAssignedDistributionSet(); + + /** + * @return business identifier of the {@link Target} + */ + String getControllerId(); + + /** + * @return assigned {@link TargetTag}s. + */ + Set getTags(); + + /** + * @return {@link Action} history of the {@link Target}. + */ + List getActions(); + + /** + * @return {@link TargetIdName} view of the {@link Target}. + */ + default TargetIdName getTargetIdName() { + return new TargetIdName(getId(), getControllerId(), getName()); + } + + /** + * @return the targetInfo object + */ + TargetInfo getTargetInfo(); + + /** + * @return the securityToken + */ + String getSecurityToken(); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetFilterQuery.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetFilterQuery.java new file mode 100644 index 000000000..5052a0060 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetFilterQuery.java @@ -0,0 +1,59 @@ +/** + * 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.model; + +/** + * Managed filter entity. + * + * Supported operators. + *
    + *
  • Equal to : ==
  • + *
  • Not equal to : !=
  • + *
  • Less than : =lt= or <
  • + *
  • Less than or equal to : =le= or <=
  • + *
  • Greater than operator : =gt= or >
  • + *
  • Greater than or equal to : =ge= or >=
  • + *
+ * Examples of RSQL expressions in both FIQL-like and alternative notation: + *
    + *
  • version==2.0.0
  • + *
  • name==targetId1;description==plugAndPlay
  • + *
  • name==targetId1 and description==plugAndPlay
  • + *
  • name==targetId1;description==plugAndPlay
  • + *
  • name==targetId1 and description==plugAndPlay
  • + *
  • name==targetId1,description==plugAndPlay,updateStatus==UNKNOWN
  • + *
  • name==targetId1 or description==plugAndPlay or updateStatus==UNKNOWN
  • + *
+ * + */ +public interface TargetFilterQuery extends TenantAwareBaseEntity { + + /** + * @return name of the {@link TargetFilterQuery}. + */ + String getName(); + + /** + * @param name + * of the {@link TargetFilterQuery}. + */ + void setName(String name); + + /** + * @return RSQL query + */ + String getQuery(); + + /** + * @param query + * in RSQL notation. + */ + void setQuery(String query); + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetIdName.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetIdName.java similarity index 96% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetIdName.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetIdName.java index 26a74e9bb..444874581 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetIdName.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetIdName.java @@ -60,6 +60,8 @@ public class TargetIdName implements Serializable { } @Override + // Exception squid:S864 - generated code + @SuppressWarnings("squid:S864") public int hashCode() { final int prime = 31; int result = 1; diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetInfo.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetInfo.java new file mode 100644 index 000000000..6317f9783 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetInfo.java @@ -0,0 +1,71 @@ +/** + * 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.model; + +import java.io.Serializable; +import java.net.URI; +import java.text.AttributedCharacterIterator; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +public interface TargetInfo extends Serializable { + /** + * @return the address under whioch the target can be reached + */ + URI getAddress(); + + /** + * @return {@link Target} this info element belongs to. + */ + Target getTarget(); + + /** + * @return time in {@link TimeUnit#MILLISECONDS} GMT when the {@link Target} + * polled the server the last time. + */ + Long getLastTargetQuery(); + + /** + * @return {@link AttributedCharacterIterator} that have been provided by + * the {@link Target} itself, e.g. hardware revision, serial number, + * mac address etc. + */ + Map getControllerAttributes(); + + /** + * @return time in {@link TimeUnit#MILLISECONDS} GMT when + * {@link #getInstalledDistributionSet()} was applied. + */ + Long getInstallationDate(); + + /** + * @return current status of the {@link Target}. + */ + TargetUpdateStatus getUpdateStatus(); + + /** + * @return currently installed {@link DistributionSet}. + */ + DistributionSet getInstalledDistributionSet(); + + /** + * @return the poll time which holds the last poll time of the target, the + * next poll time and the overdue time. In case the + * {@link #lastTargetQuery} is not set e.g. the target never polled + * before this method returns {@code null} + */ + PollStatus getPollStatus(); + + /** + * @return true if the {@link Target} has not jet provided + * {@link #getControllerAttributes()}. + */ + boolean isRequestControllerAttributes(); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetTag.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetTag.java new file mode 100644 index 000000000..f222e9e90 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetTag.java @@ -0,0 +1,24 @@ +/** + * 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.model; + +import java.util.List; + +/** + * Target tag element. + * + */ +public interface TargetTag extends Tag { + + /** + * @return {@link List} of targets assigned to this {@link Tag}. + */ + List getAssignedToTargets(); + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetTagAssignmentResult.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetTagAssignmentResult.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetTagAssignmentResult.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetTagAssignmentResult.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetUpdateStatus.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetUpdateStatus.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetUpdateStatus.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetUpdateStatus.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetWithActionStatus.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetWithActionStatus.java similarity index 93% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetWithActionStatus.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetWithActionStatus.java index ec09da3d5..9193b47ef 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetWithActionStatus.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetWithActionStatus.java @@ -12,14 +12,14 @@ import org.eclipse.hawkbit.repository.model.Action.Status; /** * - * Rollout - Target with action status. + * Target with action status. * */ public class TargetWithActionStatus { private Target target; - private Status status = null;; + private Status status; public TargetWithActionStatus(final Target target) { this.target = target; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetWithActionType.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetWithActionType.java similarity index 83% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetWithActionType.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetWithActionType.java index 18efa23a9..a9cfa81d1 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetWithActionType.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetWithActionType.java @@ -6,14 +6,12 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.model; -import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.ActionType; /** - * A custom JPA database return value object with the proper constructor so JPA - * is able to parse the result-set directly into this object. + * A custom view on {@link Target} with {@link ActionType}. * * * @@ -53,7 +51,7 @@ public class TargetWithActionType { if (actionType == ActionType.TIMEFORCED) { return forceTime; } - return Action.NO_FORCE_TIME; + return RepositoryModelConstants.NO_FORCE_TIME; } /** diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TenantAwareBaseEntity.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TenantAwareBaseEntity.java new file mode 100644 index 000000000..8c19db236 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TenantAwareBaseEntity.java @@ -0,0 +1,22 @@ +/** + * 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.model; + +/** + * {@link BaseEntity} that distinguishes between tenants. + * + */ +public interface TenantAwareBaseEntity extends BaseEntity { + + /** + * @return tenant name + */ + String getTenant(); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TenantConfiguration.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TenantConfiguration.java new file mode 100644 index 000000000..fdbc5c8d3 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TenantConfiguration.java @@ -0,0 +1,40 @@ +/** + * 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.model; + +/** + * Unstructured tenant configuration elements. Can be used to store arbitrary + * tenant configuration elements. + * + */ +public interface TenantConfiguration extends TenantAwareBaseEntity { + + /** + * @return key of the entry + */ + String getKey(); + + /** + * @param key + * of the entry + */ + void setKey(String key); + + /** + * @return value of the entry + */ + String getValue(); + + /** + * @param value + * of the entry + */ + void setValue(String value); + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantConfigurationValue.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TenantConfigurationValue.java similarity index 94% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantConfigurationValue.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TenantConfigurationValue.java index 37e00e247..a204ef506 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantConfigurationValue.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TenantConfigurationValue.java @@ -14,14 +14,14 @@ package org.eclipse.hawkbit.repository.model; * @param * type of the configuration value */ -public class TenantConfigurationValue { +public final class TenantConfigurationValue { private T value; private Long lastModifiedAt; private String lastModifiedBy; private Long createdAt; private String createdBy; - private boolean isGlobal = true; + private boolean global = true; private TenantConfigurationValue() { } @@ -41,7 +41,7 @@ public class TenantConfigurationValue { * @return true, if is global */ public boolean isGlobal() { - return isGlobal; + return global; } /** @@ -126,13 +126,13 @@ public class TenantConfigurationValue { /** * set the is global attribute. * - * @param isGlobal + * @param global * true when there is no tenant specific value, false * otherwise * @return the tenant configuration value builder */ - public TenantConfigurationValueBuilder isGlobal(final boolean isGlobal) { - this.configuration.isGlobal = isGlobal; + public TenantConfigurationValueBuilder global(final boolean global) { + this.configuration.global = global; return this; } diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TenantMetaData.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TenantMetaData.java new file mode 100644 index 000000000..0b40d9939 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TenantMetaData.java @@ -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.model; + +/** + * MetaData of a tenant account. + * + */ +public interface TenantMetaData extends BaseEntity { + + /** + * @return default {@link DistributionSetType}. + */ + DistributionSetType getDefaultDsType(); + + /** + * @param defaultDsType + * that is used of none is selected for a new + * {@link DistributionSet}. + */ + void setDefaultDsType(DistributionSetType defaultDsType); + + /** + * @return tenant name + */ + String getTenant(); + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TotalTargetCountActionStatus.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TotalTargetCountActionStatus.java similarity index 100% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TotalTargetCountActionStatus.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TotalTargetCountActionStatus.java diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TotalTargetCountStatus.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TotalTargetCountStatus.java similarity index 62% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TotalTargetCountStatus.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TotalTargetCountStatus.java index 13c41baf3..bcb0df3f4 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TotalTargetCountStatus.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TotalTargetCountStatus.java @@ -15,7 +15,8 @@ import java.util.Map; /** * - * Store all states with the target count of a rollout or rolloutgroup. + * Store target count of a {@link Rollout} or {@link RolloutGroup} for every + * {@link Status}. * */ public class TotalTargetCountStatus { @@ -24,7 +25,35 @@ public class TotalTargetCountStatus { * Status of the total target counts. */ public enum Status { - SCHEDULED, RUNNING, ERROR, FINISHED, CANCELLED, NOTSTARTED + /** + * Action is scheduled. + */ + SCHEDULED, + + /** + * Action is still running. + */ + RUNNING, + + /** + * Action failed. + */ + ERROR, + + /** + * Action is completed. + */ + FINISHED, + + /** + * Action is canceled. + */ + CANCELLED, + + /** + * Action is not started yet. + */ + NOTSTARTED } private final Map statusTotalCountMap = new EnumMap<>(Status.class); @@ -35,7 +64,7 @@ public class TotalTargetCountStatus { * * @param targetCountActionStatus * the action state map - * @param totalTargets + * @param totalTargetCount * the total target count */ public TotalTargetCountStatus(final List targetCountActionStatus, @@ -81,8 +110,7 @@ public class TotalTargetCountStatus { * @param statusTotalCountMap * the map * @param rolloutStatusCountItems - * all target statut with total count - * @return some state is populated nothing is happend + * all target {@link Status} with total count */ private final void mapActionStatusToTotalTargetCountStatus( final List targetCountActionStatus) { @@ -93,33 +121,40 @@ public class TotalTargetCountStatus { statusTotalCountMap.put(Status.RUNNING, 0L); Long notStartedTargetCount = totalTargetCount; for (final TotalTargetCountActionStatus item : targetCountActionStatus) { - switch (item.getStatus()) { - case SCHEDULED: - statusTotalCountMap.put(Status.SCHEDULED, item.getCount()); - break; - case ERROR: - statusTotalCountMap.put(Status.ERROR, item.getCount()); - break; - case FINISHED: - statusTotalCountMap.put(Status.FINISHED, item.getCount()); - break; - case RETRIEVED: - case RUNNING: - case WARNING: - case DOWNLOAD: - case CANCELING: - final Long runningItemsCount = statusTotalCountMap.get(Status.RUNNING) + item.getCount(); - statusTotalCountMap.put(Status.RUNNING, runningItemsCount); - break; - case CANCELED: - statusTotalCountMap.put(Status.CANCELLED, item.getCount()); - break; - default: - throw new IllegalArgumentException("State " + item.getStatus() + "is not valid"); - } + convertStatus(item); notStartedTargetCount -= item.getCount(); } statusTotalCountMap.put(TotalTargetCountStatus.Status.NOTSTARTED, notStartedTargetCount); } + // Exception squid:MethodCyclomaticComplexity - simple state conversion, not + // really complex. + @SuppressWarnings("squid:MethodCyclomaticComplexity") + private void convertStatus(final TotalTargetCountActionStatus item) { + switch (item.getStatus()) { + case SCHEDULED: + statusTotalCountMap.put(Status.SCHEDULED, item.getCount()); + break; + case ERROR: + statusTotalCountMap.put(Status.ERROR, item.getCount()); + break; + case FINISHED: + statusTotalCountMap.put(Status.FINISHED, item.getCount()); + break; + case RETRIEVED: + case RUNNING: + case WARNING: + case DOWNLOAD: + case CANCELING: + final Long runningItemsCount = statusTotalCountMap.get(Status.RUNNING) + item.getCount(); + statusTotalCountMap.put(Status.RUNNING, runningItemsCount); + break; + case CANCELED: + statusTotalCountMap.put(Status.CANCELLED, item.getCount()); + break; + default: + throw new IllegalArgumentException("State " + item.getStatus() + "is not valid"); + } + } + } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/AbstractReportSeries.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/AbstractReportSeries.java similarity index 94% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/AbstractReportSeries.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/AbstractReportSeries.java index 0542f68c9..747cd8279 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/AbstractReportSeries.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/AbstractReportSeries.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.report.model; +package org.eclipse.hawkbit.repository.report.model; import java.io.Serializable; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/DataReportSeries.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/DataReportSeries.java similarity index 97% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/DataReportSeries.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/DataReportSeries.java index 39c8f5723..e9fb032c3 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/DataReportSeries.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/DataReportSeries.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.report.model; +package org.eclipse.hawkbit.repository.report.model; import java.io.Serializable; import java.util.ArrayList; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/DataReportSeriesItem.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/DataReportSeriesItem.java similarity index 95% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/DataReportSeriesItem.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/DataReportSeriesItem.java index 492e27e1e..7dba6c082 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/DataReportSeriesItem.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/DataReportSeriesItem.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.report.model; +package org.eclipse.hawkbit.repository.report.model; import java.io.Serializable; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/InnerOuterDataReportSeries.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/InnerOuterDataReportSeries.java similarity index 96% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/InnerOuterDataReportSeries.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/InnerOuterDataReportSeries.java index b63935b39..357f9a554 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/InnerOuterDataReportSeries.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/InnerOuterDataReportSeries.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.report.model; +package org.eclipse.hawkbit.repository.report.model; import java.io.Serializable; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/ListReportSeries.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/ListReportSeries.java similarity index 96% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/ListReportSeries.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/ListReportSeries.java index 79c496480..18b011420 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/ListReportSeries.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/ListReportSeries.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.report.model; +package org.eclipse.hawkbit.repository.report.model; import java.util.ArrayList; import java.util.Collections; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/SeriesTime.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/SeriesTime.java similarity index 93% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/SeriesTime.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/SeriesTime.java index a50171479..0ab466acd 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/SeriesTime.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/SeriesTime.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.report.model; +package org.eclipse.hawkbit.repository.report.model; /** * A series time enum definition for {@link DataReportSeriesItem}s. diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/SystemUsageReport.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/SystemUsageReport.java similarity index 97% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/SystemUsageReport.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/SystemUsageReport.java index 45cc60cba..fe6c6bb96 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/SystemUsageReport.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/SystemUsageReport.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.report.model; +package org.eclipse.hawkbit.repository.report.model; import java.util.ArrayList; import java.util.List; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/TenantUsage.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/TenantUsage.java similarity index 98% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/TenantUsage.java rename to hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/TenantUsage.java index d0ee7102c..5467099c4 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/report/model/TenantUsage.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/TenantUsage.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.report.model; +package org.eclipse.hawkbit.repository.report.model; /** * System usage stats element for a tenant. diff --git a/hawkbit-repository/hawkbit-repository-core/pom.xml b/hawkbit-repository/hawkbit-repository-core/pom.xml new file mode 100644 index 000000000..77e20cf3c --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-core/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + + org.eclipse.hawkbit + hawkbit-repository + 0.2.0-SNAPSHOT + + hawkbit-repository-core + hawkBit :: Repository Core Implementation Support + + + + org.eclipse.hawkbit + hawkbit-repository-api + ${project.version} + + + + \ No newline at end of file diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/EventBusHolder.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/EventBusHolder.java similarity index 87% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/EventBusHolder.java rename to hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/EventBusHolder.java index 8111a1c28..3829d639b 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/EventBusHolder.java +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/EventBusHolder.java @@ -6,9 +6,8 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model.helper; +package org.eclipse.hawkbit.repository.jpa.model.helper; -import org.eclipse.hawkbit.eventbus.CacheFieldEntityListener; import org.springframework.beans.factory.annotation.Autowired; import com.google.common.eventbus.EventBus; @@ -16,7 +15,7 @@ import com.google.common.eventbus.EventBus; /** * A singleton bean which holds the {@link EventBus} to have to the cache * manager in beans not instantiated by spring e.g. JPA entities or - * {@link CacheFieldEntityListener} which cannot be autowired. + * CacheFieldEntityListener which cannot be autowired. * */ public final class EventBusHolder { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/SystemManagementHolder.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/SystemManagementHolder.java similarity index 96% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/SystemManagementHolder.java rename to hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/SystemManagementHolder.java index d1327c690..1b1fbb091 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/SystemManagementHolder.java +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/SystemManagementHolder.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model.helper; +package org.eclipse.hawkbit.repository.jpa.model.helper; import org.eclipse.hawkbit.repository.SystemManagement; import org.springframework.beans.factory.annotation.Autowired; diff --git a/hawkbit-repository/hawkbit-repository-jpa/.gitignore b/hawkbit-repository/hawkbit-repository-jpa/.gitignore new file mode 100644 index 000000000..ae3c17260 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/hawkbit-repository/README.md b/hawkbit-repository/hawkbit-repository-jpa/README.md similarity index 100% rename from hawkbit-repository/README.md rename to hawkbit-repository/hawkbit-repository-jpa/README.md diff --git a/hawkbit-repository/hawkbit-repository-jpa/pom.xml b/hawkbit-repository/hawkbit-repository-jpa/pom.xml new file mode 100644 index 000000000..bd56e9ca5 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/pom.xml @@ -0,0 +1,207 @@ + + + 4.0.0 + + org.eclipse.hawkbit + 0.2.0-SNAPSHOT + hawkbit-repository + + hawkbit-repository-jpa + hawkBit :: Repository JPA Implementation + + + + + com.ethlo.eclipselink.tools + http://ethlo.com/maven + + + + + + com.ethlo.eclipselink.tools + http://ethlo.com/maven + + + + + + + + org.eclipse.hawkbit + hawkbit-repository-api + ${project.version} + + + org.eclipse.hawkbit + hawkbit-repository-core + ${project.version} + + + org.eclipse.hawkbit + hawkbit-artifact-repository-mongo + ${project.version} + + + com.google.guava + guava + + + org.springframework.boot + spring-boot + + + org.springframework.boot + spring-boot-starter-logging + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.eclipse.persistence + org.eclipse.persistence.jpa + + + org.springframework.security + spring-security-core + + + org.flywaydb + flyway-core + + + org.springframework.boot + spring-boot-configuration-processor + true + + + cz.jirutka.rsql + rsql-parser + + + + + org.eclipse.hawkbit + hawkbit-repository-test + ${project.version} + test + + + com.fasterxml.jackson.core + jackson-core + test + + + com.fasterxml.jackson.core + jackson-databind + test + + + com.h2database + h2 + test + + + org.mariadb.jdbc + mariadb-java-client + test + + + javax.el + javax.el-api + test + + + ru.yandex.qatools.allure + allure-junit-adaptor + test + + + org.easytesting + fest-assert-core + test + + + org.easytesting + fest-assert + test + + + + + + + org.bsc.maven + maven-processor-plugin + + + process + + process + + generate-sources + + + org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor + + + + + + + org.hibernate + hibernate-jpamodelgen + ${hibernate.version} + + + + + + com.ethlo.persistence.tools + eclipselink-maven-plugin + 2.6.2 + + + process-classes + + weave + + + + + + org.eclipse.persistence + org.eclipse.persistence.jpa + ${eclipselink.version} + + + org.javassist + javassist + 3.20.0-GA + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + test-jar + + + + + + + diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/EnableJpaRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/EnableJpaRepository.java new file mode 100644 index 000000000..55fd4a111 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/EnableJpaRepository.java @@ -0,0 +1,32 @@ +/** + * 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; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.stereotype.Controller; + +/** + * Annotation to enable {@link ComponentScan} in the resource package to setup + * all {@link Controller} annotated classes and setup the REST-Resources for the + * Management API. + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Configuration +@Import(RepositoryApplicationConfiguration.class) +public @interface EnableJpaRepository { + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java similarity index 63% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java index b7330a2fb..50207037a 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java @@ -11,33 +11,21 @@ package org.eclipse.hawkbit; import java.util.HashMap; import java.util.Map; -import org.eclipse.hawkbit.aspects.ExceptionMappingAspectHandler; -import org.eclipse.hawkbit.repository.ArtifactManagement; -import org.eclipse.hawkbit.repository.ControllerManagement; -import org.eclipse.hawkbit.repository.DeploymentManagement; -import org.eclipse.hawkbit.repository.DistributionSetManagement; -import org.eclipse.hawkbit.repository.ReportManagement; -import org.eclipse.hawkbit.repository.RolloutGroupManagement; -import org.eclipse.hawkbit.repository.RolloutManagement; -import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.SystemManagement; -import org.eclipse.hawkbit.repository.TagManagement; -import org.eclipse.hawkbit.repository.TargetFilterQueryManagement; -import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; -import org.eclipse.hawkbit.repository.TenantStatsManagement; -import org.eclipse.hawkbit.repository.model.helper.AfterTransactionCommitExecutorHolder; -import org.eclipse.hawkbit.repository.model.helper.CacheManagerHolder; -import org.eclipse.hawkbit.repository.model.helper.SecurityTokenGeneratorHolder; -import org.eclipse.hawkbit.repository.model.helper.SystemManagementHolder; -import org.eclipse.hawkbit.repository.model.helper.SystemSecurityContextHolder; -import org.eclipse.hawkbit.repository.model.helper.TenantAwareHolder; -import org.eclipse.hawkbit.repository.model.helper.TenantConfigurationManagementHolder; +import org.eclipse.hawkbit.repository.jpa.aspects.ExceptionMappingAspectHandler; +import org.eclipse.hawkbit.repository.jpa.configuration.MultiTenantJpaTransactionManager; +import org.eclipse.hawkbit.repository.jpa.model.helper.AfterTransactionCommitExecutorHolder; +import org.eclipse.hawkbit.repository.jpa.model.helper.CacheManagerHolder; +import org.eclipse.hawkbit.repository.jpa.model.helper.SecurityTokenGeneratorHolder; +import org.eclipse.hawkbit.repository.jpa.model.helper.SystemManagementHolder; +import org.eclipse.hawkbit.repository.jpa.model.helper.SystemSecurityContextHolder; +import org.eclipse.hawkbit.repository.jpa.model.helper.TenantAwareHolder; +import org.eclipse.hawkbit.repository.jpa.model.helper.TenantConfigurationManagementHolder; import org.eclipse.hawkbit.security.SecurityTokenGenerator; import org.eclipse.hawkbit.security.SystemSecurityContext; import org.eclipse.hawkbit.tenancy.TenantAware; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -55,7 +43,7 @@ import org.springframework.validation.beanvalidation.MethodValidationPostProcess * General configuration for the SP Repository. * */ -@EnableJpaRepositories(basePackages = { "org.eclipse.hawkbit.repository" }) +@EnableJpaRepositories(basePackages = { "org.eclipse.hawkbit.repository.jpa" }) @EnableTransactionManagement @EnableJpaAuditing @EnableAspectJAutoProxy @@ -63,7 +51,6 @@ import org.springframework.validation.beanvalidation.MethodValidationPostProcess @ComponentScan @EnableAutoConfiguration public class RepositoryApplicationConfiguration extends JpaBaseConfiguration { - /** * @return the {@link SystemSecurityContext} singleton bean which make it * accessible in beans which cannot access the service directly, @@ -170,6 +157,7 @@ public class RepositoryApplicationConfiguration extends JpaBaseConfiguration { properties.put("eclipselink.ddl-generation", "none"); properties.put("eclipselink.persistence-context.flush-mode", "auto"); + properties.put("eclipselink.logging.logger", "JavaLogger"); return properties; } @@ -185,89 +173,4 @@ public class RepositoryApplicationConfiguration extends JpaBaseConfiguration { public PlatformTransactionManager transactionManager() { return new MultiTenantJpaTransactionManager(); } - - @Bean - @ConditionalOnMissingBean - public SystemManagement systemManagement() { - return new SystemManagement(); - } - - @Bean - @ConditionalOnMissingBean - public ReportManagement reportManagement() { - return new ReportManagement(); - } - - @Bean - @ConditionalOnMissingBean - public DistributionSetManagement distributionSetManagement() { - return new DistributionSetManagement(); - } - - @Bean - @ConditionalOnMissingBean - public TenantStatsManagement tenantStatsManagement() { - return new TenantStatsManagement(); - } - - @Bean - @ConditionalOnMissingBean - public TenantConfigurationManagement tenantConfigurationManagement() { - return new TenantConfigurationManagement(); - } - - @Bean - @ConditionalOnMissingBean - public TargetManagement targetManagement() { - return new TargetManagement(); - } - - @Bean - @ConditionalOnMissingBean - public TargetFilterQueryManagement targetFilterQueryManagement() { - return new TargetFilterQueryManagement(); - } - - @Bean - @ConditionalOnMissingBean - public TagManagement tagManagement() { - return new TagManagement(); - } - - @Bean - @ConditionalOnMissingBean - public SoftwareManagement softwareManagement() { - return new SoftwareManagement(); - } - - @Bean - @ConditionalOnMissingBean - public RolloutManagement rolloutManagement() { - return new RolloutManagement(); - } - - @Bean - @ConditionalOnMissingBean - public RolloutGroupManagement rolloutGroupManagement() { - return new RolloutGroupManagement(); - } - - @Bean - @ConditionalOnMissingBean - public DeploymentManagement deploymentManagement() { - return new DeploymentManagement(); - } - - @Bean - @ConditionalOnMissingBean - public ControllerManagement controllerManagement() { - return new ControllerManagement(); - } - - @Bean - @ConditionalOnMissingBean - public ArtifactManagement artifactManagement() { - return new ArtifactManagement(); - } - } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ActionRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionRepository.java similarity index 79% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ActionRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionRepository.java index 742a7d731..0eebbced1 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ActionRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionRepository.java @@ -6,11 +6,17 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import java.util.Collection; import java.util.List; +import org.eclipse.hawkbit.repository.jpa.model.JpaAction; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; +import org.eclipse.hawkbit.repository.jpa.model.JpaRollout; +import org.eclipse.hawkbit.repository.jpa.model.JpaRolloutGroup; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.DistributionSet; @@ -37,7 +43,7 @@ import org.springframework.transaction.annotation.Transactional; * */ @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) -public interface ActionRepository extends BaseEntityRepository, JpaSpecificationExecutor { +public interface ActionRepository extends BaseEntityRepository, JpaSpecificationExecutor { /** * Retrieves an Action with all lazy attributes. * @@ -46,7 +52,7 @@ public interface ActionRepository extends BaseEntityRepository, Jp * @return the found {@link Action} */ @EntityGraph(value = "Action.all", type = EntityGraphType.LOAD) - Action findById(Long actionId); + JpaAction findById(Long actionId); /** * Retrieves all {@link Action}s which are referring the given @@ -58,7 +64,7 @@ public interface ActionRepository extends BaseEntityRepository, Jp * the {@link DistributionSet} on which will be filtered * @return the found {@link Action}s */ - Page findByDistributionSet(final Pageable pageable, final DistributionSet ds); + Page findByDistributionSet(final Pageable pageable, final JpaDistributionSet ds); /** * Retrieves all {@link Action}s which are referring the given @@ -70,7 +76,7 @@ public interface ActionRepository extends BaseEntityRepository, Jp * the target to find assigned actions * @return the found {@link Action}s */ - Slice findByTarget(Pageable pageable, Target target); + Slice findByTarget(Pageable pageable, JpaTarget target); /** * Retrieves all {@link Action}s which are active and referring the given @@ -86,7 +92,7 @@ public interface ActionRepository extends BaseEntityRepository, Jp * @return the found {@link Action}s */ @EntityGraph(value = "Action.ds", type = EntityGraphType.LOAD) - List findByTargetAndActiveOrderByIdAsc(final Target target, boolean active); + List findByTargetAndActiveOrderByIdAsc(final JpaTarget target, boolean active); /** * Retrieves latest {@link UpdateAction} for given target and @@ -99,9 +105,9 @@ public interface ActionRepository extends BaseEntityRepository, Jp * @return action if there is one with assigned target and module is part of * assigned {@link DistributionSet}. */ - @Query("Select a from Action a join a.distributionSet ds join ds.modules modul where a.target.controllerId = :target and modul = :module order by a.id desc") + @Query("Select a from JpaAction a join a.distributionSet ds join ds.modules modul where a.target.controllerId = :target and modul = :module order by a.id desc") List findActionByTargetAndSoftwareModule(@Param("target") final String targetId, - @Param("module") SoftwareModule module); + @Param("module") JpaSoftwareModule module); /** * Retrieves all {@link UpdateAction}s which are referring the given @@ -115,9 +121,9 @@ public interface ActionRepository extends BaseEntityRepository, Jp * the {@link DistributionSet} on which will be filtered * @return the found {@link UpdateAction}s */ - @Query("Select a from Action a where a.target = :target and a.distributionSet = :ds order by a.id") - Page findByTargetAndDistributionSet(final Pageable pageable, @Param("target") final Target target, - @Param("ds") DistributionSet ds); + @Query("Select a from JpaAction a where a.target = :target and a.distributionSet = :ds order by a.id") + Page findByTargetAndDistributionSet(final Pageable pageable, @Param("target") final JpaTarget target, + @Param("ds") JpaDistributionSet ds); /** * Retrieves all {@link Action}s of a specific target, without pagination @@ -127,8 +133,8 @@ public interface ActionRepository extends BaseEntityRepository, Jp * to search for * @return a list of actions according to the searched target */ - @Query("Select a from Action a where a.target = :target order by a.id") - List findByTarget(@Param("target") final Target target); + @Query("Select a from JpaAction a where a.target = :target order by a.id") + List findByTarget(@Param("target") final JpaTarget target); /** * Retrieves all {@link Action}s of a specific target and given active flag @@ -143,8 +149,8 @@ public interface ActionRepository extends BaseEntityRepository, Jp * {@code false} for inactive * @return a paged list of actions ordered by action ID */ - @Query("Select a from Action a where a.target = :target and a.active= :active order by a.id") - Page findByActiveAndTarget(Pageable pageable, @Param("target") Target target, + @Query("Select a from JpaAction a where a.target = :target and a.active= :active order by a.id") + Page findByActiveAndTarget(Pageable pageable, @Param("target") JpaTarget target, @Param("active") boolean active); /** @@ -160,8 +166,8 @@ public interface ActionRepository extends BaseEntityRepository, Jp * @return a list of actions ordered by action ID */ @EntityGraph(value = "Action.ds", type = EntityGraphType.LOAD) - @Query("Select a from Action a where a.target = :target and a.active= :active order by a.id") - List findByActiveAndTarget(@Param("target") Target target, @Param("active") boolean active); + @Query("Select a from JpaAction a where a.target = :target and a.active= :active order by a.id") + List findByActiveAndTarget(@Param("target") JpaTarget target, @Param("active") boolean active); /** * Updates all {@link Action} to inactive for all targets with given ID. @@ -174,8 +180,8 @@ public interface ActionRepository extends BaseEntityRepository, Jp */ @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @Query("UPDATE Action a SET a.active = false WHERE a IN :keySet AND a.target IN :targetsIds") - void setToInactive(@Param("keySet") List keySet, @Param("targetsIds") List targetsIds); + @Query("UPDATE JpaAction a SET a.active = false WHERE a IN :keySet AND a.target IN :targetsIds") + void setToInactive(@Param("keySet") List keySet, @Param("targetsIds") List targetsIds); /** * Switches the status of actions from one specific status into another, @@ -193,7 +199,7 @@ public interface ActionRepository extends BaseEntityRepository, Jp */ @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @Query("UPDATE Action a SET a.status = :statusToSet WHERE a.target IN :targetsIds AND a.active = :active AND a.status = :currentStatus AND a.distributionSet.requiredMigrationStep = false") + @Query("UPDATE JpaAction a SET a.status = :statusToSet WHERE a.target IN :targetsIds AND a.active = :active AND a.status = :currentStatus AND a.distributionSet.requiredMigrationStep = false") void switchStatus(@Param("statusToSet") Action.Status statusToSet, @Param("targetsIds") List targetIds, @Param("active") boolean active, @Param("currentStatus") Action.Status currentStatus); @@ -213,8 +219,8 @@ public interface ActionRepository extends BaseEntityRepository, Jp */ @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @Query("UPDATE Action a SET a.status = :statusToSet WHERE a.rollout = :rollout AND a.active = :active AND a.status = :currentStatus") - void switchStatus(@Param("statusToSet") Action.Status statusToSet, @Param("rollout") Rollout rollout, + @Query("UPDATE JpaAction a SET a.status = :statusToSet WHERE a.rollout = :rollout AND a.active = :active AND a.status = :currentStatus") + void switchStatus(@Param("statusToSet") Action.Status statusToSet, @Param("rollout") JpaRollout rollout, @Param("active") boolean active, @Param("currentStatus") Action.Status currentStatus); /** @@ -228,8 +234,8 @@ public interface ActionRepository extends BaseEntityRepository, Jp * the status which the actions should not have * @return the found list of {@link Action}s */ - @Query("SELECT a FROM Action a WHERE a.active = true AND a.distributionSet.requiredMigrationStep = false AND a.target IN ?1 AND a.status != ?2") - List findByActiveAndTargetIdInAndActionStatusNotEqualToAndDistributionSetRequiredMigrationStep( + @Query("SELECT a FROM JpaAction a WHERE a.active = true AND a.distributionSet.requiredMigrationStep = false AND a.target IN ?1 AND a.status != ?2") + List findByActiveAndTargetIdInAndActionStatusNotEqualToAndDistributionSetRequiredMigrationStep( Collection targetIds, Action.Status notStatus); /** @@ -239,15 +245,15 @@ public interface ActionRepository extends BaseEntityRepository, Jp * the target to count the {@link Action}s * @return the count of actions referring to the given target */ - Long countByTarget(Target target); + Long countByTarget(JpaTarget target); @Override @CacheEvict(value = "feedbackReceivedOverTime", allEntries = true) - List save(Iterable entities); + List save(Iterable entities); @Override @CacheEvict(value = "feedbackReceivedOverTime", allEntries = true) - S save(S entity); + S save(S entity); /** * Counts all {@link Action}s referring to the given DistributionSet. @@ -256,7 +262,7 @@ public interface ActionRepository extends BaseEntityRepository, Jp * DistributionSet to count the {@link Action}s from * @return the count of actions referring to the given distributionSet */ - Long countByDistributionSet(DistributionSet distributionSet); + Long countByDistributionSet(JpaDistributionSet distributionSet); /** * Counts all {@link Action}s referring to the given rollout. @@ -265,7 +271,7 @@ public interface ActionRepository extends BaseEntityRepository, Jp * the rollout to count the {@link Action}s from * @return the count of actions referring to the given rollout */ - Long countByRollout(Rollout rollout); + Long countByRollout(JpaRollout rollout); /** * Counts all actions referring to a given rollout and rolloutgroup which @@ -286,8 +292,8 @@ public interface ActionRepository extends BaseEntityRepository, Jp * @return the count of actions referring the rollout and rolloutgroup and * are not in given states */ - Long countByRolloutAndRolloutGroupAndStatusNotAndStatusNotAndStatusNot(Rollout rollout, RolloutGroup rolloutGroup, - Status notStatus1, Status notStatus2, Status notStatus3); + Long countByRolloutAndRolloutGroupAndStatusNotAndStatusNotAndStatusNot(JpaRollout rollout, + JpaRolloutGroup rolloutGroup, Status notStatus1, Status notStatus2, Status notStatus3); /** * Counts all actions referring to a given rollout and rolloutgroup. @@ -298,7 +304,7 @@ public interface ActionRepository extends BaseEntityRepository, Jp * the rolloutgroup the actions belong to * @return the count of actions referring to a rollout and rolloutgroup */ - Long countByRolloutAndRolloutGroup(Rollout rollout, RolloutGroup rolloutGroup); + Long countByRolloutAndRolloutGroup(JpaRollout rollout, JpaRolloutGroup rolloutGroup); /** * Counts all actions referring to a given rollout, rolloutgroup and status. @@ -329,7 +335,7 @@ public interface ActionRepository extends BaseEntityRepository, Jp * @return the actions referring a specific rollout and a specific parent * rolloutgroup in a specific status */ - List findByRolloutAndRolloutGroupParentAndStatus(Rollout rollout, RolloutGroup rolloutGroupParent, + List findByRolloutAndRolloutGroupParentAndStatus(JpaRollout rollout, JpaRolloutGroup rolloutGroupParent, Status actionStatus); /** @@ -341,7 +347,7 @@ public interface ActionRepository extends BaseEntityRepository, Jp * the status of the actions * @return the actions referring a specific rollout an in a specific status */ - List findByRolloutAndStatus(Rollout rollout, Status actionStatus); + List findByRolloutAndStatus(JpaRollout rollout, Status actionStatus); /** * Get list of objects which has details of status and count of targets in @@ -351,7 +357,7 @@ public interface ActionRepository extends BaseEntityRepository, Jp * id of {@link Rollout} * @return list of objects with status and target count */ - @Query("SELECT NEW org.eclipse.hawkbit.repository.model.TotalTargetCountActionStatus( a.rollout.id, a.status , COUNT(a.target)) FROM Action a WHERE a.rollout.id IN ?1 GROUP BY a.rollout.id,a.status") + @Query("SELECT NEW org.eclipse.hawkbit.repository.model.TotalTargetCountActionStatus( a.rollout.id, a.status , COUNT(a.target)) FROM JpaAction a WHERE a.rollout.id IN ?1 GROUP BY a.rollout.id,a.status") List getStatusCountByRolloutId(List rolloutId); /** @@ -362,7 +368,7 @@ public interface ActionRepository extends BaseEntityRepository, Jp * id of {@link Rollout} * @return list of objects with status and target count */ - @Query("SELECT NEW org.eclipse.hawkbit.repository.model.TotalTargetCountActionStatus( a.rollout.id, a.status , COUNT(a.target)) FROM Action a WHERE a.rollout.id = ?1 GROUP BY a.rollout.id,a.status") + @Query("SELECT NEW org.eclipse.hawkbit.repository.model.TotalTargetCountActionStatus( a.rollout.id, a.status , COUNT(a.target)) FROM JpaAction a WHERE a.rollout.id = ?1 GROUP BY a.rollout.id,a.status") List getStatusCountByRolloutId(Long rolloutId); /** @@ -373,7 +379,7 @@ public interface ActionRepository extends BaseEntityRepository, Jp * id of {@link RolloutGroup} * @return list of objects with status and target count */ - @Query("SELECT NEW org.eclipse.hawkbit.repository.model.TotalTargetCountActionStatus(a.rolloutGroup.id, a.status , COUNT(a.target)) FROM Action a WHERE a.rolloutGroup.id = ?1 GROUP BY a.rolloutGroup.id, a.status") + @Query("SELECT NEW org.eclipse.hawkbit.repository.model.TotalTargetCountActionStatus(a.rolloutGroup.id, a.status , COUNT(a.target)) FROM JpaAction a WHERE a.rolloutGroup.id = ?1 GROUP BY a.rolloutGroup.id, a.status") List getStatusCountByRolloutGroupId(Long rolloutGroupId); /** @@ -384,7 +390,7 @@ public interface ActionRepository extends BaseEntityRepository, Jp * list of id of {@link RolloutGroup} * @return list of objects with status and target count */ - @Query("SELECT NEW org.eclipse.hawkbit.repository.model.TotalTargetCountActionStatus(a.rolloutGroup.id, a.status , COUNT(a.target)) FROM Action a WHERE a.rolloutGroup.id IN ?1 GROUP BY a.rolloutGroup.id, a.status") + @Query("SELECT NEW org.eclipse.hawkbit.repository.model.TotalTargetCountActionStatus(a.rolloutGroup.id, a.status , COUNT(a.target)) FROM JpaAction a WHERE a.rolloutGroup.id IN ?1 GROUP BY a.rolloutGroup.id, a.status") List getStatusCountByRolloutGroupId(List rolloutGroupId); } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ActionStatusRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionStatusRepository.java similarity index 81% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ActionStatusRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionStatusRepository.java index 2a0e8cfb3..7a2c574df 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ActionStatusRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionStatusRepository.java @@ -6,8 +6,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; +import org.eclipse.hawkbit.repository.jpa.model.JpaAction; +import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.ActionStatus; @@ -25,7 +27,7 @@ import org.springframework.transaction.annotation.Transactional; */ @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface ActionStatusRepository - extends BaseEntityRepository, JpaSpecificationExecutor { + extends BaseEntityRepository, JpaSpecificationExecutor { /** * Counts {@link ActionStatus} entries of given {@link Action} in @@ -35,7 +37,7 @@ public interface ActionStatusRepository * to count status entries * @return number of actions in repository */ - Long countByAction(Action action); + Long countByAction(JpaAction action); /** * Counts {@link ActionStatus} entries of given {@link Action} with given @@ -47,7 +49,7 @@ public interface ActionStatusRepository * to filter for * @return number of actions in repository */ - Long countByActionAndStatus(Action action, Status status); + Long countByActionAndStatus(JpaAction action, Status status); /** * Retrieves all {@link ActionStatus} entries from repository of given @@ -59,7 +61,7 @@ public interface ActionStatusRepository * of the status entries * @return pages list of {@link ActionStatus} entries */ - Page findByAction(Pageable pageReq, Action action); + Page findByAction(Pageable pageReq, JpaAction action); /** * Finds all status updates for the defined action and target including @@ -74,6 +76,6 @@ public interface ActionStatusRepository * @return Page with found targets */ @EntityGraph(value = "ActionStatus.withMessages", type = EntityGraphType.LOAD) - Page getByAction(Pageable pageReq, Action action); + Page getByAction(Pageable pageReq, JpaAction action); } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/BaseEntityRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/BaseEntityRepository.java similarity index 85% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/BaseEntityRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/BaseEntityRepository.java index 16f80596d..0d9f72b37 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/BaseEntityRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/BaseEntityRepository.java @@ -6,10 +6,11 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import java.io.Serializable; +import org.eclipse.hawkbit.repository.jpa.model.AbstractJpaTenantAwareBaseEntity; import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.repository.NoRepositoryBean; @@ -27,7 +28,7 @@ import org.springframework.transaction.annotation.Transactional; */ @NoRepositoryBean @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) -public interface BaseEntityRepository +public interface BaseEntityRepository extends PagingAndSortingRepository { /** diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/CurrentTenantCacheKeyGenerator.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/CurrentTenantCacheKeyGenerator.java new file mode 100644 index 000000000..029246d2d --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/CurrentTenantCacheKeyGenerator.java @@ -0,0 +1,40 @@ +/** + * 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.jpa; + +import org.springframework.cache.interceptor.KeyGenerator; +import org.springframework.context.annotation.Bean; +import org.springframework.stereotype.Service; + +/** + * Defines the interfaces to register the {@link KeyGenerator} as bean which is + * used by spring caching framework to resolve the key-generator. The + * key-generator must registered as bean so spring can resolve the key-generator + * by its name. + * + * When using the {@link Service} annotation e.g. by {@link JpaSystemManagement} + * the bean registration must be declared by the interface due spring registers + * the bean by the implemented interfaces. So introduce a single interface for + * the {@link JpaSystemManagement} implementation to allow it to register the + * key-generator bean. + * + */ +@FunctionalInterface +public interface CurrentTenantCacheKeyGenerator { + + /** + * Bean declaration to register a {@code currentTenantKeyGenerator} bean + * which is used by the caching framework. + * + * @return the {@link KeyGenerator} to be used to cache the values of the + * current used tenant in the {@link JpaSystemManagement} + */ + @Bean + KeyGenerator currentTenantKeyGenerator(); +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DeploymentHelper.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DeploymentHelper.java new file mode 100644 index 000000000..f5d00862b --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DeploymentHelper.java @@ -0,0 +1,102 @@ +/** + * 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.jpa; + +import java.util.List; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; +import javax.validation.constraints.NotNull; + +import org.eclipse.hawkbit.repository.TargetManagement; +import org.eclipse.hawkbit.repository.jpa.model.JpaAction; +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.Status; +import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; + +/** + * Utility class for deployment related topics. + * + */ +public final class DeploymentHelper { + + private DeploymentHelper() { + // utility class + } + + /** + * Internal helper method used only inside service level. As a result is no + * additional security necessary. + * + * @param target + * to update + * @param status + * of the target + * @param setInstalledDate + * to set + * @param entityManager + * for the operation + * @param targetInfoRepository + * for the operation + * + * @return updated target + */ + static JpaTarget updateTargetInfo(@NotNull final JpaTarget target, @NotNull final TargetUpdateStatus status, + final boolean setInstalledDate, final TargetInfoRepository targetInfoRepository, + final EntityManager entityManager) { + final JpaTargetInfo ts = (JpaTargetInfo) target.getTargetInfo(); + ts.setUpdateStatus(status); + + if (setInstalledDate) { + ts.setInstallationDate(System.currentTimeMillis()); + } + targetInfoRepository.save(ts); + return entityManager.merge(target); + } + + /** + * This method is called, when cancellation has been successful. It sets the + * action to canceled, resets the meta data of the target and in case there + * is a new action this action is triggered. + * + * @param action + * the action which is set to canceled + * @param actionRepository + * for the operation + * @param targetManagement + * for the operation + * @param entityManager + * for the operation + * @param targetInfoRepository + * for the operation + */ + static void successCancellation(final JpaAction action, final ActionRepository actionRepository, + final TargetManagement targetManagement, final TargetInfoRepository targetInfoRepository, + final EntityManager entityManager) { + + // set action inactive + action.setActive(false); + action.setStatus(Status.CANCELED); + + final JpaTarget target = (JpaTarget) action.getTarget(); + final List nextActiveActions = actionRepository.findByTargetAndActiveOrderByIdAsc(target, true).stream() + .filter(a -> !a.getId().equals(action.getId())).collect(Collectors.toList()); + + if (nextActiveActions.isEmpty()) { + target.setAssignedDistributionSet(target.getTargetInfo().getInstalledDistributionSet()); + updateTargetInfo(target, TargetUpdateStatus.IN_SYNC, false, targetInfoRepository, entityManager); + } else { + target.setAssignedDistributionSet(nextActiveActions.get(0).getDistributionSet()); + } + targetManagement.updateTarget(target); + } + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetMetadataRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetMetadataRepository.java similarity index 70% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetMetadataRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetMetadataRepository.java index c042a32d0..7b8b1b20f 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetMetadataRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetMetadataRepository.java @@ -6,10 +6,11 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; +import org.eclipse.hawkbit.repository.jpa.model.DsMetadataCompositeKey; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetMetadata; import org.eclipse.hawkbit.repository.model.DistributionSetMetadata; -import org.eclipse.hawkbit.repository.model.DsMetadataCompositeKey; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.transaction.annotation.Isolation; @@ -17,13 +18,10 @@ import org.springframework.transaction.annotation.Transactional; /** * {@link DistributionSetMetadata} repository. - * - * - * */ @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface DistributionSetMetadataRepository - extends PagingAndSortingRepository, - JpaSpecificationExecutor { + extends PagingAndSortingRepository, + JpaSpecificationExecutor { } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetRepository.java similarity index 72% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetRepository.java index f2138bb2d..1ab6cbe08 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetRepository.java @@ -6,15 +6,17 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import java.util.Collection; import java.util.List; -import org.eclipse.hawkbit.repository.model.Action; +import org.eclipse.hawkbit.repository.jpa.model.JpaAction; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; import org.eclipse.hawkbit.repository.model.DistributionSet; -import org.eclipse.hawkbit.repository.model.DistributionSetTag; -import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.Tag; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; @@ -27,12 +29,10 @@ import org.springframework.transaction.annotation.Transactional; /** * {@link DistributionSet} repository. * - * - * */ @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface DistributionSetRepository - extends BaseEntityRepository, JpaSpecificationExecutor { + extends BaseEntityRepository, JpaSpecificationExecutor { /** * Finds {@link DistributionSet}s by assigned {@link Tag}. @@ -41,8 +41,8 @@ public interface DistributionSetRepository * to be found * @return list of found {@link DistributionSet}s */ - @Query(value = "Select Distinct ds from DistributionSet ds join ds.tags dst where dst = :tag") - List findByTag(@Param("tag") final DistributionSetTag tag); + @Query(value = "Select Distinct ds from JpaDistributionSet ds join ds.tags dst where dst = :tag") + List findByTag(@Param("tag") final JpaDistributionSetTag tag); /** * deletes the {@link DistributionSet}s with the given IDs. @@ -52,9 +52,12 @@ public interface DistributionSetRepository */ @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @Query("update DistributionSet d set d.deleted = 1 where d.id in :ids") + @Query("update JpaDistributionSet d set d.deleted = 1 where d.id in :ids") void deleteDistributionSet(@Param("ids") Long... ids); + @Override + List findAll(Iterable ids); + /** * deletes {@link DistributionSet}s by the given IDs. * @@ -65,7 +68,7 @@ public interface DistributionSetRepository @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) // Workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=349477 - @Query("DELETE FROM DistributionSet d WHERE d.id IN ?1") + @Query("DELETE FROM JpaDistributionSet d WHERE d.id IN ?1") int deleteByIdIn(Collection ids); /** @@ -76,7 +79,7 @@ public interface DistributionSetRepository * to search for * @return {@link List} of found {@link DistributionSet}s */ - List findByModules(SoftwareModule module); + List findByModules(JpaSoftwareModule module); /** * Finds {@link DistributionSet}s based on given ID if they are not assigned @@ -86,7 +89,7 @@ public interface DistributionSetRepository * to search for * @return */ - @Query("select ac.distributionSet.id from Action ac where ac.distributionSet.id in :ids") + @Query("select ac.distributionSet.id from JpaAction ac where ac.distributionSet.id in :ids") List findAssignedDistributionSetsById(@Param("ids") Long... ids); /** @@ -100,7 +103,7 @@ public interface DistributionSetRepository * @see org.springframework.data.repository.CrudRepository#save(java.lang.Iterable) */ @Override - List save(Iterable entities); + List save(Iterable entities); /** * Finds the distribution set for a specific action. @@ -109,8 +112,8 @@ public interface DistributionSetRepository * the action associated with the distribution set to find * @return the distribution set associated with the given action */ - @Query("select DISTINCT d from DistributionSet d join fetch d.modules m join d.actions a where a = :action") - DistributionSet findByAction(@Param("action") Action action); + @Query("select DISTINCT d from JpaDistributionSet d join fetch d.modules m join d.actions a where a = :action") + JpaDistributionSet findByAction(@Param("action") JpaAction action); /** * Counts {@link DistributionSet} instances of given type in the repository. @@ -119,7 +122,7 @@ public interface DistributionSetRepository * to search for * @return number of found {@link DistributionSet}s */ - long countByType(DistributionSetType type); + long countByType(JpaDistributionSetType type); /** * Counts {@link DistributionSet} with given diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetTagRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetTagRepository.java similarity index 79% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetTagRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetTagRepository.java index 8521a96b9..d13316b91 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetTagRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetTagRepository.java @@ -6,10 +6,11 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import java.util.List; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.repository.model.TargetTag; @@ -24,7 +25,7 @@ import org.springframework.transaction.annotation.Transactional; */ @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface DistributionSetTagRepository - extends BaseEntityRepository, JpaSpecificationExecutor { + extends BaseEntityRepository, JpaSpecificationExecutor { /** * deletes the {@link DistributionSet} with the given name. * @@ -43,7 +44,7 @@ public interface DistributionSetTagRepository * to filter on * @return the {@link DistributionSetTag} if found, otherwise null */ - DistributionSetTag findByNameEquals(final String tagName); + JpaDistributionSetTag findByNameEquals(final String tagName); /** * Returns all instances of the type. @@ -51,8 +52,8 @@ public interface DistributionSetTagRepository * @return all entities */ @Override - List findAll(); + List findAll(); @Override - List save(Iterable entities); + List save(Iterable entities); } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetTypeRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetTypeRepository.java similarity index 80% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetTypeRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetTypeRepository.java index 289dd6c09..82754d7f8 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetTypeRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetTypeRepository.java @@ -6,10 +6,11 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType; import org.eclipse.hawkbit.repository.model.DistributionSetType; -import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; @@ -23,7 +24,7 @@ import org.springframework.transaction.annotation.Transactional; */ @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface DistributionSetTypeRepository - extends BaseEntityRepository, JpaSpecificationExecutor { + extends BaseEntityRepository, JpaSpecificationExecutor { /** * @@ -34,7 +35,7 @@ public interface DistributionSetTypeRepository * false if undeleted ones * @return list of found {@link DistributionSetType}s */ - Page findByDeleted(Pageable pageable, boolean isDeleted); + Page findByDeleted(Pageable pageable, boolean isDeleted); /** * @param isDeleted @@ -54,5 +55,5 @@ public interface DistributionSetTypeRepository * @return the number of {@link DistributionSetType}s in the repository * assigned to the given software module type */ - Long countByElementsSmType(SoftwareModuleType softwareModuleType); + Long countByElementsSmType(JpaSoftwareModuleType softwareModuleType); } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/EclipseLinkTargetInfoRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/EclipseLinkTargetInfoRepository.java similarity index 85% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/EclipseLinkTargetInfoRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/EclipseLinkTargetInfoRepository.java index e37a51d6c..93b861092 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/EclipseLinkTargetInfoRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/EclipseLinkTargetInfoRepository.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import java.util.Collection; import java.util.List; @@ -14,7 +14,7 @@ import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; -import org.eclipse.hawkbit.repository.model.TargetInfo; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetInfo; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; @@ -40,7 +40,7 @@ public class EclipseLinkTargetInfoRepository implements TargetInfoRepository { @Transactional(isolation = Isolation.READ_UNCOMMITTED) public void setTargetUpdateStatus(final TargetUpdateStatus status, final List targets) { final Query query = entityManager.createQuery( - "update TargetInfo ti set ti.updateStatus = :status where ti.targetId in :targets and ti.updateStatus != :status"); + "update JpaTargetInfo ti set ti.updateStatus = :status where ti.targetId in :targets and ti.updateStatus != :status"); query.setParameter("targets", targets); query.setParameter("status", status); @@ -50,7 +50,7 @@ public class EclipseLinkTargetInfoRepository implements TargetInfoRepository { @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) @CacheEvict(value = { "targetStatus", "distributionUsageInstalled", "targetsLastPoll" }, allEntries = true) - public S save(final S entity) { + public S save(final S entity) { if (entity.isNew()) { entityManager.persist(entity); @@ -66,7 +66,7 @@ public class EclipseLinkTargetInfoRepository implements TargetInfoRepository { @CacheEvict(value = { "targetStatus", "distributionUsageInstalled", "targetsLastPoll" }, allEntries = true) public void deleteByTargetIdIn(final Collection targetIDs) { final javax.persistence.Query query = entityManager - .createQuery("DELETE FROM TargetInfo ti where ti.targetId IN :target"); + .createQuery("DELETE FROM JpaTargetInfo ti where ti.targetId IN :target"); query.setParameter("target", targetIDs); } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ExternalArtifactProviderRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ExternalArtifactProviderRepository.java similarity index 80% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ExternalArtifactProviderRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ExternalArtifactProviderRepository.java index d0802d242..039c4917e 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ExternalArtifactProviderRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ExternalArtifactProviderRepository.java @@ -6,8 +6,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; +import org.eclipse.hawkbit.repository.jpa.model.JpaExternalArtifactProvider; import org.eclipse.hawkbit.repository.model.ExternalArtifactProvider; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; @@ -17,6 +18,6 @@ import org.springframework.transaction.annotation.Transactional; * */ @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) -public interface ExternalArtifactProviderRepository extends BaseEntityRepository { +public interface ExternalArtifactProviderRepository extends BaseEntityRepository { } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ExternalArtifactRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ExternalArtifactRepository.java similarity index 81% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ExternalArtifactRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ExternalArtifactRepository.java index d20da8013..5845afbee 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ExternalArtifactRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ExternalArtifactRepository.java @@ -6,8 +6,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; +import org.eclipse.hawkbit.repository.jpa.model.JpaExternalArtifact; import org.eclipse.hawkbit.repository.model.ExternalArtifact; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -19,7 +20,7 @@ import org.springframework.transaction.annotation.Transactional; * */ @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) -public interface ExternalArtifactRepository extends BaseEntityRepository { +public interface ExternalArtifactRepository extends BaseEntityRepository { /** * Searches for external artifact for a base software module. @@ -31,6 +32,6 @@ public interface ExternalArtifactRepository extends BaseEntityRepository */ - Page findBySoftwareModuleId(Pageable pageReq, final Long swId); + Page findBySoftwareModuleId(Pageable pageReq, final Long swId); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaArtifactManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaArtifactManagement.java new file mode 100644 index 000000000..ea0e5c34f --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaArtifactManagement.java @@ -0,0 +1,301 @@ +/** + * 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.jpa; + +import java.io.InputStream; +import java.util.List; + +import org.eclipse.hawkbit.artifact.repository.ArtifactRepository; +import org.eclipse.hawkbit.artifact.repository.ArtifactStoreException; +import org.eclipse.hawkbit.artifact.repository.HashNotMatchException; +import org.eclipse.hawkbit.artifact.repository.model.DbArtifact; +import org.eclipse.hawkbit.artifact.repository.model.DbArtifactHash; +import org.eclipse.hawkbit.repository.ArtifactManagement; +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.jpa.model.JpaExternalArtifact; +import org.eclipse.hawkbit.repository.jpa.model.JpaExternalArtifactProvider; +import org.eclipse.hawkbit.repository.jpa.model.JpaLocalArtifact; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; +import org.eclipse.hawkbit.repository.jpa.specifications.SoftwareModuleSpecification; +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.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; + +/** + * JPA based {@link ArtifactManagement} implementation. + * + */ +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) +@Validated +@Service +public class JpaArtifactManagement implements ArtifactManagement { + + private static final Logger LOG = LoggerFactory.getLogger(JpaArtifactManagement.class); + + @Autowired + private LocalArtifactRepository localArtifactRepository; + + @Autowired + private ExternalArtifactRepository externalArtifactRepository; + + @Autowired + private SoftwareModuleRepository softwareModuleRepository; + + @Autowired + private ExternalArtifactProviderRepository externalArtifactProviderRepository; + + @Autowired + private ArtifactRepository artifactRepository; + + private static LocalArtifact checkForExistingArtifact(final String filename, final boolean overrideExisting, + final SoftwareModule softwareModule) { + if (softwareModule.getLocalArtifactByFilename(filename).isPresent()) { + if (overrideExisting) { + LOG.debug("overriding existing artifact with new filename {}", filename); + return softwareModule.getLocalArtifactByFilename(filename).get(); + } else { + throw new EntityAlreadyExistsException("File with that name already exists in the Software Module"); + } + } + return null; + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public ExternalArtifact createExternalArtifact(final ExternalArtifactProvider externalRepository, + final String urlSuffix, final Long moduleId) { + + final SoftwareModule module = getModuleAndThrowExceptionIfThatFails(moduleId); + return externalArtifactRepository.save(new JpaExternalArtifact(externalRepository, urlSuffix, module)); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public ExternalArtifactProvider createExternalArtifactProvider(final String name, final String description, + final String basePath, final String defaultUrlSuffix) { + return externalArtifactProviderRepository + .save(new JpaExternalArtifactProvider(name, description, basePath, defaultUrlSuffix)); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public LocalArtifact createLocalArtifact(final InputStream stream, final Long moduleId, final String filename, + final String providedMd5Sum, final String providedSha1Sum, final boolean overrideExisting, + final String contentType) { + DbArtifact result = null; + + final SoftwareModule softwareModule = getModuleAndThrowExceptionIfThatFails(moduleId); + + final LocalArtifact existing = checkForExistingArtifact(filename, overrideExisting, softwareModule); + + try { + result = artifactRepository.store(stream, filename, contentType, + new DbArtifactHash(providedSha1Sum, providedMd5Sum)); + } catch (final ArtifactStoreException e) { + throw new ArtifactUploadFailedException(e); + } catch (final HashNotMatchException e) { + if (e.getHashFunction().equals(HashNotMatchException.SHA1)) { + throw new InvalidSHA1HashException(e.getMessage(), e); + } else { + throw new InvalidMD5HashException(e.getMessage(), e); + } + } + if (result == null) { + return null; + } + + return storeArtifactMetadata(softwareModule, filename, result, existing); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public void deleteExternalArtifact(final Long id) { + final ExternalArtifact existing = externalArtifactRepository.findOne(id); + + if (null == existing) { + return; + } + + existing.getSoftwareModule().removeArtifact(existing); + softwareModuleRepository.save((JpaSoftwareModule) existing.getSoftwareModule()); + externalArtifactRepository.delete(id); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public void deleteLocalArtifact(final LocalArtifact existing) { + if (existing == null) { + return; + } + + boolean artifactIsOnlyUsedByOneSoftwareModule = true; + for (final LocalArtifact lArtifact : localArtifactRepository + .findByGridFsFileName(((JpaLocalArtifact) existing).getGridFsFileName())) { + if (!lArtifact.getSoftwareModule().isDeleted() + && Long.compare(lArtifact.getSoftwareModule().getId(), existing.getSoftwareModule().getId()) != 0) { + artifactIsOnlyUsedByOneSoftwareModule = false; + break; + } + } + + if (artifactIsOnlyUsedByOneSoftwareModule) { + try { + LOG.debug("deleting artifact from repository {}", ((JpaLocalArtifact) existing).getGridFsFileName()); + artifactRepository.deleteBySha1(((JpaLocalArtifact) existing).getGridFsFileName()); + } catch (final ArtifactStoreException e) { + throw new ArtifactDeleteFailedException(e); + } + } + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public void deleteLocalArtifact(final Long id) { + final JpaLocalArtifact existing = localArtifactRepository.findOne(id); + + if (null == existing) { + return; + } + + deleteLocalArtifact(existing); + + existing.getSoftwareModule().removeArtifact(existing); + softwareModuleRepository.save((JpaSoftwareModule) existing.getSoftwareModule()); + localArtifactRepository.delete(id); + } + + @Override + public Artifact findArtifact(final Long id) { + return localArtifactRepository.findOne(id); + } + + @Override + public List findByFilenameAndSoftwareModule(final String filename, final Long softwareModuleId) { + return localArtifactRepository.findByFilenameAndSoftwareModuleId(filename, softwareModuleId); + } + + @Override + public LocalArtifact findFirstLocalArtifactsBySHA1(final String sha1) { + return localArtifactRepository.findFirstByGridFsFileName(sha1); + } + + @Override + public List findLocalArtifactByFilename(final String filename) { + return localArtifactRepository.findByFilename(filename); + } + + @Override + public Page findLocalArtifactBySoftwareModule(final Pageable pageReq, final Long swId) { + return localArtifactRepository.findBySoftwareModuleId(pageReq, swId); + } + + @Override + public SoftwareModule findSoftwareModuleById(final Long id) { + + final Specification spec = SoftwareModuleSpecification.byId(id); + + return softwareModuleRepository.findOne(spec); + } + + @Override + public SoftwareModule findSoftwareModuleWithDetails(final Long id) { + final SoftwareModule result = findSoftwareModuleById(id); + if (result != null) { + result.getArtifacts().size(); + } + + return result; + } + + private SoftwareModule getModuleAndThrowExceptionIfThatFails(final Long moduleId) { + final SoftwareModule softwareModule = findSoftwareModuleWithDetails(moduleId); + + if (softwareModule == null) { + LOG.debug("no software module with ID {} exists", moduleId); + throw new EntityNotFoundException("Software Module: " + moduleId); + } + return softwareModule; + } + + @Override + public DbArtifact loadLocalArtifactBinary(final LocalArtifact artifact) { + final DbArtifact result = artifactRepository + .getArtifactBySha1(((JpaLocalArtifact) artifact).getGridFsFileName()); + if (result == null) { + throw new GridFSDBFileNotFoundException(((JpaLocalArtifact) artifact).getGridFsFileName()); + } + + return result; + } + + private LocalArtifact storeArtifactMetadata(final SoftwareModule softwareModule, final String providedFilename, + final DbArtifact result, final LocalArtifact existing) { + JpaLocalArtifact artifact = (JpaLocalArtifact) existing; + if (existing == null) { + artifact = new JpaLocalArtifact(result.getHashes().getSha1(), providedFilename, softwareModule); + } + artifact.setMd5Hash(result.getHashes().getMd5()); + artifact.setSha1Hash(result.getHashes().getSha1()); + artifact.setSize(result.getSize()); + + LOG.debug("storing new artifact into repository {}", artifact); + return localArtifactRepository.save(artifact); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public LocalArtifact createLocalArtifact(final InputStream inputStream, final Long moduleId, final String filename, + final boolean overrideExisting) { + return createLocalArtifact(inputStream, moduleId, filename, null, null, overrideExisting, null); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public LocalArtifact createLocalArtifact(final InputStream inputStream, final Long moduleId, final String filename, + final boolean overrideExisting, final String contentType) { + return createLocalArtifact(inputStream, moduleId, filename, null, null, overrideExisting, contentType); + } + + @Override + public Long countLocalArtifactsAll() { + return localArtifactRepository.count(); + } + + @Override + public Long countExternalArtifactsAll() { + return externalArtifactRepository.count(); + } +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaControllerManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaControllerManagement.java new file mode 100644 index 000000000..77b71e661 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaControllerManagement.java @@ -0,0 +1,454 @@ +/** + * 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.jpa; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; +import javax.validation.constraints.NotNull; + +import org.eclipse.hawkbit.repository.ControllerManagement; +import org.eclipse.hawkbit.repository.RepositoryConstants; +import org.eclipse.hawkbit.repository.TargetManagement; +import org.eclipse.hawkbit.repository.TenantConfigurationManagement; +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.jpa.cache.CacheWriteNotify; +import org.eclipse.hawkbit.repository.jpa.model.JpaAction; +import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus; +import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus_; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetInfo; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget_; +import org.eclipse.hawkbit.repository.jpa.specifications.ActionSpecifications; +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.repository.model.TenantConfiguration; +import org.eclipse.hawkbit.security.HawkbitSecurityProperties; +import org.eclipse.hawkbit.security.SystemSecurityContext; +import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; + +/** + * JPA based {@link ControllerManagement} implementation. + * + */ +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) +@Validated +@Service +public class JpaControllerManagement implements ControllerManagement { + private static final Logger LOG = LoggerFactory.getLogger(ControllerManagement.class); + private static final Logger LOG_DOS = LoggerFactory.getLogger("server-security.dos"); + + @Autowired + private EntityManager entityManager; + + @Autowired + private ActionRepository actionRepository; + + @Autowired + private TargetRepository targetRepository; + + @Autowired + private TargetManagement targetManagement; + + @Autowired + private TargetInfoRepository targetInfoRepository; + + @Autowired + private SoftwareModuleRepository softwareModuleRepository; + + @Autowired + private ActionStatusRepository actionStatusRepository; + + @Autowired + private HawkbitSecurityProperties securityProperties; + + @Autowired + private TenantConfigurationRepository tenantConfigurationRepository; + + @Autowired + private TenantConfigurationManagement tenantConfigurationManagement; + + @Autowired + private CacheWriteNotify cacheWriteNotify; + + @Autowired + private SystemSecurityContext systemSecurityContext; + + @Override + public String getPollingTime() { + final TenantConfigurationKey configurationKey = TenantConfigurationKey.POLLING_TIME_INTERVAL; + final Class propertyType = String.class; + JpaTenantConfigurationManagement.validateTenantConfigurationDataType(configurationKey, propertyType); + final TenantConfiguration tenantConfiguration = tenantConfigurationRepository + .findByKey(configurationKey.getKeyName()); + + return systemSecurityContext.runAsSystem(() -> tenantConfigurationManagement + .buildTenantConfigurationValueByKey(configurationKey, propertyType, tenantConfiguration).getValue()); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public Target updateLastTargetQuery(final String controllerId, final URI address) { + final Target target = targetRepository.findByControllerId(controllerId); + if (target == null) { + throw new EntityNotFoundException(controllerId); + } + + return updateLastTargetQuery(target.getTargetInfo(), address).getTarget(); + } + + @Override + public Action getActionForDownloadByTargetAndSoftwareModule(final String controllerId, + final SoftwareModule module) { + final List action = actionRepository.findActionByTargetAndSoftwareModule(controllerId, + (JpaSoftwareModule) module); + + if (action.isEmpty() || action.get(0).isCancelingOrCanceled()) { + throw new EntityNotFoundException( + "No assigment found for module " + module.getId() + " to target " + controllerId); + } + + return action.get(0); + } + + @Override + public boolean hasTargetArtifactAssigned(final String controllerId, final LocalArtifact localArtifact) { + final Target target = targetRepository.findByControllerId(controllerId); + if (target == null) { + return false; + } + return actionRepository.count(ActionSpecifications.hasTargetAssignedArtifact(target, localArtifact)) > 0; + } + + @Override + public List findActionByTargetAndActive(final Target target) { + return actionRepository.findByTargetAndActiveOrderByIdAsc((JpaTarget) target, true); + } + + @Override + public List findSoftwareModulesByDistributionSet(final DistributionSet distributionSet) { + return new ArrayList<>(softwareModuleRepository.findByAssignedTo((JpaDistributionSet) distributionSet)); + } + + @Override + public Action findActionWithDetails(final Long actionId) { + return actionRepository.findById(actionId); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public Target findOrRegisterTargetIfItDoesNotexist(final String controllerId, final URI address) { + final Specification spec = (targetRoot, query, cb) -> cb + .equal(targetRoot.get(JpaTarget_.controllerId), controllerId); + + JpaTarget target = targetRepository.findOne(spec); + + if (target == null) { + target = new JpaTarget(controllerId); + target.setDescription("Plug and Play target: " + controllerId); + target.setName(controllerId); + return targetManagement.createTarget(target, TargetUpdateStatus.REGISTERED, System.currentTimeMillis(), + address); + } + + return updateLastTargetQuery(target.getTargetInfo(), address).getTarget(); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public TargetInfo updateTargetStatus(final TargetInfo targetInfo, final TargetUpdateStatus status, + final Long lastTargetQuery, final URI address) { + final JpaTargetInfo mtargetInfo = (JpaTargetInfo) entityManager.merge(targetInfo); + if (status != null) { + mtargetInfo.setUpdateStatus(status); + } + if (lastTargetQuery != null) { + mtargetInfo.setLastTargetQuery(lastTargetQuery); + } + if (address != null) { + mtargetInfo.setAddress(address.toString()); + } + return targetInfoRepository.save(mtargetInfo); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public Action addCancelActionStatus(final ActionStatus actionStatus) { + final JpaAction action = (JpaAction) actionStatus.getAction(); + + checkForToManyStatusEntries(action); + action.setStatus(actionStatus.getStatus()); + + switch (actionStatus.getStatus()) { + case WARNING: + case ERROR: + case RUNNING: + break; + case CANCELED: + case FINISHED: + handleFinishedCancelation(actionStatus, action); + break; + case RETRIEVED: + actionStatus.addMessage(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Cancellation request retrieved."); + break; + default: + // do nothing + } + actionRepository.save(action); + actionStatusRepository.save((JpaActionStatus) actionStatus); + + return action; + } + + private void handleFinishedCancelation(final ActionStatus actionStatus, final JpaAction action) { + // in case of successful cancellation we also report the success at + // the canceled action itself. + actionStatus.addMessage( + RepositoryConstants.SERVER_MESSAGE_PREFIX + "Cancellation completion is finished sucessfully."); + DeploymentHelper.successCancellation(action, actionRepository, targetManagement, targetInfoRepository, + entityManager); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public Action addUpdateActionStatus(@NotNull final ActionStatus actionStatus) { + final JpaAction action = (JpaAction) actionStatus.getAction(); + + if (!action.isActive()) { + LOG.debug("Update of actionStatus {} for action {} not possible since action not active anymore.", + actionStatus.getId(), action.getId()); + return action; + } + return handleAddUpdateActionStatus((JpaActionStatus) actionStatus, action); + } + + /** + * Sets {@link TargetUpdateStatus} based on given {@link ActionStatus}. + * + * @param actionStatus + * @param action + * @return + */ + private Action handleAddUpdateActionStatus(final JpaActionStatus actionStatus, final JpaAction action) { + LOG.debug("addUpdateActionStatus for action {}", action.getId()); + + final JpaAction mergedAction = entityManager.merge(action); + JpaTarget mergedTarget = (JpaTarget) mergedAction.getTarget(); + // check for a potential DOS attack + checkForToManyStatusEntries(action); + + switch (actionStatus.getStatus()) { + case ERROR: + mergedTarget = DeploymentHelper.updateTargetInfo(mergedTarget, TargetUpdateStatus.ERROR, false, + targetInfoRepository, entityManager); + handleErrorOnAction(mergedAction, mergedTarget); + break; + case FINISHED: + handleFinishedAndStoreInTargetStatus(mergedTarget, mergedAction); + break; + case CANCELED: + case WARNING: + case RUNNING: + DeploymentHelper.updateTargetInfo(mergedTarget, TargetUpdateStatus.PENDING, false, targetInfoRepository, + entityManager); + break; + default: + break; + } + + actionStatusRepository.save(actionStatus); + + LOG.debug("addUpdateActionStatus {} for target {} is finished.", action.getId(), mergedTarget.getId()); + + return actionRepository.save(mergedAction); + } + + private void handleErrorOnAction(final JpaAction mergedAction, final JpaTarget mergedTarget) { + mergedAction.setActive(false); + mergedAction.setStatus(Status.ERROR); + mergedTarget.setAssignedDistributionSet(null); + targetManagement.updateTarget(mergedTarget); + } + + private void checkForToManyStatusEntries(final JpaAction action) { + if (securityProperties.getDos().getMaxStatusEntriesPerAction() > 0) { + + final Long statusCount = actionStatusRepository.countByAction(action); + + if (statusCount >= securityProperties.getDos().getMaxStatusEntriesPerAction()) { + LOG_DOS.error( + "Potential denial of service (DOS) attack identfied. More status entries in the system than permitted ({})!", + securityProperties.getDos().getMaxStatusEntriesPerAction()); + throw new ToManyStatusEntriesException( + String.valueOf(securityProperties.getDos().getMaxStatusEntriesPerAction())); + } + } + } + + private void handleFinishedAndStoreInTargetStatus(final JpaTarget target, final JpaAction action) { + action.setActive(false); + action.setStatus(Status.FINISHED); + final JpaTargetInfo targetInfo = (JpaTargetInfo) target.getTargetInfo(); + final JpaDistributionSet ds = (JpaDistributionSet) entityManager.merge(action.getDistributionSet()); + targetInfo.setInstalledDistributionSet(ds); + if (target.getAssignedDistributionSet() != null && targetInfo.getInstalledDistributionSet() != null && target + .getAssignedDistributionSet().getId().equals(targetInfo.getInstalledDistributionSet().getId())) { + targetInfo.setUpdateStatus(TargetUpdateStatus.IN_SYNC); + targetInfo.setInstallationDate(System.currentTimeMillis()); + } else { + targetInfo.setUpdateStatus(TargetUpdateStatus.PENDING); + targetInfo.setInstallationDate(System.currentTimeMillis()); + } + targetInfoRepository.save(targetInfo); + entityManager.detach(ds); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public Target updateControllerAttributes(final String controllerId, final Map data) { + final JpaTarget target = targetRepository.findByControllerId(controllerId); + + if (target == null) { + throw new EntityNotFoundException(controllerId); + } + + final JpaTargetInfo targetInfo = (JpaTargetInfo) target.getTargetInfo(); + targetInfo.getControllerAttributes().putAll(data); + + if (targetInfo.getControllerAttributes().size() > securityProperties.getDos() + .getMaxAttributeEntriesPerTarget()) { + LOG_DOS.info("Target tries to insert more than the allowed number of entries ({}). DOS attack anticipated!", + securityProperties.getDos().getMaxAttributeEntriesPerTarget()); + throw new ToManyAttributeEntriesException( + String.valueOf(securityProperties.getDos().getMaxAttributeEntriesPerTarget())); + } + + targetInfo.setLastTargetQuery(System.currentTimeMillis()); + targetInfo.setRequestControllerAttributes(false); + return targetRepository.save(target); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public Action registerRetrieved(final Action action, final String message) { + return handleRegisterRetrieved((JpaAction) action, message); + } + + /** + * 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 updated action in case the status has been changed to + * {@link Status#RETRIEVED} + */ + private Action handleRegisterRetrieved(final JpaAction action, final String message) { + // do a manual query with CriteriaBuilder to avoid unnecessary field + // queries and an extra + // count query made by spring-data when using pageable requests, we + // don't need an extra count + // query, we just want to check if the last action status is a retrieved + // or not. + final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); + final CriteriaQuery queryActionStatus = cb.createQuery(Object[].class); + final Root actionStatusRoot = queryActionStatus.from(JpaActionStatus.class); + final CriteriaQuery query = queryActionStatus + .multiselect(actionStatusRoot.get(JpaActionStatus_.id), actionStatusRoot.get(JpaActionStatus_.status)) + .where(cb.equal(actionStatusRoot.get(JpaActionStatus_.action), action)) + .orderBy(cb.desc(actionStatusRoot.get(JpaActionStatus_.id))); + final List resultList = entityManager.createQuery(query).setFirstResult(0).setMaxResults(1) + .getResultList(); + + // if the latest status is not in retrieve state then we add a retrieved + // state again, we want + // to document a deployment retrieved status and a cancel retrieved + // status, but multiple + // retrieves after the other we don't want to store to protect to + // overflood action status in + // case controller retrieves a action multiple times. + if (resultList.isEmpty() || !Status.RETRIEVED.equals(resultList.get(0)[1])) { + // document that the status has been retrieved + actionStatusRepository + .save(new JpaActionStatus(action, Status.RETRIEVED, System.currentTimeMillis(), message)); + + // don't change the action status itself in case the action is in + // canceling state otherwise + // we modify the action status and the controller won't get the + // cancel job anymore. + if (!action.isCancelingOrCanceled()) { + final JpaAction actionMerge = entityManager.merge(action); + actionMerge.setStatus(Status.RETRIEVED); + return actionRepository.save(actionMerge); + } + } + return action; + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public void addInformationalActionStatus(final ActionStatus statusMessage) { + actionStatusRepository.save((JpaActionStatus) statusMessage); + } + + @Override + public String getSecurityTokenByControllerId(final String controllerId) { + final Target target = targetRepository.findByControllerId(controllerId); + return target != null ? target.getSecurityToken() : null; + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public TargetInfo updateLastTargetQuery(final TargetInfo target, final URI address) { + return updateTargetStatus(target, null, System.currentTimeMillis(), address); + } + + @Override + public void downloadProgressPercent(final long statusId, final int progressPercent) { + cacheWriteNotify.downloadProgressPercent(statusId, progressPercent); + } + +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDeploymentManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDeploymentManagement.java new file mode 100644 index 000000000..4739f16a7 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDeploymentManagement.java @@ -0,0 +1,714 @@ +/** + * 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.jpa; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Join; +import javax.persistence.criteria.JoinType; +import javax.persistence.criteria.ListJoin; +import javax.persistence.criteria.Root; +import javax.validation.constraints.NotNull; + +import org.eclipse.hawkbit.eventbus.event.CancelTargetAssignmentEvent; +import org.eclipse.hawkbit.repository.ActionFields; +import org.eclipse.hawkbit.repository.DeploymentManagement; +import org.eclipse.hawkbit.repository.DistributionSetAssignmentResult; +import org.eclipse.hawkbit.repository.TargetManagement; +import org.eclipse.hawkbit.repository.eventbus.event.TargetAssignDistributionSetEvent; +import org.eclipse.hawkbit.repository.eventbus.event.TargetInfoUpdateEvent; +import org.eclipse.hawkbit.repository.exception.CancelActionNotAllowedException; +import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; +import org.eclipse.hawkbit.repository.exception.ForceQuitActionNotAllowedException; +import org.eclipse.hawkbit.repository.exception.IncompleteDistributionSetException; +import org.eclipse.hawkbit.repository.jpa.configuration.Constants; +import org.eclipse.hawkbit.repository.jpa.executor.AfterTransactionCommitExecutor; +import org.eclipse.hawkbit.repository.jpa.model.JpaAction; +import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus; +import org.eclipse.hawkbit.repository.jpa.model.JpaActionWithStatusCount; +import org.eclipse.hawkbit.repository.jpa.model.JpaAction_; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet_; +import org.eclipse.hawkbit.repository.jpa.model.JpaRollout; +import org.eclipse.hawkbit.repository.jpa.model.JpaRolloutGroup; +import org.eclipse.hawkbit.repository.jpa.model.JpaRollout_; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetInfo; +import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility; +import org.eclipse.hawkbit.repository.jpa.specifications.TargetSpecifications; +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.SoftwareModule; +import org.eclipse.hawkbit.repository.model.SoftwareModuleType; +import org.eclipse.hawkbit.repository.model.Target; +import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; +import org.eclipse.hawkbit.repository.model.TargetWithActionType; +import org.eclipse.hawkbit.security.SystemSecurityContext; +import org.hibernate.validator.constraints.NotEmpty; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.data.domain.AuditorAware; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Slice; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; + +import com.google.common.collect.Lists; +import com.google.common.eventbus.EventBus; + +/** + * JPA implementation for {@link DeploymentManagement}. + * + */ +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) +@Validated +@Service +public class JpaDeploymentManagement implements DeploymentManagement { + private static final Logger LOG = LoggerFactory.getLogger(JpaDeploymentManagement.class); + + @Autowired + private EntityManager entityManager; + + @Autowired + private ActionRepository actionRepository; + + @Autowired + private DistributionSetRepository distributoinSetRepository; + + @Autowired + private SoftwareModuleRepository softwareModuleRepository; + + @Autowired + private TargetRepository targetRepository; + + @Autowired + private ActionStatusRepository actionStatusRepository; + + @Autowired + private TargetManagement targetManagement; + + @Autowired + private TargetInfoRepository targetInfoRepository; + + @Autowired + private AuditorAware auditorProvider; + + @Autowired + private EventBus eventBus; + + @Autowired + private AfterTransactionCommitExecutor afterCommit; + + @Autowired + private SystemSecurityContext systemSecurityContext; + + @Override + @Transactional(isolation = Isolation.READ_COMMITTED) + @Modifying + @CacheEvict(value = { "distributionUsageAssigned" }, allEntries = true) + public DistributionSetAssignmentResult assignDistributionSet(final DistributionSet pset, + final List targets) { + + return assignDistributionSetByTargetId((JpaDistributionSet) pset, + targets.stream().map(target -> target.getControllerId()).collect(Collectors.toList()), + ActionType.FORCED, org.eclipse.hawkbit.repository.model.RepositoryModelConstants.NO_FORCE_TIME); + + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_COMMITTED) + @CacheEvict(value = { "distributionUsageAssigned" }, allEntries = true) + public DistributionSetAssignmentResult assignDistributionSet(final Long dsID, final String... targetIDs) { + return assignDistributionSet(dsID, ActionType.FORCED, + org.eclipse.hawkbit.repository.model.RepositoryModelConstants.NO_FORCE_TIME, targetIDs); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + @CacheEvict(value = { "distributionUsageAssigned" }, allEntries = true) + // Exception squid:S2095: see + // https://jira.sonarsource.com/browse/SONARJAVA-1478 + @SuppressWarnings({ "squid:S2095" }) + public DistributionSetAssignmentResult assignDistributionSet(final Long dsID, final ActionType actionType, + final long forcedTimestamp, final String... targetIDs) { + return assignDistributionSet(dsID, Arrays.stream(targetIDs) + .map(t -> new TargetWithActionType(t, actionType, forcedTimestamp)).collect(Collectors.toList())); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_COMMITTED) + @CacheEvict(value = { "distributionUsageAssigned" }, allEntries = true) + public DistributionSetAssignmentResult assignDistributionSet(final Long dsID, + final Collection targets) { + final JpaDistributionSet set = distributoinSetRepository.findOne(dsID); + if (set == null) { + throw new EntityNotFoundException( + String.format("no %s with id %d found", DistributionSet.class.getSimpleName(), dsID)); + } + + return assignDistributionSetToTargets(set, targets, null, null); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_COMMITTED) + @CacheEvict(value = { "distributionUsageAssigned" }, allEntries = true) + public DistributionSetAssignmentResult assignDistributionSet(final Long dsID, + final Collection targets, final Rollout rollout, final RolloutGroup rolloutGroup) { + final JpaDistributionSet set = distributoinSetRepository.findOne(dsID); + if (set == null) { + throw new EntityNotFoundException( + String.format("no %s with id %d found", DistributionSet.class.getSimpleName(), dsID)); + } + + return assignDistributionSetToTargets(set, targets, (JpaRollout) rollout, (JpaRolloutGroup) rolloutGroup); + } + + /** + * 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}. + */ + private DistributionSetAssignmentResult assignDistributionSetToTargets(@NotNull final JpaDistributionSet set, + final Collection targetsWithActionType, final JpaRollout rollout, + final JpaRolloutGroup rolloutGroup) { + + if (!set.isComplete()) { + throw new IncompleteDistributionSetException( + "Distribution set of type " + set.getType().getKey() + " is incomplete: " + set.getId()); + } + + final List controllerIDs = targetsWithActionType.stream().map(TargetWithActionType::getTargetId) + .collect(Collectors.toList()); + + LOG.debug("assignDistribution({}) to {} targets", set, controllerIDs.size()); + + final Map targetsWithActionMap = targetsWithActionType.stream() + .collect(Collectors.toMap(TargetWithActionType::getTargetId, Function.identity())); + + // split tIDs length into max entries in-statement because many database + // have constraint of max entries in in-statements e.g. Oracle with + // maximum 1000 elements, so we need to split the entries here and + // execute multiple statements we take the target only into account if + // the requested operation is no duplicate of a previous one + final List targets = Lists.partition(controllerIDs, Constants.MAX_ENTRIES_IN_STATEMENT).stream() + .map(ids -> targetRepository + .findAll(TargetSpecifications.hasControllerIdAndAssignedDistributionSetIdNot(ids, set.getId()))) + .flatMap(t -> t.stream()).collect(Collectors.toList()); + + if (targets.isEmpty()) { + // detaching as it is not necessary to persist the set itself + entityManager.detach(set); + // return with nothing as all targets had the DS already assigned + return new DistributionSetAssignmentResult(Collections.emptyList(), 0, targetsWithActionType.size(), + Collections.emptyList(), targetManagement); + } + + final List> targetIds = Lists.partition( + targets.stream().map(Target::getId).collect(Collectors.toList()), Constants.MAX_ENTRIES_IN_STATEMENT); + + // override all active actions and set them into canceling state, we + // need to remember which one we have been switched to canceling state + // because for targets which we have changed to canceling we don't want + // to publish the new action update event. + final Set targetIdsCancellList = new HashSet<>(); + targetIds.forEach(ids -> targetIdsCancellList.addAll(overrideObsoleteUpdateActions(ids))); + + // cancel all scheduled actions which are in-active, these actions were + // not active before and the manual assignment which has been done + // cancels the + targetIds.forEach(tIds -> actionRepository.switchStatus(Status.CANCELED, tIds, false, Status.SCHEDULED)); + + // set assigned distribution set and TargetUpdateStatus + final String currentUser; + if (auditorProvider != null) { + currentUser = auditorProvider.getCurrentAuditor(); + } else { + currentUser = null; + } + + targetIds.forEach(tIds -> targetRepository.setAssignedDistributionSet(set, System.currentTimeMillis(), + currentUser, tIds)); + targetIds.forEach(tIds -> targetInfoRepository.setTargetUpdateStatus(TargetUpdateStatus.PENDING, tIds)); + final Map targetIdsToActions = actionRepository + .save(targets.stream().map(t -> createTargetAction(targetsWithActionMap, t, set, rollout, rolloutGroup)) + .collect(Collectors.toList())) + .stream().collect(Collectors.toMap(a -> a.getTarget().getControllerId(), Function.identity())); + + // create initial action status when action is created so we remember + // the initial running status because we will change the status + // of the action itself and with this action status we have a nicer + // action history. + targetIdsToActions.values().forEach(action -> { + final JpaActionStatus actionStatus = new JpaActionStatus(); + actionStatus.setAction(action); + actionStatus.setOccurredAt(action.getCreatedAt()); + actionStatus.setStatus(Status.RUNNING); + actionStatusRepository.save(actionStatus); + }); + + // flush to get action IDs + entityManager.flush(); + // collect updated target and actions IDs in order to return them + final DistributionSetAssignmentResult result = new DistributionSetAssignmentResult( + targets.stream().map(target -> target.getControllerId()).collect(Collectors.toList()), targets.size(), + controllerIDs.size() - targets.size(), + targetIdsToActions.values().stream().map(Action::getId).collect(Collectors.toList()), targetManagement); + + LOG.debug("assignDistribution({}) finished {}", set, result); + + final List softwareModules = softwareModuleRepository.findByAssignedTo(set); + + // detaching as it is not necessary to persist the set itself + entityManager.detach(set); + + sendDistributionSetAssignmentEvent(targets, targetIdsCancellList, targetIdsToActions, softwareModules); + + return result; + } + + private void sendDistributionSetAssignmentEvent(final List targets, final Set targetIdsCancellList, + final Map targetIdsToActions, final List softwareModules) { + targets.stream().filter(t -> !!!targetIdsCancellList.contains(t.getId())) + .forEach(t -> assignDistributionSetEvent(t, targetIdsToActions.get(t.getControllerId()).getId(), + softwareModules)); + } + + private static JpaAction createTargetAction(final Map targetsWithActionMap, + final JpaTarget target, final JpaDistributionSet set, final JpaRollout rollout, + final JpaRolloutGroup rolloutGroup) { + final JpaAction actionForTarget = new JpaAction(); + final TargetWithActionType targetWithActionType = targetsWithActionMap.get(target.getControllerId()); + actionForTarget.setActionType(targetWithActionType.getActionType()); + actionForTarget.setForcedTime(targetWithActionType.getForceTime()); + actionForTarget.setActive(true); + actionForTarget.setStatus(Status.RUNNING); + actionForTarget.setTarget(target); + actionForTarget.setDistributionSet(set); + actionForTarget.setRollout(rollout); + actionForTarget.setRolloutGroup(rolloutGroup); + return actionForTarget; + } + + /** + * Sends the {@link TargetAssignDistributionSetEvent} for a specific target + * to the {@link EventBus}. + * + * @param target + * the Target which has been assigned to a distribution set + * @param actionId + * the action id of the assignment + * @param softwareModules + * the software modules which have been assigned + */ + private void assignDistributionSetEvent(final JpaTarget target, final Long actionId, + final List modules) { + ((JpaTargetInfo) target.getTargetInfo()).setUpdateStatus(TargetUpdateStatus.PENDING); + final String targetSecurityToken = systemSecurityContext.runAsSystem(() -> target.getSecurityToken()); + @SuppressWarnings({ "unchecked", "rawtypes" }) + final Collection softwareModules = (Collection) modules; + afterCommit.afterCommit(() -> { + eventBus.post(new TargetInfoUpdateEvent(target.getTargetInfo())); + eventBus.post(new TargetAssignDistributionSetEvent(target.getOptLockRevision(), target.getTenant(), + target.getControllerId(), actionId, softwareModules, target.getTargetInfo().getAddress(), + targetSecurityToken)); + }); + } + + /** + * Removes {@link UpdateAction}s that are no longer necessary and sends + * cancellations to the controller. + * + * @param myTarget + * to override {@link UpdateAction}s + */ + private Set overrideObsoleteUpdateActions(final List targetsIds) { + + final Set cancelledTargetIds = new HashSet<>(); + + // Figure out if there are potential target/action combinations that + // need to be considered + // for cancelation + final List activeActions = actionRepository + .findByActiveAndTargetIdInAndActionStatusNotEqualToAndDistributionSetRequiredMigrationStep(targetsIds, + Action.Status.CANCELING); + activeActions.forEach(action -> { + action.setStatus(Status.CANCELING); + // document that the status has been retrieved + + actionStatusRepository.save(new JpaActionStatus(action, Status.CANCELING, System.currentTimeMillis(), + "manual cancelation requested")); + + cancelAssignDistributionSetEvent(action.getTarget(), action.getId()); + + cancelledTargetIds.add(action.getTarget().getId()); + }); + + actionRepository.save(activeActions); + + return cancelledTargetIds; + + } + + private DistributionSetAssignmentResult assignDistributionSetByTargetId(@NotNull final JpaDistributionSet set, + @NotEmpty final List tIDs, final ActionType actionType, final long forcedTime) { + + return assignDistributionSetToTargets(set, tIDs.stream() + .map(t -> new TargetWithActionType(t, actionType, forcedTime)).collect(Collectors.toList()), null, + null); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_COMMITTED) + public Action cancelAction(final Action action, final Target target) { + LOG.debug("cancelAction({}, {})", action, target); + if (action.isCancelingOrCanceled()) { + throw new CancelActionNotAllowedException("Actions in canceling or canceled state cannot be canceled"); + } + final JpaAction myAction = (JpaAction) entityManager.merge(action); + + if (myAction.isActive()) { + LOG.debug("action ({}) was still active. Change to {}.", action, Status.CANCELING); + myAction.setStatus(Status.CANCELING); + + // document that the status has been retrieved + actionStatusRepository.save(new JpaActionStatus(myAction, Status.CANCELING, System.currentTimeMillis(), + "manual cancelation requested")); + final Action saveAction = actionRepository.save(myAction); + cancelAssignDistributionSetEvent(target, myAction.getId()); + + return saveAction; + } else { + throw new CancelActionNotAllowedException( + "Action [id: " + action.getId() + "] is not active and cannot be canceled"); + } + } + + /** + * Sends the {@link CancelTargetAssignmentEvent} for a specific target to + * the {@link EventBus}. + * + * @param target + * the Target which has been assigned to a distribution set + * @param actionId + * the action id of the assignment + */ + private void cancelAssignDistributionSetEvent(final Target target, final Long actionId) { + afterCommit.afterCommit(() -> eventBus.post(new CancelTargetAssignmentEvent(target.getOptLockRevision(), + target.getTenant(), target.getControllerId(), actionId, target.getTargetInfo().getAddress()))); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_COMMITTED) + public Action forceQuitAction(final Action action) { + final JpaAction mergedAction = (JpaAction) entityManager.merge(action); + + if (!mergedAction.isCancelingOrCanceled()) { + throw new ForceQuitActionNotAllowedException( + "Action [id: " + action.getId() + "] is not canceled yet and cannot be force quit"); + } + + if (!mergedAction.isActive()) { + throw new ForceQuitActionNotAllowedException( + "Action [id: " + action.getId() + "] is not active and cannot be force quit"); + } + + LOG.warn("action ({}) was still activ and has been force quite.", action); + + // document that the status has been retrieved + actionStatusRepository.save(new JpaActionStatus(mergedAction, Status.CANCELED, System.currentTimeMillis(), + "A force quit has been performed.")); + + DeploymentHelper.successCancellation(mergedAction, actionRepository, targetManagement, targetInfoRepository, + entityManager); + + return actionRepository.save(mergedAction); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_COMMITTED) + public void createScheduledAction(final Collection targets, final DistributionSet distributionSet, + final ActionType actionType, final Long forcedTime, final Rollout rollout, + final RolloutGroup rolloutGroup) { + // cancel all current scheduled actions for this target. E.g. an action + // is already scheduled and a next action is created then cancel the + // current scheduled action to cancel. E.g. a new scheduled action is + // created. + final List targetIds = targets.stream().map(t -> t.getId()).collect(Collectors.toList()); + actionRepository.switchStatus(Action.Status.CANCELED, targetIds, false, Action.Status.SCHEDULED); + targets.forEach(target -> { + final JpaAction action = new JpaAction(); + action.setTarget(target); + action.setActive(false); + action.setDistributionSet(distributionSet); + action.setActionType(actionType); + action.setForcedTime(forcedTime); + action.setStatus(Status.SCHEDULED); + action.setRollout(rollout); + action.setRolloutGroup(rolloutGroup); + actionRepository.save(action); + }); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_COMMITTED) + public Action startScheduledAction(final Action action) { + + final JpaAction mergedAction = (JpaAction) entityManager.merge(action); + final JpaTarget mergedTarget = (JpaTarget) entityManager.merge(action.getTarget()); + + // check if we need to override running update actions + final Set overrideObsoleteUpdateActions = overrideObsoleteUpdateActions( + Collections.singletonList(action.getTarget().getId())); + + final boolean hasDistributionSetAlreadyAssigned = targetRepository + .count(TargetSpecifications.hasControllerIdAndAssignedDistributionSetIdNot( + Collections.singletonList(mergedTarget.getControllerId()), + action.getDistributionSet().getId())) == 0; + if (hasDistributionSetAlreadyAssigned) { + // the target has already the distribution set assigned, we don't + // need to start the scheduled action, just finished it. + mergedAction.setStatus(Status.FINISHED); + mergedAction.setActive(false); + return actionRepository.save(mergedAction); + } + + mergedAction.setActive(true); + mergedAction.setStatus(Status.RUNNING); + final Action savedAction = actionRepository.save(mergedAction); + + final JpaActionStatus actionStatus = new JpaActionStatus(); + actionStatus.setAction(action); + actionStatus.setOccurredAt(action.getCreatedAt()); + actionStatus.setStatus(Status.RUNNING); + actionStatusRepository.save(actionStatus); + + mergedTarget.setAssignedDistributionSet(action.getDistributionSet()); + final JpaTargetInfo targetInfo = (JpaTargetInfo) mergedTarget.getTargetInfo(); + targetInfo.setUpdateStatus(TargetUpdateStatus.PENDING); + targetRepository.save(mergedTarget); + targetInfoRepository.save(targetInfo); + + // in case we canceled an action before for this target, then don't fire + // assignment event + if (!overrideObsoleteUpdateActions.contains(savedAction.getId())) { + final List softwareModules = softwareModuleRepository + .findByAssignedTo((JpaDistributionSet) action.getDistributionSet()); + // send distribution set assignment event + + assignDistributionSetEvent((JpaTarget) mergedAction.getTarget(), mergedAction.getId(), softwareModules); + } + return savedAction; + } + + @Override + public Action findAction(final Long actionId) { + return actionRepository.findOne(actionId); + } + + @Override + public Action findActionWithDetails(final Long actionId) { + return actionRepository.findById(actionId); + } + + @Override + public Slice findActionsByTarget(final Pageable pageable, final Target target) { + return actionRepository.findByTarget(pageable, (JpaTarget) target); + } + + @Override + public List findActionsByTarget(final Target target) { + return actionRepository.findByTarget((JpaTarget) target); + } + + @Override + public List findActionsWithStatusCountByTargetOrderByIdDesc(final Target target) { + final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); + final CriteriaQuery query = cb.createQuery(JpaActionWithStatusCount.class); + final Root actionRoot = query.from(JpaAction.class); + final ListJoin actionStatusJoin = actionRoot.join(JpaAction_.actionStatus, + JoinType.LEFT); + final Join actionDsJoin = actionRoot.join(JpaAction_.distributionSet); + final Join actionRolloutJoin = actionRoot.join(JpaAction_.rollout, JoinType.LEFT); + + final CriteriaQuery multiselect = query.distinct(true).multiselect( + actionRoot.get(JpaAction_.id), actionRoot.get(JpaAction_.actionType), actionRoot.get(JpaAction_.active), + actionRoot.get(JpaAction_.forcedTime), actionRoot.get(JpaAction_.status), + actionRoot.get(JpaAction_.createdAt), actionRoot.get(JpaAction_.lastModifiedAt), + actionDsJoin.get(JpaDistributionSet_.id), actionDsJoin.get(JpaDistributionSet_.name), + actionDsJoin.get(JpaDistributionSet_.version), cb.count(actionStatusJoin), + actionRolloutJoin.get(JpaRollout_.name)); + multiselect.where(cb.equal(actionRoot.get(JpaAction_.target), target)); + multiselect.orderBy(cb.desc(actionRoot.get(JpaAction_.id))); + multiselect.groupBy(actionRoot.get(JpaAction_.id)); + return new ArrayList<>(entityManager.createQuery(multiselect).getResultList()); + } + + @Override + public Page findActionsByTarget(final String rsqlParam, final Target target, final Pageable pageable) { + final Specification specification = RSQLUtility.parse(rsqlParam, ActionFields.class); + + return convertAcPage(actionRepository.findAll((Specification) (root, query, cb) -> cb + .and(specification.toPredicate(root, query, cb), cb.equal(root.get(JpaAction_.target), target)), + pageable), pageable); + } + + private static Page convertAcPage(final Page findAll, final Pageable pageable) { + return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + } + + @Override + public Slice findActionsByTarget(final Target foundTarget, final Pageable pageable) { + return actionRepository.findByTarget(pageable, (JpaTarget) foundTarget); + } + + @Override + public Page findActiveActionsByTarget(final Pageable pageable, final Target target) { + return actionRepository.findByActiveAndTarget(pageable, (JpaTarget) target, true); + } + + @Override + public List findActiveActionsByTarget(final Target target) { + return actionRepository.findByActiveAndTarget((JpaTarget) target, true); + } + + @Override + public List findInActiveActionsByTarget(final Target target) { + return actionRepository.findByActiveAndTarget((JpaTarget) target, false); + } + + @Override + public Page findInActiveActionsByTarget(final Pageable pageable, final Target target) { + return actionRepository.findByActiveAndTarget(pageable, (JpaTarget) target, false); + } + + @Override + public Long countActionsByTarget(final Target target) { + return actionRepository.countByTarget((JpaTarget) target); + } + + @Override + public Long countActionsByTarget(final String rsqlParam, final Target target) { + final Specification spec = RSQLUtility.parse(rsqlParam, ActionFields.class); + + return actionRepository.count((root, query, cb) -> cb.and(spec.toPredicate(root, query, cb), + cb.equal(root.get(JpaAction_.target), target))); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public Action forceTargetAction(final Long actionId) { + final JpaAction action = actionRepository.findOne(actionId); + if (action != null && !action.isForced()) { + action.setActionType(ActionType.FORCED); + return actionRepository.save(action); + } + return action; + } + + @Override + public Page findActionStatusByAction(final Pageable pageReq, final Action action) { + return actionStatusRepository.findByAction(pageReq, (JpaAction) action); + } + + @Override + public Page findActionStatusByActionWithMessages(final Pageable pageReq, final Action action) { + return actionStatusRepository.getByAction(pageReq, (JpaAction) action); + } + + @Override + public List findActionsByRolloutGroupParentAndStatus(final Rollout rollout, + final RolloutGroup rolloutGroupParent, final Action.Status actionStatus) { + return actionRepository.findByRolloutAndRolloutGroupParentAndStatus((JpaRollout) rollout, + (JpaRolloutGroup) rolloutGroupParent, actionStatus); + } + + @Override + public List findActionsByRolloutAndStatus(final Rollout rollout, final Action.Status actionStatus) { + return actionRepository.findByRolloutAndStatus((JpaRollout) rollout, actionStatus); + } + + @Override + public Page findActionStatusAll(final Pageable pageable) { + return convertAcSPage(actionStatusRepository.findAll(pageable), pageable); + } + + private static Page convertAcSPage(final Page findAll, final Pageable pageable) { + return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + } + + @Override + public Long countActionStatusAll() { + return actionStatusRepository.count(); + } + + @Override + public Long countActionsAll() { + return actionRepository.count(); + } + + @Override + public Slice findActionsByDistributionSet(final Pageable pageable, final DistributionSet ds) { + return actionRepository.findByDistributionSet(pageable, (JpaDistributionSet) ds); + } + + @Override + public Slice findActionsAll(final Pageable pageable) { + return convertAcPage(actionRepository.findAll(pageable), pageable); + } +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDistributionSetManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDistributionSetManagement.java new file mode 100644 index 000000000..e5a38cf51 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDistributionSetManagement.java @@ -0,0 +1,745 @@ +/** + * 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.jpa; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; + +import org.eclipse.hawkbit.repository.DistributionSetFields; +import org.eclipse.hawkbit.repository.DistributionSetManagement; +import org.eclipse.hawkbit.repository.DistributionSetMetadataFields; +import org.eclipse.hawkbit.repository.DistributionSetTypeFields; +import org.eclipse.hawkbit.repository.SystemManagement; +import org.eclipse.hawkbit.repository.TagManagement; +import org.eclipse.hawkbit.repository.eventbus.event.DistributionSetTagAssigmentResultEvent; +import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; +import org.eclipse.hawkbit.repository.exception.EntityLockedException; +import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; +import org.eclipse.hawkbit.repository.exception.EntityReadOnlyException; +import org.eclipse.hawkbit.repository.jpa.executor.AfterTransactionCommitExecutor; +import org.eclipse.hawkbit.repository.jpa.model.DsMetadataCompositeKey; +import org.eclipse.hawkbit.repository.jpa.model.JpaAction; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetMetadata; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetMetadata_; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet_; +import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility; +import org.eclipse.hawkbit.repository.jpa.specifications.DistributionSetSpecification; +import org.eclipse.hawkbit.repository.jpa.specifications.DistributionSetTypeSpecification; +import org.eclipse.hawkbit.repository.jpa.specifications.SpecificationsBuilder; +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.DistributionSetFilter.DistributionSetFilterBuilder; +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.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; + +import com.google.common.base.Strings; +import com.google.common.eventbus.EventBus; + +/** + * JPA implementation of {@link DistributionSetManagement}. + * + */ +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) +@Validated +@Service +public class JpaDistributionSetManagement implements DistributionSetManagement { + + @Autowired + private EntityManager entityManager; + + @Autowired + private DistributionSetRepository distributionSetRepository; + + @Autowired + private TagManagement tagManagement; + + @Autowired + private SystemManagement systemManagement; + + @Autowired + private DistributionSetTypeRepository distributionSetTypeRepository; + + @Autowired + private DistributionSetMetadataRepository distributionSetMetadataRepository; + + @Autowired + private ActionRepository actionRepository; + + @Autowired + private EventBus eventBus; + + @Autowired + private AfterTransactionCommitExecutor afterCommit; + + @Override + public DistributionSet findDistributionSetByIdWithDetails(final Long distid) { + return distributionSetRepository.findOne(DistributionSetSpecification.byId(distid)); + } + + @Override + public DistributionSet findDistributionSetById(final Long distid) { + return distributionSetRepository.findOne(distid); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public DistributionSetTagAssignmentResult toggleTagAssignment(final Collection dsIds, final String tagName) { + + final List sets = findDistributionSetListWithDetails(dsIds); + final DistributionSetTag myTag = tagManagement.findDistributionSetTag(tagName); + + DistributionSetTagAssignmentResult result; + final List toBeChangedDSs = new ArrayList<>(); + for (final JpaDistributionSet set : sets) { + if (set.getTags().add(myTag)) { + toBeChangedDSs.add(set); + } + } + + // un-assignment case + if (toBeChangedDSs.isEmpty()) { + for (final JpaDistributionSet set : sets) { + if (set.getTags().remove(myTag)) { + toBeChangedDSs.add(set); + } + } + result = new DistributionSetTagAssignmentResult(dsIds.size() - toBeChangedDSs.size(), 0, + toBeChangedDSs.size(), Collections.emptyList(), + new ArrayList<>(distributionSetRepository.save(toBeChangedDSs)), myTag); + } else { + result = new DistributionSetTagAssignmentResult(dsIds.size() - toBeChangedDSs.size(), toBeChangedDSs.size(), + 0, new ArrayList<>(distributionSetRepository.save(toBeChangedDSs)), Collections.emptyList(), myTag); + } + + final DistributionSetTagAssignmentResult resultAssignment = result; + afterCommit.afterCommit(() -> eventBus.post(new DistributionSetTagAssigmentResultEvent(resultAssignment))); + + // no reason to persist the tag + entityManager.detach(myTag); + return result; + } + + private List findDistributionSetListWithDetails(final Collection distributionIdSet) { + return distributionSetRepository.findAll(DistributionSetSpecification.byIds(distributionIdSet)); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public DistributionSet updateDistributionSet(final DistributionSet ds) { + checkNotNull(ds.getId()); + final DistributionSet persisted = findDistributionSetByIdWithDetails(ds.getId()); + checkDistributionSetSoftwareModulesIsAllowedToModify((JpaDistributionSet) ds, persisted.getModules()); + return distributionSetRepository.save((JpaDistributionSet) ds); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public void deleteDistributionSet(final Long... distributionSetIDs) { + final List toHardDelete = new ArrayList<>(); + + final List assigned = distributionSetRepository.findAssignedDistributionSetsById(distributionSetIDs); + + // soft delete assigned + if (!assigned.isEmpty()) { + distributionSetRepository.deleteDistributionSet(assigned.toArray(new Long[assigned.size()])); + } + + // mark the rest as hard delete + for (final Long setId : distributionSetIDs) { + if (!assigned.contains(setId)) { + toHardDelete.add(setId); + } + } + + // hard delete the rest if exixts + if (!toHardDelete.isEmpty()) { + // don't give the delete statement an empty list, JPA/Oracle cannot + // handle the empty list + distributionSetRepository.deleteByIdIn(toHardDelete); + } + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public DistributionSet createDistributionSet(final DistributionSet dSet) { + prepareDsSave(dSet); + if (dSet.getType() == null) { + dSet.setType(systemManagement.getTenantMetadata().getDefaultDsType()); + } + return distributionSetRepository.save((JpaDistributionSet) dSet); + } + + private void prepareDsSave(final DistributionSet dSet) { + if (dSet.getId() != null) { + throw new EntityAlreadyExistsException("Parameter seems to be an existing, already persisted entity"); + } + + if (distributionSetRepository.countByNameAndVersion(dSet.getName(), dSet.getVersion()) > 0) { + throw new EntityAlreadyExistsException("DistributionSet with that name and version already exists."); + } + + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public List createDistributionSets(final Collection distributionSets) { + for (final DistributionSet ds : distributionSets) { + prepareDsSave(ds); + if (ds.getType() == null) { + ds.setType(systemManagement.getTenantMetadata().getDefaultDsType()); + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + final Collection toSave = (Collection) distributionSets; + + return new ArrayList<>(distributionSetRepository.save(toSave)); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public DistributionSet assignSoftwareModules(final DistributionSet ds, final Set softwareModules) { + checkDistributionSetSoftwareModulesIsAllowedToModify((JpaDistributionSet) ds, softwareModules); + for (final SoftwareModule softwareModule : softwareModules) { + ds.addModule(softwareModule); + } + return distributionSetRepository.save((JpaDistributionSet) ds); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public DistributionSet unassignSoftwareModule(final DistributionSet ds, final SoftwareModule softwareModule) { + final Set softwareModules = new HashSet<>(); + softwareModules.add(softwareModule); + ds.removeModule(softwareModule); + checkDistributionSetSoftwareModulesIsAllowedToModify((JpaDistributionSet) ds, softwareModules); + return distributionSetRepository.save((JpaDistributionSet) ds); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public DistributionSetType updateDistributionSetType(final DistributionSetType dsType) { + checkNotNull(dsType.getId()); + + final JpaDistributionSetType persisted = distributionSetTypeRepository.findOne(dsType.getId()); + + // throw exception if user tries to update a DS type that is already in + // use + if (!persisted.areModuleEntriesIdentical(dsType) && distributionSetRepository.countByType(persisted) > 0) { + throw new EntityReadOnlyException( + String.format("distribution set type %s set is already assigned to targets and cannot be changed", + dsType.getName())); + } + + return distributionSetTypeRepository.save((JpaDistributionSetType) dsType); + } + + @Override + public Page findDistributionSetTypesAll(final String rsqlParam, final Pageable pageable) { + final Specification spec = RSQLUtility.parse(rsqlParam, + DistributionSetTypeFields.class); + + return convertDsTPage(distributionSetTypeRepository.findAll(spec, pageable)); + } + + private static Page convertDsTPage(final Page findAll) { + return new PageImpl<>(new ArrayList<>(findAll.getContent())); + } + + @Override + public Page findDistributionSetTypesAll(final Pageable pageable) { + return convertDsTPage(distributionSetTypeRepository.findByDeleted(pageable, false)); + } + + @Override + public Page findDistributionSetsByFilters(final Pageable pageable, + final DistributionSetFilter distributionSetFilter) { + final List> specList = buildDistributionSetSpecifications( + distributionSetFilter); + return convertDsPage(findByCriteriaAPI(pageable, specList), pageable); + } + + private static Page convertDsPage(final Page findAll, + final Pageable pageable) { + return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + } + + /** + * + * @param distributionSetFilter + * had details of filters to be applied + * @return a single DistributionSet which is either installed or assigned to + * a specific target or {@code null}. + */ + private DistributionSet findDistributionSetsByFiltersAndInstalledOrAssignedTarget( + final DistributionSetFilter distributionSetFilter) { + final List> specList = buildDistributionSetSpecifications( + distributionSetFilter); + if (specList == null || specList.isEmpty()) { + return null; + } + return distributionSetRepository.findOne(SpecificationsBuilder.combineWithAnd(specList)); + } + + @Override + public Page findDistributionSetsByDeletedAndOrCompleted(final Pageable pageReq, + final Boolean deleted, final Boolean complete) { + final List> specList = new ArrayList<>(); + + if (deleted != null) { + final Specification spec = DistributionSetSpecification.isDeleted(deleted); + specList.add(spec); + } + + if (complete != null) { + final Specification spec = DistributionSetSpecification.isCompleted(complete); + specList.add(spec); + } + + return convertDsPage(findByCriteriaAPI(pageReq, specList), pageReq); + } + + @Override + public Page findDistributionSetsAll(final String rsqlParam, final Pageable pageReq, + final Boolean deleted) { + + final Specification spec = RSQLUtility.parse(rsqlParam, DistributionSetFields.class); + + final List> specList = new ArrayList<>(); + if (deleted != null) { + specList.add(DistributionSetSpecification.isDeleted(deleted)); + } + specList.add(spec); + return convertDsPage(findByCriteriaAPI(pageReq, specList), pageReq); + } + + @Override + public Page findDistributionSetsAllOrderedByLinkTarget(final Pageable pageable, + final DistributionSetFilterBuilder distributionSetFilterBuilder, final String assignedOrInstalled) { + + final DistributionSetFilter filterWithInstalledTargets = distributionSetFilterBuilder + .setInstalledTargetId(assignedOrInstalled).setAssignedTargetId(null).build(); + final DistributionSet installedDS = findDistributionSetsByFiltersAndInstalledOrAssignedTarget( + filterWithInstalledTargets); + + final DistributionSetFilter filterWithAssignedTargets = distributionSetFilterBuilder.setInstalledTargetId(null) + .setAssignedTargetId(assignedOrInstalled).build(); + final DistributionSet assignedDS = findDistributionSetsByFiltersAndInstalledOrAssignedTarget( + filterWithAssignedTargets); + + final DistributionSetFilter dsFilterWithNoTargetLinked = distributionSetFilterBuilder.setInstalledTargetId(null) + .setAssignedTargetId(null).build(); + // first fine the distribution sets filtered by the given filter + // parameters + final Page findDistributionSetsByFilters = findDistributionSetsByFilters(pageable, + dsFilterWithNoTargetLinked); + + final List resultSet = new LinkedList<>(findDistributionSetsByFilters.getContent()); + int orderIndex = 0; + if (installedDS != null) { + final boolean remove = resultSet.remove(installedDS); + if (!remove) { + resultSet.remove(resultSet.size() - 1); + } + resultSet.add(orderIndex, installedDS); + orderIndex++; + } + if (assignedDS != null && !assignedDS.equals(installedDS)) { + final boolean remove = resultSet.remove(assignedDS); + if (!remove) { + resultSet.remove(resultSet.size() - 1); + } + resultSet.add(orderIndex, assignedDS); + } + + return new PageImpl<>(resultSet, pageable, findDistributionSetsByFilters.getTotalElements()); + } + + @Override + public DistributionSet findDistributionSetByNameAndVersion(final String distributionName, final String version) { + final Specification spec = DistributionSetSpecification + .equalsNameAndVersionIgnoreCase(distributionName, version); + return distributionSetRepository.findOne(spec); + + } + + @Override + public List findDistributionSetsAll(final Collection dist) { + return new ArrayList<>(distributionSetRepository.findAll(DistributionSetSpecification.byIds(dist))); + } + + @Override + public Long countDistributionSetsAll() { + + final List> specList = new LinkedList<>(); + + final Specification spec = DistributionSetSpecification.isDeleted(Boolean.FALSE); + specList.add(spec); + + return distributionSetRepository.count(SpecificationsBuilder.combineWithAnd(specList)); + } + + @Override + public Long countDistributionSetTypesAll() { + return distributionSetTypeRepository.countByDeleted(false); + } + + @Override + public DistributionSetType findDistributionSetTypeByName(final String name) { + return distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byName(name)); + } + + @Override + public DistributionSetType findDistributionSetTypeById(final Long id) { + return distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byId(id)); + } + + @Override + public DistributionSetType findDistributionSetTypeByKey(final String key) { + return distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byKey(key)); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public DistributionSetType createDistributionSetType(final DistributionSetType type) { + if (type.getId() != null) { + throw new EntityAlreadyExistsException("Given type contains an Id!"); + } + + return distributionSetTypeRepository.save((JpaDistributionSetType) type); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public void deleteDistributionSetType(final DistributionSetType ty) { + final JpaDistributionSetType type = (JpaDistributionSetType) ty; + + if (distributionSetRepository.countByType(type) > 0) { + final JpaDistributionSetType toDelete = entityManager.merge(type); + toDelete.setDeleted(true); + distributionSetTypeRepository.save(toDelete); + } else { + distributionSetTypeRepository.delete(type.getId()); + } + } + + @Override + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + @Modifying + public DistributionSetMetadata createDistributionSetMetadata(final DistributionSetMetadata md) { + final JpaDistributionSetMetadata metadata = (JpaDistributionSetMetadata) md; + + if (distributionSetMetadataRepository.exists(metadata.getId())) { + throwMetadataKeyAlreadyExists(metadata.getId().getKey()); + } + // merge base distribution set so optLockRevision gets updated and audit + // log written because + // modifying metadata is modifying the base distribution set itself for + // auditing purposes. + entityManager.merge((JpaDistributionSet) metadata.getDistributionSet()).setLastModifiedAt(0L); + return distributionSetMetadataRepository.save(metadata); + } + + @Override + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + @Modifying + public List createDistributionSetMetadata(final Collection md) { + + @SuppressWarnings({ "rawtypes", "unchecked" }) + final Collection metadata = (Collection) md; + + for (final JpaDistributionSetMetadata distributionSetMetadata : metadata) { + checkAndThrowAlreadyIfDistributionSetMetadataExists(distributionSetMetadata.getId()); + } + metadata.forEach(m -> entityManager.merge((JpaDistributionSet) m.getDistributionSet()).setLastModifiedAt(0L)); + + return new ArrayList<>( + (Collection) distributionSetMetadataRepository.save(metadata)); + } + + @Override + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + @Modifying + public DistributionSetMetadata updateDistributionSetMetadata(final DistributionSetMetadata md) { + final JpaDistributionSetMetadata metadata = (JpaDistributionSetMetadata) md; + + // check if exists otherwise throw entity not found exception + findOne(metadata.getDistributionSet(), metadata.getKey()); + // touch it to update the lock revision because we are modifying the + // DS indirectly + entityManager.merge((JpaDistributionSet) metadata.getDistributionSet()).setLastModifiedAt(0L); + return distributionSetMetadataRepository.save(metadata); + } + + @Override + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + @Modifying + public void deleteDistributionSetMetadata(final DistributionSet distributionSet, final String key) { + distributionSetMetadataRepository.delete(new DsMetadataCompositeKey(distributionSet, key)); + } + + @Override + public Page findDistributionSetMetadataByDistributionSetId(final Long distributionSetId, + final Pageable pageable) { + + return convertMdPage(distributionSetMetadataRepository + .findAll((Specification) (root, query, cb) -> cb.equal( + root.get(JpaDistributionSetMetadata_.distributionSet).get(JpaDistributionSet_.id), + distributionSetId), pageable), + pageable); + } + + @Override + public Page findDistributionSetMetadataByDistributionSetId(final Long distributionSetId, + final String rsqlParam, final Pageable pageable) { + + final Specification spec = RSQLUtility.parse(rsqlParam, + DistributionSetMetadataFields.class); + + return convertMdPage( + distributionSetMetadataRepository + .findAll((Specification) (root, query, cb) -> cb.and( + cb.equal(root.get(JpaDistributionSetMetadata_.distributionSet) + .get(JpaDistributionSet_.id), distributionSetId), + spec.toPredicate(root, query, cb)), pageable), + pageable); + } + + private static Page convertMdPage(final Page findAll, + final Pageable pageable) { + return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + } + + @Override + public DistributionSetMetadata findOne(final DistributionSet distributionSet, final String key) { + final DistributionSetMetadata findOne = distributionSetMetadataRepository + .findOne(new DsMetadataCompositeKey(distributionSet, key)); + if (findOne == null) { + throw new EntityNotFoundException("Metadata with key '" + key + "' does not exist"); + } + return findOne; + } + + @Override + public DistributionSet findDistributionSetByAction(final Action action) { + return distributionSetRepository.findByAction((JpaAction) action); + } + + @Override + public boolean isDistributionSetInUse(final DistributionSet distributionSet) { + return actionRepository.countByDistributionSet((JpaDistributionSet) distributionSet) > 0; + } + + private static List> buildDistributionSetSpecifications( + final DistributionSetFilter distributionSetFilter) { + final List> specList = new ArrayList<>(); + + Specification spec; + + if (null != distributionSetFilter.getIsComplete()) { + spec = DistributionSetSpecification.isCompleted(distributionSetFilter.getIsComplete()); + specList.add(spec); + } + + if (null != distributionSetFilter.getIsDeleted()) { + spec = DistributionSetSpecification.isDeleted(distributionSetFilter.getIsDeleted()); + specList.add(spec); + } + + if (distributionSetFilter.getType() != null) { + spec = DistributionSetSpecification.byType(distributionSetFilter.getType()); + specList.add(spec); + } + + if (!Strings.isNullOrEmpty(distributionSetFilter.getSearchText())) { + spec = DistributionSetSpecification.likeNameOrDescriptionOrVersion(distributionSetFilter.getSearchText()); + specList.add(spec); + } + + if (isDSWithNoTagSelected(distributionSetFilter) || isTagsSelected(distributionSetFilter)) { + spec = DistributionSetSpecification.hasTags(distributionSetFilter.getTagNames(), + distributionSetFilter.getSelectDSWithNoTag()); + specList.add(spec); + } + if (distributionSetFilter.getInstalledTargetId() != null) { + spec = DistributionSetSpecification.installedTarget(distributionSetFilter.getInstalledTargetId()); + specList.add(spec); + } + if (distributionSetFilter.getAssignedTargetId() != null) { + spec = DistributionSetSpecification.assignedTarget(distributionSetFilter.getAssignedTargetId()); + specList.add(spec); + } + return specList; + } + + private void checkDistributionSetSoftwareModulesIsAllowedToModify(final JpaDistributionSet distributionSet, + final Set softwareModules) { + if (!new HashSet(distributionSet.getModules()).equals(softwareModules) + && actionRepository.countByDistributionSet(distributionSet) > 0) { + throw new EntityLockedException( + String.format("distribution set %s:%s is already assigned to targets and cannot be changed", + distributionSet.getName(), distributionSet.getVersion())); + } + } + + private static Boolean isDSWithNoTagSelected(final DistributionSetFilter distributionSetFilter) { + if (distributionSetFilter.getSelectDSWithNoTag() != null && distributionSetFilter.getSelectDSWithNoTag()) { + return true; + } + return false; + } + + private static Boolean isTagsSelected(final DistributionSetFilter distributionSetFilter) { + if (distributionSetFilter.getTagNames() != null && !distributionSetFilter.getTagNames().isEmpty()) { + return true; + } + return false; + } + + /** + * executes findAll with the given {@link DistributionSet} + * {@link Specification}s. + * + * @param pageable + * paging parameter + * @param specList + * list of @link {@link Specification} + * @return the page with the found {@link DistributionSet} + */ + private Page findByCriteriaAPI(final Pageable pageable, + final List> specList) { + + if (specList == null || specList.isEmpty()) { + return distributionSetRepository.findAll(pageable); + } + + return distributionSetRepository.findAll(SpecificationsBuilder.combineWithAnd(specList), pageable); + } + + private void checkAndThrowAlreadyIfDistributionSetMetadataExists(final DsMetadataCompositeKey metadataId) { + if (distributionSetMetadataRepository.exists(metadataId)) { + throw new EntityAlreadyExistsException( + "Metadata entry with key '" + metadataId.getKey() + "' already exists"); + } + } + + private static void throwMetadataKeyAlreadyExists(final String metadataKey) { + throw new EntityAlreadyExistsException("Metadata entry with key '" + metadataKey + "' already exists"); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public List assignTag(final Collection dsIds, final DistributionSetTag tag) { + final List allDs = findDistributionSetListWithDetails(dsIds); + + allDs.forEach(ds -> ds.getTags().add(tag)); + + final List save = new ArrayList<>(distributionSetRepository.save(allDs)); + + afterCommit.afterCommit(() -> { + + final DistributionSetTagAssignmentResult result = new DistributionSetTagAssignmentResult(0, save.size(), 0, + save, Collections.emptyList(), tag); + eventBus.post(new DistributionSetTagAssigmentResultEvent(result)); + }); + + return save; + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public List unAssignAllDistributionSetsByTag(final DistributionSetTag tag) { + + @SuppressWarnings({ "unchecked", "rawtypes" }) + final Collection distributionSets = (Collection) tag.getAssignedToDistributionSet(); + + return new ArrayList<>(unAssignTag(distributionSets, tag)); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public DistributionSet unAssignTag(final Long dsId, final DistributionSetTag distributionSetTag) { + final List allDs = findDistributionSetListWithDetails(Arrays.asList(dsId)); + final List unAssignTag = unAssignTag(allDs, distributionSetTag); + return unAssignTag.isEmpty() ? null : unAssignTag.get(0); + } + + private List unAssignTag(final Collection distributionSets, + final DistributionSetTag tag) { + distributionSets.forEach(ds -> ds.getTags().remove(tag)); + return distributionSetRepository.save(distributionSets); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public List createDistributionSetTypes(final Collection types) { + return types.stream().map(this::createDistributionSetType).collect(Collectors.toList()); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public void deleteDistributionSet(final DistributionSet set) { + deleteDistributionSet(set.getId()); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public DistributionSetTagAssignmentResult toggleTagAssignment(final Collection sets, + final DistributionSetTag tag) { + return toggleTagAssignment(sets.stream().map(ds -> ds.getId()).collect(Collectors.toList()), tag.getName()); + } + + @Override + public Long countDistributionSetsByType(final DistributionSetType type) { + return distributionSetRepository.countByType((JpaDistributionSetType) type); + } +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaEntityFactory.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaEntityFactory.java new file mode 100644 index 000000000..afa3b4dc6 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaEntityFactory.java @@ -0,0 +1,208 @@ +/** + * 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.jpa; + +import java.util.Collection; + +import org.eclipse.hawkbit.repository.EntityFactory; +import org.eclipse.hawkbit.repository.jpa.model.JpaAction; +import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetMetadata; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType; +import org.eclipse.hawkbit.repository.jpa.model.JpaLocalArtifact; +import org.eclipse.hawkbit.repository.jpa.model.JpaRollout; +import org.eclipse.hawkbit.repository.jpa.model.JpaRolloutGroup; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleMetadata; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetFilterQuery; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag; +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.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.springframework.stereotype.Service; + +/** + * JPA Implementation of {@link EntityFactory}. + * + */ +@Service +public class JpaEntityFactory implements EntityFactory { + + @Override + public DistributionSetType generateDistributionSetType() { + return new JpaDistributionSetType(); + } + + @Override + public DistributionSet generateDistributionSet() { + return new JpaDistributionSet(); + } + + @Override + public DistributionSetMetadata generateDistributionSetMetadata() { + return new JpaDistributionSetMetadata(); + } + + @Override + public DistributionSetMetadata generateDistributionSetMetadata(final DistributionSet distributionSet, + final String key, final String value) { + return new JpaDistributionSetMetadata(key, distributionSet, value); + } + + @Override + public DistributionSetType generateDistributionSetType(final String key, final String name, + final String description) { + return new JpaDistributionSetType(key, name, description); + } + + @Override + public DistributionSet generateDistributionSet(final String name, final String version, final String description, + final DistributionSetType type, final Collection moduleList) { + return new JpaDistributionSet(name, version, description, type, moduleList); + } + + @Override + public Target generateTarget(final String controllerId) { + return new JpaTarget(controllerId); + } + + @Override + public TargetTag generateTargetTag() { + return new JpaTargetTag(); + } + + @Override + public DistributionSetTag generateDistributionSetTag() { + return new JpaDistributionSetTag(); + } + + @Override + public TargetTag generateTargetTag(final String name, final String description, final String colour) { + return new JpaTargetTag(name, description, colour); + } + + @Override + public DistributionSetTag generateDistributionSetTag(final String name, final String description, + final String colour) { + return new JpaDistributionSetTag(name, description, colour); + } + + @Override + public TargetTag generateTargetTag(final String name) { + return new JpaTargetTag(name); + } + + @Override + public DistributionSetTag generateDistributionSetTag(final String name) { + return new JpaDistributionSetTag(name); + } + + @Override + public TargetFilterQuery generateTargetFilterQuery() { + return new JpaTargetFilterQuery(); + } + + @Override + public SoftwareModuleType generateSoftwareModuleType() { + return new JpaSoftwareModuleType(); + } + + @Override + public SoftwareModule generateSoftwareModule() { + return new JpaSoftwareModule(); + } + + @Override + public SoftwareModule generateSoftwareModule(final SoftwareModuleType type, final String name, final String version, + final String description, final String vendor) { + + return new JpaSoftwareModule(type, name, version, description, vendor); + } + + @Override + public SoftwareModuleMetadata generateSoftwareModuleMetadata() { + return new JpaSoftwareModuleMetadata(); + } + + @Override + public SoftwareModuleMetadata generateSoftwareModuleMetadata(final SoftwareModule softwareModule, final String key, + final String value) { + return new JpaSoftwareModuleMetadata(key, softwareModule, value); + } + + @Override + public SoftwareModuleType generateSoftwareModuleType(final String key, final String name, final String description, + final int maxAssignments) { + return new JpaSoftwareModuleType(key, name, description, maxAssignments); + } + + @Override + public Rollout generateRollout() { + return new JpaRollout(); + } + + @Override + public RolloutGroup generateRolloutGroup() { + return new JpaRolloutGroup(); + } + + @Override + public Action generateAction() { + return new JpaAction(); + } + + @Override + public ActionStatus generateActionStatus() { + return new JpaActionStatus(); + } + + @Override + public ActionStatus generateActionStatus(final Action action, final Status status, final Long occurredAt, + final String message) { + return new JpaActionStatus((JpaAction) action, status, occurredAt, message); + } + + @Override + public ActionStatus generateActionStatus(final Action action, final Status status, final Long occurredAt, + final Collection messages) { + + final ActionStatus result = new JpaActionStatus((JpaAction) action, status, occurredAt, null); + messages.forEach(result::addMessage); + + return result; + } + + @Override + public ActionStatus generateActionStatus(final Action action, final Status status, final Long occurredAt) { + return new JpaActionStatus(action, status, occurredAt); + } + + @Override + public LocalArtifact generateLocalArtifact() { + return new JpaLocalArtifact(); + } + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ReportManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaReportManagement.java similarity index 69% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ReportManagement.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaReportManagement.java index 406538705..76eb04a34 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ReportManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaReportManagement.java @@ -6,12 +6,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import java.io.Serializable; -import java.time.LocalDate; import java.time.LocalDateTime; -import java.time.YearMonth; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.ArrayList; @@ -31,33 +29,35 @@ import javax.persistence.criteria.JoinType; import javax.persistence.criteria.ListJoin; import javax.persistence.criteria.Root; -import org.eclipse.hawkbit.report.model.DataReportSeries; -import org.eclipse.hawkbit.report.model.DataReportSeriesItem; -import org.eclipse.hawkbit.report.model.InnerOuterDataReportSeries; -import org.eclipse.hawkbit.report.model.ListReportSeries; -import org.eclipse.hawkbit.report.model.SeriesTime; -import org.eclipse.hawkbit.repository.model.DistributionSet; -import org.eclipse.hawkbit.repository.model.DistributionSet_; -import org.eclipse.hawkbit.repository.model.Target; -import org.eclipse.hawkbit.repository.model.TargetInfo; -import org.eclipse.hawkbit.repository.model.TargetInfo_; +import org.eclipse.hawkbit.repository.ReportManagement; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet_; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetInfo; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetInfo_; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget_; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; -import org.eclipse.hawkbit.repository.model.Target_; +import org.eclipse.hawkbit.repository.report.model.DataReportSeries; +import org.eclipse.hawkbit.repository.report.model.DataReportSeriesItem; +import org.eclipse.hawkbit.repository.report.model.InnerOuterDataReportSeries; +import org.eclipse.hawkbit.repository.report.model.SeriesTime; import org.eclipse.hawkbit.tenancy.TenantAware; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; /** - * Service layer for generating hawkBit reports. + * JPA implementation of {@link ReportManagement}. * */ @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) @Validated -public class ReportManagement { +@Service +public class JpaReportManagement implements ReportManagement { @Value("${spring.jpa.database}") private String databaseType; @@ -82,26 +82,19 @@ public class ReportManagement { @Autowired private TenantAware tenantAware; - /** - * 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 - */ + @Override @Cacheable("targetStatus") public DataReportSeries targetStatus() { final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaQuery query = cb.createQuery(Object[].class); - final Root targetRoot = query.from(Target.class); - final Join targetInfo = targetRoot.join(Target_.targetInfo); - final Expression countColumn = cb.count(targetInfo.get(TargetInfo_.targetId)); + final Root targetRoot = query.from(JpaTarget.class); + final Join targetInfo = targetRoot.join(JpaTarget_.targetInfo); + final Expression countColumn = cb.count(targetInfo.get(JpaTargetInfo_.targetId)); final CriteriaQuery multiselect = query - .multiselect(targetInfo.get(TargetInfo_.updateStatus), countColumn) - .groupBy(targetInfo.get(TargetInfo_.updateStatus)) - .orderBy(cb.desc(targetInfo.get(TargetInfo_.updateStatus))); + .multiselect(targetInfo.get(JpaTargetInfo_.updateStatus), countColumn) + .groupBy(targetInfo.get(JpaTargetInfo_.updateStatus)) + .orderBy(cb.desc(targetInfo.get(JpaTargetInfo_.updateStatus))); // | col1 | col2 | // | U_STATUS | COUNT | @@ -114,38 +107,24 @@ public class ReportManagement { return new DataReportSeries<>("Target Status Overview", reportSeriesItems); } - /** - * 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 - */ + @Override @Cacheable("distributionUsageAssigned") public List> distributionUsageAssigned(final int topXEntries) { // top X entries distribution usage final CriteriaBuilder cbTopX = entityManager.getCriteriaBuilder(); final CriteriaQuery queryTopX = cbTopX.createQuery(Object[].class); - final Root rootTopX = queryTopX.from(DistributionSet.class); - final ListJoin joinTopX = rootTopX.join(DistributionSet_.assignedToTargets, + final Root rootTopX = queryTopX.from(JpaDistributionSet.class); + final ListJoin joinTopX = rootTopX.join(JpaDistributionSet_.assignedToTargets, JoinType.LEFT); final Expression countColumn = cbTopX.count(joinTopX); // top x usage query final CriteriaQuery groupBy = queryTopX - .multiselect(rootTopX.get(DistributionSet_.name), rootTopX.get(DistributionSet_.version), countColumn) - .where(cbTopX.equal(rootTopX.get(DistributionSet_.deleted), false)) - .groupBy(rootTopX.get(DistributionSet_.name), rootTopX.get(DistributionSet_.version)) - .orderBy(cbTopX.desc(countColumn), cbTopX.asc(rootTopX.get(DistributionSet_.name))); + .multiselect(rootTopX.get(JpaDistributionSet_.name), rootTopX.get(JpaDistributionSet_.version), + countColumn) + .where(cbTopX.equal(rootTopX.get(JpaDistributionSet_.deleted), false)) + .groupBy(rootTopX.get(JpaDistributionSet_.name), rootTopX.get(JpaDistributionSet_.version)) + .orderBy(cbTopX.desc(countColumn), cbTopX.asc(rootTopX.get(JpaDistributionSet_.name))); // | col1 | col2 | col3 | // | NAME | VER | COUNT | final List resultListTop = entityManager.createQuery(groupBy).getResultList(); @@ -154,38 +133,23 @@ public class ReportManagement { return mapDistirbutionUsageResultToDataReport(topXEntries, resultListTop); } - /** - * 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 - */ + @Override @Cacheable("distributionUsageInstalled") public List> distributionUsageInstalled(final int topXEntries) { // top X entries distribution usage final CriteriaBuilder cbTopX = entityManager.getCriteriaBuilder(); final CriteriaQuery queryTopX = cbTopX.createQuery(Object[].class); - final Root rootTopX = queryTopX.from(DistributionSet.class); - final ListJoin joinTopX = rootTopX.join(DistributionSet_.installedAtTargets, - JoinType.LEFT); + final Root rootTopX = queryTopX.from(JpaDistributionSet.class); + final ListJoin joinTopX = rootTopX + .join(JpaDistributionSet_.installedAtTargets, JoinType.LEFT); final Expression countColumn = cbTopX.count(joinTopX); // top x usage query final CriteriaQuery groupBy = queryTopX - .multiselect(rootTopX.get(DistributionSet_.name), rootTopX.get(DistributionSet_.version), countColumn) - .where(cbTopX.equal(rootTopX.get(DistributionSet_.deleted), false)) - .groupBy(rootTopX.get(DistributionSet_.name), rootTopX.get(DistributionSet_.version)) - .orderBy(cbTopX.desc(countColumn), cbTopX.asc(rootTopX.get(DistributionSet_.name))); + .multiselect(rootTopX.get(JpaDistributionSet_.name), rootTopX.get(JpaDistributionSet_.version), + countColumn) + .where(cbTopX.equal(rootTopX.get(JpaDistributionSet_.deleted), false)) + .groupBy(rootTopX.get(JpaDistributionSet_.name), rootTopX.get(JpaDistributionSet_.version)) + .orderBy(cbTopX.desc(countColumn), cbTopX.asc(rootTopX.get(JpaDistributionSet_.name))); // | col1 | col2 | col3 | // | NAME | VER | COUNT | final List resultListTop = entityManager.createQuery(groupBy).getResultList(); @@ -194,18 +158,7 @@ public class ReportManagement { return mapDistirbutionUsageResultToDataReport(topXEntries, resultListTop); } - /** - * Generates report for target created over period. - * - * @param dateType - * {@link PerMonth} - * @param from - * start date - * @param to - * end date - * @return DataReportSeries ListReportSeries list of target created - * count - */ + @Override @Cacheable("targetsCreatedOverPeriod") public DataReportSeries targetsCreatedOverPeriod(final DateType dateType, final LocalDateTime from, final LocalDateTime to) { @@ -256,23 +209,13 @@ public class ReportManagement { } } - /** - * Generates report for feedback over period. - * - * @param dateType - * {@link PerMonth} - * @param from - * start date - * @param to - * end date - * @return DataReportSeries ListReportSeries list of action status - * count - */ + @Override @Cacheable("feedbackReceivedOverTime") public DataReportSeries feedbackReceivedOverTime(final DateType dateType, final LocalDateTime from, final LocalDateTime to) { final Query createNativeQuery = entityManager .createNativeQuery(getFeedbackReceivedQueryTemplate(dateType, from, to)); + @SuppressWarnings("unchecked") final List resultList = createNativeQuery.getResultList(); final List> reportItems = resultList.stream() @@ -282,19 +225,7 @@ public class ReportManagement { return new DataReportSeries<>("FeedbackRecieved", reportItems); } - /** - * Generates a report as a {@link ListReportSeries} targets polled based on - * the {@link TargetStatus#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. - * - */ + @Override @Cacheable("targetsLastPoll") public DataReportSeries targetsLastPoll() { @@ -347,15 +278,15 @@ public class ReportManagement { // count select statement final CriteriaQuery countSelect = cb.createQuery(Long.class); - final Root countSelectRoot = countSelect.from(Target.class); - final Join targetInfoJoin = countSelectRoot.join(Target_.targetInfo); + final Root countSelectRoot = countSelect.from(JpaTarget.class); + final Join targetInfoJoin = countSelectRoot.join(JpaTarget_.targetInfo); countSelect.select(cb.count(countSelectRoot)); if (start != null && end != null) { - countSelect.where(cb.between(targetInfoJoin.get(TargetInfo_.lastTargetQuery), start, end)); + countSelect.where(cb.between(targetInfoJoin.get(JpaTargetInfo_.lastTargetQuery), start, end)); } else if (from == null && to != null) { - countSelect.where(cb.lessThanOrEqualTo(targetInfoJoin.get(TargetInfo_.lastTargetQuery), end)); + countSelect.where(cb.lessThanOrEqualTo(targetInfoJoin.get(JpaTargetInfo_.lastTargetQuery), end)); } else { - countSelect.where(cb.isNull(targetInfoJoin.get(TargetInfo_.lastTargetQuery))); + countSelect.where(cb.isNull(targetInfoJoin.get(JpaTargetInfo_.lastTargetQuery))); } return countSelect; } @@ -502,80 +433,4 @@ public class ReportManagement { } } - /** - * 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() { - - } - - /** - * @return PerMonth - */ - public static PerMonth perMonth() { - return PER_MONTH; - } - } - - /** - * Data base format. - * - * - * - * @param - */ - public interface DateType { - /** - * @param s - * @return T - */ - T format(String s); - - /** - * h2 format. - * - * @return String - */ - String h2Format(); - - /** - * mysql format. - * - * @return String - */ - String mySqlFormat(); - } - - /** - * Gives the date format based on DB H2 or mySql. - * - * - * - */ - public static final class PerMonth implements DateType, 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"; - } - - } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutGroupManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutGroupManagement.java similarity index 51% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutGroupManagement.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutGroupManagement.java index 401a8cb16..7d176d40a 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutGroupManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutGroupManagement.java @@ -6,8 +6,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -19,20 +20,25 @@ import javax.persistence.criteria.Join; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.ListJoin; import javax.persistence.criteria.Root; -import javax.validation.constraints.NotNull; -import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; +import org.eclipse.hawkbit.repository.RolloutGroupFields; +import org.eclipse.hawkbit.repository.RolloutGroupManagement; +import org.eclipse.hawkbit.repository.TargetFields; +import org.eclipse.hawkbit.repository.jpa.model.JpaAction; +import org.eclipse.hawkbit.repository.jpa.model.JpaAction_; +import org.eclipse.hawkbit.repository.jpa.model.JpaRolloutGroup; +import org.eclipse.hawkbit.repository.jpa.model.JpaRolloutGroup_; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget_; +import org.eclipse.hawkbit.repository.jpa.model.RolloutTargetGroup; +import org.eclipse.hawkbit.repository.jpa.model.RolloutTargetGroup_; +import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility; import org.eclipse.hawkbit.repository.model.Action; -import org.eclipse.hawkbit.repository.model.Action_; 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_; -import org.eclipse.hawkbit.repository.model.RolloutTargetGroup; -import org.eclipse.hawkbit.repository.model.RolloutTargetGroup_; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetWithActionStatus; -import org.eclipse.hawkbit.repository.model.Target_; import org.eclipse.hawkbit.repository.model.TotalTargetCountActionStatus; import org.eclipse.hawkbit.repository.model.TotalTargetCountStatus; import org.springframework.beans.factory.annotation.Autowired; @@ -41,18 +47,18 @@ import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; -import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; /** - * RolloutGroupManagement to control rollout groups. This service secures all - * the functionality based on the {@link PreAuthorize} annotation on methods. + * JPA implementation of {@link RolloutGroupManagement}. */ @Validated +@Service @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) -public class RolloutGroupManagement { +public class JpaRolloutGroupManagement implements RolloutGroupManagement { @Autowired private RolloutGroupRepository rolloutGroupRepository; @@ -66,68 +72,43 @@ public class RolloutGroupManagement { @Autowired private EntityManager entityManager; - /** - * 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) + @Override public RolloutGroup findRolloutGroupById(final Long rolloutGroupId) { return rolloutGroupRepository.findOne(rolloutGroupId); } - /** - * 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 page - * the page request to sort and limit the result - * @return a page of found {@link RolloutGroup}s - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ) - public Page findRolloutGroupsByRolloutId(final Long rolloutId, final Pageable page) { - return rolloutGroupRepository.findByRolloutId(rolloutId, page); + @Override + public Page findRolloutGroupsByRolloutId(final Long rolloutId, final Pageable pageable) { + return convertPage(rolloutGroupRepository.findByRolloutId(rolloutId, pageable), pageable); } - /** - * Retrieves a page of {@link RolloutGroup}s filtered by a given - * {@link Rollout} and the given {@link Specification}. - * - * @param rolloutId - * the ID of the rollout to filter the {@link RolloutGroup}s - * @param specification - * the specification to filter the result set based on attributes - * of the {@link RolloutGroup} - * @param page - * the page request to sort and limit the result - * @return a page of found {@link RolloutGroup}s - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ) - public Page findRolloutGroupsByPredicate(final Rollout rollout, - final Specification specification, final Pageable page) { - return rolloutGroupRepository.findAll((root, query, criteriaBuilder) -> criteriaBuilder.and( - criteriaBuilder.equal(root.get(RolloutGroup_.rollout), rollout), - specification.toPredicate(root, query, criteriaBuilder)), page); + private static Page convertPage(final Page findAll, final Pageable pageable) { + return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); } - /** - * 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 page - * the page request to sort and limit the result - * @return a page of found {@link RolloutGroup}s - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ) - public Page findAllRolloutGroupsWithDetailedStatus(final Long rolloutId, final Pageable page) { - final Page rolloutGroups = rolloutGroupRepository.findByRolloutId(rolloutId, page); + private static Page convertTPage(final Page findAll, final Pageable pageable) { + return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + } + + @Override + public Page findRolloutGroupsAll(final Rollout rollout, final String rsqlParam, + final Pageable pageable) { + + final Specification specification = RSQLUtility.parse(rsqlParam, RolloutGroupFields.class); + + return convertPage( + rolloutGroupRepository + .findAll( + (root, query, criteriaBuilder) -> criteriaBuilder.and( + criteriaBuilder.equal(root.get(JpaRolloutGroup_.rollout), rollout), + specification.toPredicate(root, query, criteriaBuilder)), + pageable), + pageable); + } + + @Override + public Page findAllRolloutGroupsWithDetailedStatus(final Long rolloutId, final Pageable pageable) { + final Page rolloutGroups = rolloutGroupRepository.findByRolloutId(rolloutId, pageable); final List rolloutGroupIds = rolloutGroups.getContent().stream().map(rollout -> rollout.getId()) .collect(Collectors.toList()); final Map> allStatesForRollout = getStatusCountItemForRolloutGroup( @@ -139,17 +120,10 @@ public class RolloutGroupManagement { rolloutGroup.setTotalTargetCountStatus(totalTargetCountStatus); } - return rolloutGroups; + return convertPage(rolloutGroups, 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) + @Override public RolloutGroup findRolloutGroupWithDetailedStatus(final Long rolloutGroupId) { final RolloutGroup rolloutGroup = findRolloutGroupById(rolloutGroupId); final List rolloutStatusCountItems = actionRepository @@ -169,78 +143,45 @@ public class RolloutGroupManagement { return resultList.stream().collect(Collectors.groupingBy(TotalTargetCountActionStatus::getId)); } - /** - * Get targets of specified rollout group. - * - * @param rolloutGroup - * rollout group - * @param specification - * the specification for filtering the targets of a rollout group - * @param page - * the page request to sort and limit the result - * - * @return Page list of targets of a rollout group - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ) - public Page findRolloutGroupTargets(final RolloutGroup rolloutGroup, - final Specification specification, final Pageable page) { - return targetRepository.findAll((root, query, criteriaBuilder) -> { - final ListJoin rolloutTargetJoin = root.join(Target_.rolloutTargetGroup); - return criteriaBuilder.and(specification.toPredicate(root, query, criteriaBuilder), + @Override + public Page findRolloutGroupTargets(final RolloutGroup rolloutGroup, final String rsqlParam, + final Pageable pageable) { + + final Specification rsqlSpecification = RSQLUtility.parse(rsqlParam, TargetFields.class); + + return convertTPage(targetRepository.findAll((root, query, criteriaBuilder) -> { + final ListJoin rolloutTargetJoin = root.join(JpaTarget_.rolloutTargetGroup); + return criteriaBuilder.and(rsqlSpecification.toPredicate(root, query, criteriaBuilder), criteriaBuilder.equal(rolloutTargetJoin.get(RolloutTargetGroup_.rolloutGroup), rolloutGroup)); - }, page); + }, 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 list of targets of a rollout group - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ) - public Page findRolloutGroupTargets(@NotNull final RolloutGroup rolloutGroup, final Pageable page) { + @Override + public Page findRolloutGroupTargets(final RolloutGroup rolloutGroup, final Pageable page) { if (isRolloutStatusReady(rolloutGroup)) { // in case of status ready the action has not been created yet and // the relation information between target and rollout-group is // stored in the #TargetRolloutGroup. return targetRepository.findByRolloutTargetGroupRolloutGroupId(rolloutGroup.getId(), page); } - return targetRepository.findByActionsRolloutGroup(rolloutGroup, page); + return targetRepository.findByActionsRolloutGroup((JpaRolloutGroup) rolloutGroup, page); } private static boolean isRolloutStatusReady(final RolloutGroup rolloutGroup) { return rolloutGroup != null && RolloutStatus.READY.equals(rolloutGroup.getRollout().getStatus()); } - /** - * - * 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) + @Override public Page findAllTargetsWithActionStatus(final PageRequest pageRequest, - @NotNull final RolloutGroup rolloutGroup) { + final RolloutGroup rolloutGroup) { final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaQuery query = cb.createQuery(Object[].class); final CriteriaQuery countQuery = cb.createQuery(Long.class); final Root targetRoot = query.distinct(true).from(RolloutTargetGroup.class); - final Join targetJoin = targetRoot.join(RolloutTargetGroup_.target); - final ListJoin actionJoin = targetRoot.join(RolloutTargetGroup_.actions, + final Join targetJoin = targetRoot.join(RolloutTargetGroup_.target); + final ListJoin actionJoin = targetRoot.join(RolloutTargetGroup_.actions, JoinType.LEFT); final Root countQueryFrom = countQuery.distinct(true).from(RolloutTargetGroup.class); @@ -250,7 +191,7 @@ public class RolloutGroupManagement { .where(cb.equal(countQueryFrom.get(RolloutTargetGroup_.rolloutGroup), rolloutGroup)); final Long totalCount = entityManager.createQuery(countQuery).getSingleResult(); - final CriteriaQuery multiselect = query.multiselect(targetJoin, actionJoin.get(Action_.status)) + final CriteriaQuery multiselect = query.multiselect(targetJoin, actionJoin.get(JpaAction_.status)) .where(cb.equal(targetRoot.get(RolloutTargetGroup_.rolloutGroup), rolloutGroup)); final List targetWithActionStatus = entityManager.createQuery(multiselect) .setFirstResult(pageRequest.getOffset()).setMaxResults(pageRequest.getPageSize()).getResultList() @@ -258,4 +199,5 @@ public class RolloutGroupManagement { .collect(Collectors.toList()); return new PageImpl<>(targetWithActionStatus, pageRequest, totalCount); } + } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutManagement.java similarity index 63% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutManagement.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutManagement.java index d59feb424..d412d2164 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutManagement.java @@ -6,8 +6,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; @@ -16,30 +17,35 @@ import java.util.concurrent.Executor; import java.util.stream.Collectors; import javax.persistence.EntityManager; -import javax.validation.constraints.NotNull; -import org.eclipse.hawkbit.cache.CacheWriteNotify; -import org.eclipse.hawkbit.eventbus.event.RolloutGroupCreatedEvent; -import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; +import org.eclipse.hawkbit.repository.DeploymentManagement; +import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; +import org.eclipse.hawkbit.repository.RolloutFields; +import org.eclipse.hawkbit.repository.RolloutManagement; +import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.exception.RolloutIllegalStateException; +import org.eclipse.hawkbit.repository.jpa.cache.CacheWriteNotify; +import org.eclipse.hawkbit.repository.jpa.model.JpaRollout; +import org.eclipse.hawkbit.repository.jpa.model.JpaRolloutGroup; +import org.eclipse.hawkbit.repository.jpa.model.JpaRollout_; +import org.eclipse.hawkbit.repository.jpa.model.RolloutTargetGroup; +import org.eclipse.hawkbit.repository.jpa.rollout.condition.RolloutGroupActionEvaluator; +import org.eclipse.hawkbit.repository.jpa.rollout.condition.RolloutGroupConditionEvaluator; +import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.ActionType; 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.RolloutGroupConditions; import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupErrorCondition; import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupStatus; import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessCondition; -import org.eclipse.hawkbit.repository.model.RolloutTargetGroup; -import org.eclipse.hawkbit.repository.model.Rollout_; +import org.eclipse.hawkbit.repository.model.RolloutGroupConditions; import org.eclipse.hawkbit.repository.model.Target; +import org.eclipse.hawkbit.repository.model.TargetWithActionType; import org.eclipse.hawkbit.repository.model.TotalTargetCountActionStatus; import org.eclipse.hawkbit.repository.model.TotalTargetCountStatus; -import org.eclipse.hawkbit.rollout.condition.RolloutGroupActionEvaluator; -import org.eclipse.hawkbit.rollout.condition.RolloutGroupConditionEvaluator; -import org.hibernate.validator.constraints.NotEmpty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; @@ -47,6 +53,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Slice; import org.springframework.data.domain.Sort; @@ -54,7 +61,7 @@ import org.springframework.data.domain.Sort.Direction; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.Modifying; import org.springframework.scheduling.annotation.EnableScheduling; -import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.annotation.Isolation; @@ -66,14 +73,13 @@ import org.springframework.util.Assert; import org.springframework.validation.annotation.Validated; /** - * 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. + * JPA implementation of {@link RolloutManagement}. */ @Validated +@Service @EnableScheduling @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) -public class RolloutManagement { +public class JpaRolloutManagement implements RolloutManagement { private static final Logger LOGGER = LoggerFactory.getLogger(RolloutManagement.class); @Autowired @@ -132,122 +138,49 @@ public class RolloutManagement { */ private static final Set startingRollouts = ConcurrentHashMap.newKeySet(); - /** - * Retrieves all rollouts. - * - * @param page - * the page request to sort and limit the result - * @return a page of found rollouts - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ) - public Page findAll(final Pageable page) { - return rolloutRepository.findAll(page); + @Override + public Page findAll(final Pageable pageable) { + return convertPage(rolloutRepository.findAll(pageable), pageable); } - /** - * Retrieves all rollouts found by the given specification. - * - * @param specification - * the specification to filter rollouts - * @param page - * the page request to sort and limit the result - * @return a page of found rollouts - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ) - public Page findAllWithDetailedStatusByPredicate(final Specification specification, - final Pageable page) { - final Page findAll = rolloutRepository.findAll(specification, page); + private static Page convertPage(final Page findAll, final Pageable pageable) { + return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + } + + private static Slice convertPage(final Slice findAll, final Pageable pageable) { + return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, 0); + } + + @Override + public Page findAllWithDetailedStatusByPredicate(final String rsqlParam, final Pageable pageable) { + + final Specification specification = RSQLUtility.parse(rsqlParam, RolloutFields.class); + + final Page findAll = rolloutRepository.findAll(specification, pageable); setRolloutStatusDetails(findAll); - return findAll; + return convertPage(findAll, pageable); } - /** - * 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) + @Override public Rollout findRolloutById(final Long rolloutId) { return rolloutRepository.findOne(rolloutId); } - /** - * 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. - */ + @Override @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE) public Rollout createRollout(final Rollout rollout, final int amountGroup, final RolloutGroupConditions conditions) { - final Rollout savedRollout = createRollout(rollout, amountGroup); + final JpaRollout savedRollout = createRollout((JpaRollout) rollout, amountGroup); return createRolloutGroups(amountGroup, conditions, savedRollout); } - /** - * 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} - */ + @Override @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE) public Rollout createRolloutAsync(final Rollout rollout, final int amountGroup, final RolloutGroupConditions conditions) { - final Rollout savedRollout = createRollout(rollout, amountGroup); + final JpaRollout savedRollout = createRollout((JpaRollout) rollout, amountGroup); creatingRollouts.add(savedRollout.getName()); // need to flush the entity manager here to get the ID of the rollout, // because entity manager is set to FlushMode#Auto, entitymanager will @@ -267,7 +200,7 @@ public class RolloutManagement { return savedRollout; } - private Rollout createRollout(final Rollout rollout, final int amountGroup) { + private JpaRollout createRollout(final JpaRollout rollout, final int amountGroup) { verifyRolloutGroupParameter(amountGroup); final Long totalTargets = targetManagement.countTargetByTargetFilterQuery(rollout.getTargetFilterQuery()); rollout.setTotalTargets(totalTargets.longValue()); @@ -283,7 +216,7 @@ public class RolloutManagement { } private Rollout createRolloutGroupsInNewTransaction(final int amountOfGroups, - final RolloutGroupConditions conditions, final Rollout savedRollout) { + final RolloutGroupConditions conditions, final JpaRollout savedRollout) { final DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("creatingRollout"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); @@ -306,7 +239,7 @@ public class RolloutManagement { * @return the rollout with created groups */ private Rollout createRolloutGroups(final int amountOfGroups, final RolloutGroupConditions conditions, - final Rollout savedRollout) { + final JpaRollout savedRollout) { int pageIndex = 0; int groupIndex = 0; final Long totalCount = savedRollout.getTotalTargets(); @@ -322,7 +255,7 @@ public class RolloutManagement { while (pageIndex < totalCount) { groupIndex++; final String nameAndDesc = "group-" + groupIndex; - final RolloutGroup group = new RolloutGroup(); + final JpaRolloutGroup group = new JpaRolloutGroup(); group.setName(nameAndDesc); group.setDescription(nameAndDesc); group.setRollout(savedRollout); @@ -334,7 +267,7 @@ public class RolloutManagement { group.setErrorAction(conditions.getErrorAction()); group.setErrorActionExp(conditions.getErrorActionExp()); - final RolloutGroup savedGroup = rolloutGroupRepository.save(group); + final JpaRolloutGroup savedGroup = rolloutGroupRepository.save(group); final Slice targetGroup = targetManagement.findTargetsAll(savedRollout.getTargetFilterQuery(), new OffsetBasedPageRequest(pageIndex, groupSize, new Sort(Direction.ASC, "id"))); @@ -353,62 +286,23 @@ public class RolloutManagement { return rolloutRepository.save(savedRollout); } - /** - * 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. - */ + @Override @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE + SpringEvalExpressions.HAS_AUTH_OR - + SpringEvalExpressions.IS_SYSTEM_CODE) public Rollout startRollout(final Rollout rollout) { - final Rollout mergedRollout = entityManager.merge(rollout); + final JpaRollout mergedRollout = entityManager.merge((JpaRollout) rollout); checkIfRolloutCanStarted(rollout, mergedRollout); return doStartRollout(mergedRollout); } - /** - * 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. - */ - @Transactional + @Override + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE + SpringEvalExpressions.HAS_AUTH_OR - + SpringEvalExpressions.IS_SYSTEM_CODE) public Rollout startRolloutAsync(final Rollout rollout) { - final Rollout mergedRollout = entityManager.merge(rollout); + final JpaRollout mergedRollout = entityManager.merge((JpaRollout) rollout); checkIfRolloutCanStarted(rollout, mergedRollout); mergedRollout.setStatus(RolloutStatus.STARTING); - final Rollout updatedRollout = rolloutRepository.save(mergedRollout); + final JpaRollout updatedRollout = rolloutRepository.save(mergedRollout); startingRollouts.add(updatedRollout.getName()); executor.execute(() -> { try { @@ -427,13 +321,13 @@ public class RolloutManagement { } - private Rollout doStartRollout(final Rollout rollout) { + private Rollout doStartRollout(final JpaRollout rollout) { final DistributionSet distributionSet = rollout.getDistributionSet(); final ActionType actionType = rollout.getActionType(); final long forceTime = rollout.getForcedTime(); - final List rolloutGroups = rolloutGroupRepository.findByRolloutOrderByIdAsc(rollout); + final List rolloutGroups = rolloutGroupRepository.findByRolloutOrderByIdAsc(rollout); for (int iGroup = 0; iGroup < rolloutGroups.size(); iGroup++) { - final RolloutGroup rolloutGroup = rolloutGroups.get(iGroup); + final JpaRolloutGroup rolloutGroup = rolloutGroups.get(iGroup); final List targetGroup = targetRepository.findByRolloutTargetGroupRolloutGroup(rolloutGroup); // firstgroup can already be started if (iGroup == 0) { @@ -456,31 +350,11 @@ public class RolloutManagement { return rolloutRepository.save(rollout); } - /** - * 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. - */ + @Override @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE + SpringEvalExpressions.HAS_AUTH_OR - + SpringEvalExpressions.IS_SYSTEM_CODE) public void pauseRollout(final Rollout rollout) { - final Rollout mergedRollout = entityManager.merge(rollout); + final JpaRollout mergedRollout = entityManager.merge((JpaRollout) rollout); if (mergedRollout.getStatus() != RolloutStatus.RUNNING) { throw new RolloutIllegalStateException("Rollout can only be paused in state running but current state is " + rollout.getStatus().name().toLowerCase()); @@ -494,23 +368,11 @@ public class RolloutManagement { rolloutRepository.save(mergedRollout); } - /** - * 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. - */ + @Override @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE + SpringEvalExpressions.HAS_AUTH_OR - + SpringEvalExpressions.IS_SYSTEM_CODE) public void resumeRollout(final Rollout rollout) { - final Rollout mergedRollout = entityManager.merge(rollout); + final JpaRollout mergedRollout = entityManager.merge((JpaRollout) rollout); if (!(RolloutStatus.PAUSED.equals(mergedRollout.getStatus()))) { throw new RolloutIllegalStateException("Rollout can only be resumed in state paused but current state is " + rollout.getStatus().name().toLowerCase()); @@ -519,38 +381,9 @@ public class RolloutManagement { rolloutRepository.save(mergedRollout); } - /** - * 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. - * - *
-     * {@code
-     *  SystemSecurityContext.runAsSystem(new Callable() {
-     *     public Void call() throws Exception {
-     *        //run system-code
-     *     }
-     * });
-     *  }
-     * 
- * - * 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). - */ + @Override @Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_UNCOMMITTED) @Modifying - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE + SpringEvalExpressions.HAS_AUTH_OR - + SpringEvalExpressions.IS_SYSTEM_CODE) public void checkRunningRollouts(final long delayBetweenChecks) { verifyStuckedRollouts(); final long lastCheck = System.currentTimeMillis(); @@ -564,13 +397,13 @@ public class RolloutManagement { return; } - final List rolloutsToCheck = rolloutRepository.findByLastCheckAndStatus(lastCheck, + final List rolloutsToCheck = rolloutRepository.findByLastCheckAndStatus(lastCheck, RolloutStatus.RUNNING); LOGGER.info("Found {} running rollouts to check", rolloutsToCheck.size()); - for (final Rollout rollout : rolloutsToCheck) { + for (final JpaRollout rollout : rolloutsToCheck) { LOGGER.debug("Checking rollout {}", rollout); - final List rolloutGroups = rolloutGroupRepository.findByRolloutAndStatus(rollout, + final List rolloutGroups = rolloutGroupRepository.findByRolloutAndStatus(rollout, RolloutGroupStatus.RUNNING); if (rolloutGroups.isEmpty()) { @@ -600,7 +433,7 @@ public class RolloutManagement { * In case this happens, set the rollout to error state. */ private void verifyStuckedRollouts() { - final List rolloutsInCreatingState = rolloutRepository.findByStatus(RolloutStatus.CREATING); + final List rolloutsInCreatingState = rolloutRepository.findByStatus(RolloutStatus.CREATING); rolloutsInCreatingState.stream().filter(rollout -> !creatingRollouts.contains(rollout.getName())) .forEach(rollout -> { LOGGER.warn( @@ -610,7 +443,7 @@ public class RolloutManagement { rolloutRepository.save(rollout); }); - final List rolloutsInStartingState = rolloutRepository.findByStatus(RolloutStatus.STARTING); + final List rolloutsInStartingState = rolloutRepository.findByStatus(RolloutStatus.STARTING); rolloutsInStartingState.stream().filter(rollout -> !startingRollouts.contains(rollout.getName())) .forEach(rollout -> { LOGGER.warn( @@ -622,8 +455,8 @@ public class RolloutManagement { } - private void executeRolloutGroups(final Rollout rollout, final List rolloutGroups) { - for (final RolloutGroup rolloutGroup : rolloutGroups) { + private void executeRolloutGroups(final JpaRollout rollout, final List rolloutGroups) { + for (final JpaRolloutGroup rolloutGroup : rolloutGroups) { // error state check, do we need to stop the whole // rollout because of error? final RolloutGroupErrorCondition errorCondition = rolloutGroup.getErrorCondition(); @@ -644,8 +477,8 @@ public class RolloutManagement { } } - private void executeLatestRolloutGroup(final Rollout rollout) { - final List latestRolloutGroup = rolloutGroupRepository + private void executeLatestRolloutGroup(final JpaRollout rollout) { + final List latestRolloutGroup = rolloutGroupRepository .findByRolloutAndStatusNotOrderByIdDesc(rollout, RolloutGroupStatus.SCHEDULED); if (latestRolloutGroup.isEmpty()) { return; @@ -663,13 +496,13 @@ public class RolloutManagement { } } - private boolean isRolloutComplete(final Rollout rollout) { + private boolean isRolloutComplete(final JpaRollout rollout) { final Long groupsActiveLeft = rolloutGroupRepository.countByRolloutAndStatusOrStatus(rollout, RolloutGroupStatus.RUNNING, RolloutGroupStatus.SCHEDULED); return groupsActiveLeft == 0; } - private boolean isRolloutGroupComplete(final Rollout rollout, final RolloutGroup rolloutGroup) { + private boolean isRolloutGroupComplete(final JpaRollout rollout, final JpaRolloutGroup rolloutGroup) { final Long actionsLeftForRollout = actionRepository .countByRolloutAndRolloutGroupAndStatusNotAndStatusNotAndStatusNot(rollout, rolloutGroup, Action.Status.ERROR, Action.Status.FINISHED, Action.Status.CANCELED); @@ -718,65 +551,35 @@ public class RolloutManagement { rolloutGroup, rolloutGroup.getSuccessActionExp()); } - /** - * Counts all {@link Target}s in the repository. - * - * @return number of targets - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ) + @Override public Long countRolloutsAll() { return rolloutRepository.count(); } - /** - * Count rollouts by specified filter text. - * - * @param searchText - * name or description - * @return total count rollouts for specified filter text. - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ) + @Override public Long countRolloutsAllByFilters(final String searchText) { return rolloutRepository.count(likeNameOrDescription(searchText)); } - private static Specification likeNameOrDescription(final String searchText) { + private static Specification likeNameOrDescription(final String searchText) { return (rolloutRoot, query, criteriaBuilder) -> { final String searchTextToLower = searchText.toLowerCase(); return criteriaBuilder.or( - criteriaBuilder.like(criteriaBuilder.lower(rolloutRoot.get(Rollout_.name)), searchTextToLower), - criteriaBuilder.like(criteriaBuilder.lower(rolloutRoot.get(Rollout_.description)), + criteriaBuilder.like(criteriaBuilder.lower(rolloutRoot.get(JpaRollout_.name)), searchTextToLower), + criteriaBuilder.like(criteriaBuilder.lower(rolloutRoot.get(JpaRollout_.description)), searchTextToLower)); }; } - /** - * * Retrieves a specific rollout by its ID. - * - * @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) - public Slice findRolloutByFilters(final Pageable pageable, @NotEmpty final String searchText) { - final Specification specs = likeNameOrDescription(searchText); - final Slice findAll = criteriaNoCountDao.findAll(specs, pageable, Rollout.class); + @Override + public Slice findRolloutByFilters(final Pageable pageable, final String searchText) { + final Specification specs = likeNameOrDescription(searchText); + final Slice findAll = criteriaNoCountDao.findAll(specs, pageable, JpaRollout.class); setRolloutStatusDetails(findAll); - return findAll; + return convertPage(findAll, pageable); } - /** - * 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) + @Override public Rollout findRolloutByName(final String rolloutName) { return rolloutRepository.findByName(rolloutName); } @@ -789,13 +592,12 @@ public class RolloutManagement { * * @return Rollout updated rollout */ - @NotNull + @Override @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE) - public Rollout updateRollout(@NotNull final Rollout rollout) { + public Rollout updateRollout(final Rollout rollout) { Assert.notNull(rollout.getId()); - return rolloutRepository.save(rollout); + return rolloutRepository.save((JpaRollout) rollout); } /** @@ -807,30 +609,22 @@ public class RolloutManagement { * statuses * */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ) - public Page findAllRolloutsWithDetailedStatus(final Pageable page) { - final Page rollouts = findAll(page); + @Override + public Page findAllRolloutsWithDetailedStatus(final Pageable pageable) { + final Page rollouts = rolloutRepository.findAll(pageable); setRolloutStatusDetails(rollouts); - return rollouts; + return convertPage(rollouts, pageable); } - /** - * 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) + @Override public Rollout findRolloutWithDetailedStatus(final Long rolloutId) { final Rollout rollout = findRolloutById(rolloutId); final List rolloutStatusCountItems = actionRepository .getStatusCountByRolloutId(rolloutId); final TotalTargetCountStatus totalTargetCountStatus = new TotalTargetCountStatus(rolloutStatusCountItems, rollout.getTotalTargets()); - rollout.setTotalTargetCountStatus(totalTargetCountStatus); + ((JpaRollout) rollout).setTotalTargetCountStatus(totalTargetCountStatus); return rollout; } @@ -839,7 +633,7 @@ public class RolloutManagement { return resultList.stream().collect(Collectors.groupingBy(TotalTargetCountActionStatus::getId)); } - private void setRolloutStatusDetails(final Slice rollouts) { + private void setRolloutStatusDetails(final Slice rollouts) { final List rolloutIds = rollouts.getContent().stream().map(rollout -> rollout.getId()) .collect(Collectors.toList()); final Map> allStatesForRollout = getStatusCountItemForRollout( @@ -848,7 +642,7 @@ public class RolloutManagement { for (final Rollout rollout : rollouts) { final TotalTargetCountStatus totalTargetCountStatus = new TotalTargetCountStatus( allStatesForRollout.get(rollout.getId()), rollout.getTotalTargets()); - rollout.setTotalTargetCountStatus(totalTargetCountStatus); + ((JpaRollout) rollout).setTotalTargetCountStatus(totalTargetCountStatus); } } @@ -859,16 +653,7 @@ public class RolloutManagement { } } - /*** - * 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 - */ + @Override public float getFinishedPercentForRunningGroup(final Long rolloutId, final RolloutGroup rolloutGroup) { final Long totalGroup = rolloutGroup.getTotalTargets(); final Long finished = actionRepository.countByRolloutIdAndRolloutGroupIdAndStatus(rolloutId, @@ -881,4 +666,5 @@ public class RolloutManagement { // calculate threshold return ((float) finished / (float) totalGroup) * 100; } + } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSoftwareManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSoftwareManagement.java new file mode 100644 index 000000000..2fc057aec --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSoftwareManagement.java @@ -0,0 +1,665 @@ +/** + * 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.jpa; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.ListJoin; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; + +import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; +import org.eclipse.hawkbit.repository.ArtifactManagement; +import org.eclipse.hawkbit.repository.SoftwareManagement; +import org.eclipse.hawkbit.repository.SoftwareModuleFields; +import org.eclipse.hawkbit.repository.SoftwareModuleMetadataFields; +import org.eclipse.hawkbit.repository.SoftwareModuleTypeFields; +import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; +import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet_; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleMetadata; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleMetadata_; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule_; +import org.eclipse.hawkbit.repository.jpa.model.SwMetadataCompositeKey; +import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility; +import org.eclipse.hawkbit.repository.jpa.specifications.SoftwareModuleSpecification; +import org.eclipse.hawkbit.repository.jpa.specifications.SpecificationsBuilder; +import org.eclipse.hawkbit.repository.model.AssignedSoftwareModule; +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.SoftwareModuleType; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.AuditorAware; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Slice; +import org.springframework.data.domain.SliceImpl; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; + +import com.google.common.base.Strings; +import com.google.common.collect.Sets; + +/** + * JPA implementation of {@link SoftwareManagement}. + * + */ +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) +@Validated +@Service +public class JpaSoftwareManagement implements SoftwareManagement { + + @Autowired + private EntityManager entityManager; + + @Autowired + private DistributionSetRepository distributionSetRepository; + + @Autowired + private DistributionSetTypeRepository distributionSetTypeRepository; + + @Autowired + private SoftwareModuleRepository softwareModuleRepository; + + @Autowired + private SoftwareModuleMetadataRepository softwareModuleMetadataRepository; + + @Autowired + private SoftwareModuleTypeRepository softwareModuleTypeRepository; + + @Autowired + private NoCountPagingRepository criteriaNoCountDao; + + @Autowired + private AuditorAware auditorProvider; + + @Autowired + private ArtifactManagement artifactManagement; + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public SoftwareModule updateSoftwareModule(final SoftwareModule sm) { + checkNotNull(sm.getId()); + + final JpaSoftwareModule module = softwareModuleRepository.findOne(sm.getId()); + + boolean updated = false; + if (null == sm.getDescription() || !sm.getDescription().equals(module.getDescription())) { + module.setDescription(sm.getDescription()); + updated = true; + } + if (null == sm.getVendor() || !sm.getVendor().equals(module.getVendor())) { + module.setVendor(sm.getVendor()); + updated = true; + } + + return updated ? softwareModuleRepository.save(module) : module; + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public SoftwareModuleType updateSoftwareModuleType(final SoftwareModuleType sm) { + checkNotNull(sm.getId()); + + final JpaSoftwareModuleType type = softwareModuleTypeRepository.findOne(sm.getId()); + + boolean updated = false; + if (sm.getDescription() != null && !sm.getDescription().equals(type.getDescription())) { + type.setDescription(sm.getDescription()); + updated = true; + } + if (sm.getColour() != null && !sm.getColour().equals(type.getColour())) { + type.setColour(sm.getColour()); + updated = true; + } + return updated ? softwareModuleTypeRepository.save(type) : type; + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public SoftwareModule createSoftwareModule(final SoftwareModule swModule) { + if (null != swModule.getId()) { + throw new EntityAlreadyExistsException(); + } + return softwareModuleRepository.save((JpaSoftwareModule) swModule); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public List createSoftwareModule(final Collection swModules) { + swModules.forEach(swModule -> { + if (null != swModule.getId()) { + throw new EntityAlreadyExistsException(); + } + }); + + @SuppressWarnings({ "unchecked", "rawtypes" }) + final Collection jpaCast = (Collection) swModules; + + return new ArrayList<>(softwareModuleRepository.save(jpaCast)); + } + + @Override + public Slice findSoftwareModulesByType(final Pageable pageable, final SoftwareModuleType type) { + + final List> specList = new LinkedList<>(); + + Specification spec = SoftwareModuleSpecification.equalType((JpaSoftwareModuleType) type); + specList.add(spec); + + spec = SoftwareModuleSpecification.isDeletedFalse(); + specList.add(spec); + + return convertSmPage(findSwModuleByCriteriaAPI(pageable, specList), pageable); + } + + private static Slice convertSmPage(final Slice findAll, + final Pageable pageable) { + return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, 0); + } + + private static Page convertSmPage(final Page findAll, final Pageable pageable) { + return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + } + + private static Page convertSmMdPage(final Page findAll, + final Pageable pageable) { + return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + } + + @Override + public Long countSoftwareModulesByType(final SoftwareModuleType type) { + + final List> specList = new ArrayList<>(); + + Specification spec = SoftwareModuleSpecification.equalType((JpaSoftwareModuleType) type); + specList.add(spec); + + spec = SoftwareModuleSpecification.isDeletedFalse(); + specList.add(spec); + + return countSwModuleByCriteriaAPI(specList); + } + + @Override + public SoftwareModule findSoftwareModuleById(final Long id) { + return artifactManagement.findSoftwareModuleById(id); + } + + @Override + public SoftwareModule findSoftwareModuleByNameAndVersion(final String name, final String version, + final SoftwareModuleType type) { + + return softwareModuleRepository.findOneByNameAndVersionAndType(name, version, (JpaSoftwareModuleType) type); + } + + private boolean isUnassigned(final JpaSoftwareModule bsmMerged) { + return distributionSetRepository.findByModules(bsmMerged).isEmpty(); + } + + private Slice findSwModuleByCriteriaAPI(final Pageable pageable, + final List> specList) { + return criteriaNoCountDao.findAll(SpecificationsBuilder.combineWithAnd(specList), pageable, + JpaSoftwareModule.class); + } + + private Long countSwModuleByCriteriaAPI(final List> specList) { + return softwareModuleRepository.count(SpecificationsBuilder.combineWithAnd(specList)); + } + + private void deleteGridFsArtifacts(final JpaSoftwareModule swModule) { + for (final LocalArtifact localArtifact : swModule.getLocalArtifacts()) { + artifactManagement.deleteLocalArtifact(localArtifact); + } + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public void deleteSoftwareModules(final Collection ids) { + final List swModulesToDelete = softwareModuleRepository.findByIdIn(ids); + final Set assignedModuleIds = new HashSet<>(); + swModulesToDelete.forEach(swModule -> { + + // delete binary data of artifacts + deleteGridFsArtifacts(swModule); + + if (isUnassigned(swModule)) { + + softwareModuleRepository.delete(swModule); + + } else { + + assignedModuleIds.add(swModule.getId()); + } + }); + + if (!assignedModuleIds.isEmpty()) { + String currentUser = null; + if (auditorProvider != null) { + currentUser = auditorProvider.getCurrentAuditor(); + } + softwareModuleRepository.deleteSoftwareModule(System.currentTimeMillis(), currentUser, + assignedModuleIds.toArray(new Long[0])); + } + } + + @Override + public Slice findSoftwareModulesAll(final Pageable pageable) { + + final List> specList = new ArrayList<>(); + + Specification spec = SoftwareModuleSpecification.isDeletedFalse(); + specList.add(spec); + + spec = (root, query, cb) -> { + if (!query.getResultType().isAssignableFrom(Long.class)) { + root.fetch(JpaSoftwareModule_.type); + } + return cb.conjunction(); + }; + + specList.add(spec); + + return convertSmPage(findSwModuleByCriteriaAPI(pageable, specList), pageable); + } + + @Override + public Long countSoftwareModulesAll() { + + final List> specList = new ArrayList<>(); + + final Specification spec = SoftwareModuleSpecification.isDeletedFalse(); + specList.add(spec); + + return countSwModuleByCriteriaAPI(specList); + } + + @Override + public SoftwareModule findSoftwareModuleWithDetails(final Long id) { + return artifactManagement.findSoftwareModuleWithDetails(id); + } + + @Override + public Page findSoftwareModulesByPredicate(final String rsqlParam, final Pageable pageable) { + final Specification spec = RSQLUtility.parse(rsqlParam, SoftwareModuleFields.class); + + return convertSmPage(softwareModuleRepository.findAll(spec, pageable), pageable); + } + + @Override + public Page findSoftwareModuleTypesAll(final String rsqlParam, final Pageable pageable) { + + final Specification spec = RSQLUtility.parse(rsqlParam, SoftwareModuleTypeFields.class); + + return convertSmTPage(softwareModuleTypeRepository.findAll(spec, pageable), pageable); + } + + private static Page convertSmTPage(final Page findAll, + final Pageable pageable) { + return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + } + + @Override + @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) + public List findSoftwareModulesById(final Collection ids) { + return new ArrayList<>(softwareModuleRepository.findByIdIn(ids)); + } + + @Override + public Slice findSoftwareModuleByFilters(final Pageable pageable, final String searchText, + final SoftwareModuleType type) { + + final List> specList = new ArrayList<>(); + + Specification spec = SoftwareModuleSpecification.isDeletedFalse(); + specList.add(spec); + + if (!Strings.isNullOrEmpty(searchText)) { + spec = SoftwareModuleSpecification.likeNameOrVersion(searchText); + specList.add(spec); + } + + if (null != type) { + spec = SoftwareModuleSpecification.equalType((JpaSoftwareModuleType) type); + specList.add(spec); + } + + spec = (root, query, cb) -> { + if (!query.getResultType().isAssignableFrom(Long.class)) { + root.fetch(JpaSoftwareModule_.type); + } + return cb.conjunction(); + }; + + specList.add(spec); + + return convertSmPage(findSwModuleByCriteriaAPI(pageable, specList), pageable); + } + + @Override + public Slice findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc( + final Pageable pageable, final Long orderByDistributionId, final String searchText, + final SoftwareModuleType ty) { + final JpaSoftwareModuleType type = (JpaSoftwareModuleType) ty; + + final List resultList = new ArrayList<>(); + final int pageSize = pageable.getPageSize(); + final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); + + // get the assigned software modules + final CriteriaQuery assignedQuery = cb.createQuery(JpaSoftwareModule.class); + final Root assignedRoot = assignedQuery.from(JpaSoftwareModule.class); + assignedQuery.distinct(true); + final ListJoin assignedDsJoin = assignedRoot + .join(JpaSoftwareModule_.assignedTo); + // build the specifications and then to predicates necessary by the + // given filters + final Predicate[] specPredicate = specificationsToPredicate(buildSpecificationList(searchText, type), + assignedRoot, assignedQuery, cb, + cb.equal(assignedDsJoin.get(JpaDistributionSet_.id), orderByDistributionId)); + // if we have some predicates then add it to the where clause of the + // multi select + assignedQuery.where(specPredicate); + assignedQuery.orderBy(cb.asc(assignedRoot.get(JpaSoftwareModule_.name)), + cb.asc(assignedRoot.get(JpaSoftwareModule_.version))); + // don't page the assigned query on database, we need all assigned + // software modules to filter + // them out in the unassigned query + final List assignedSoftwareModules = entityManager.createQuery(assignedQuery) + .getResultList(); + // map result + if (pageable.getOffset() < assignedSoftwareModules.size()) { + assignedSoftwareModules + .subList(pageable.getOffset(), Math.min(assignedSoftwareModules.size(), pageable.getPageSize())) + .forEach(sw -> resultList.add(new AssignedSoftwareModule(sw, true))); + } + + if (assignedSoftwareModules.size() >= pageSize) { + return new SliceImpl<>(resultList); + } + + // get the unassigned software modules + final CriteriaQuery unassignedQuery = cb.createQuery(JpaSoftwareModule.class); + unassignedQuery.distinct(true); + final Root unassignedRoot = unassignedQuery.from(JpaSoftwareModule.class); + + Predicate[] unassignedSpec; + if (!assignedSoftwareModules.isEmpty()) { + unassignedSpec = specificationsToPredicate(buildSpecificationList(searchText, type), unassignedRoot, + unassignedQuery, cb, cb.not(unassignedRoot.get(JpaSoftwareModule_.id) + .in(assignedSoftwareModules.stream().map(sw -> sw.getId()).collect(Collectors.toList())))); + } else { + unassignedSpec = specificationsToPredicate(buildSpecificationList(searchText, type), unassignedRoot, + unassignedQuery, cb); + } + + unassignedQuery.where(unassignedSpec); + unassignedQuery.orderBy(cb.asc(unassignedRoot.get(JpaSoftwareModule_.name)), + cb.asc(unassignedRoot.get(JpaSoftwareModule_.version))); + final List unassignedSoftwareModules = entityManager.createQuery(unassignedQuery) + .setFirstResult(Math.max(0, pageable.getOffset() - assignedSoftwareModules.size())) + .setMaxResults(pageSize).getResultList(); + // map result + unassignedSoftwareModules.forEach(sw -> resultList.add(new AssignedSoftwareModule(sw, false))); + + return new SliceImpl<>(resultList); + } + + private static List> buildSpecificationList(final String searchText, + final JpaSoftwareModuleType type) { + final List> specList = new ArrayList<>(); + if (!Strings.isNullOrEmpty(searchText)) { + specList.add(SoftwareModuleSpecification.likeNameOrVersion(searchText)); + } + if (type != null) { + specList.add(SoftwareModuleSpecification.equalType(type)); + } + specList.add(SoftwareModuleSpecification.isDeletedFalse()); + return specList; + } + + private Predicate[] specificationsToPredicate(final List> specifications, + final Root root, final CriteriaQuery query, final CriteriaBuilder cb, + final Predicate... additionalPredicates) { + final List predicates = new ArrayList<>(); + specifications.forEach(spec -> predicates.add(spec.toPredicate(root, query, cb))); + for (final Predicate predicate : additionalPredicates) { + predicates.add(predicate); + } + return predicates.toArray(new Predicate[predicates.size()]); + } + + @Override + public Long countSoftwareModuleByFilters(final String searchText, final SoftwareModuleType type) { + + final List> specList = new ArrayList<>(); + + Specification spec = SoftwareModuleSpecification.isDeletedFalse(); + specList.add(spec); + + if (!Strings.isNullOrEmpty(searchText)) { + spec = SoftwareModuleSpecification.likeNameOrVersion(searchText); + specList.add(spec); + } + + if (null != type) { + spec = SoftwareModuleSpecification.equalType((JpaSoftwareModuleType) type); + specList.add(spec); + } + + return countSwModuleByCriteriaAPI(specList); + } + + @Override + public Page findSoftwareModuleTypesAll(final Pageable pageable) { + return softwareModuleTypeRepository.findByDeleted(pageable, false); + } + + @Override + public Long countSoftwareModuleTypesAll() { + return softwareModuleTypeRepository.countByDeleted(false); + } + + @Override + public SoftwareModuleType findSoftwareModuleTypeByKey(final String key) { + return softwareModuleTypeRepository.findByKey(key); + } + + @Override + public SoftwareModuleType findSoftwareModuleTypeById(final Long id) { + return softwareModuleTypeRepository.findOne(id); + } + + @Override + public SoftwareModuleType findSoftwareModuleTypeByName(final String name) { + return softwareModuleTypeRepository.findByName(name); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public SoftwareModuleType createSoftwareModuleType(final SoftwareModuleType type) { + if (type.getId() != null) { + throw new EntityAlreadyExistsException("Given type contains an Id!"); + } + + return softwareModuleTypeRepository.save((JpaSoftwareModuleType) type); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public void deleteSoftwareModuleType(final SoftwareModuleType ty) { + final JpaSoftwareModuleType type = (JpaSoftwareModuleType) ty; + + if (softwareModuleRepository.countByType(type) > 0 + || distributionSetTypeRepository.countByElementsSmType(type) > 0) { + final JpaSoftwareModuleType toDelete = entityManager.merge(type); + toDelete.setDeleted(true); + softwareModuleTypeRepository.save(toDelete); + } else { + softwareModuleTypeRepository.delete(type.getId()); + } + } + + @Override + public Page findSoftwareModuleByAssignedTo(final Pageable pageable, final DistributionSet set) { + return softwareModuleRepository.findByAssignedTo(pageable, (JpaDistributionSet) set); + } + + @Override + public Page findSoftwareModuleByAssignedToAndType(final Pageable pageable, + final DistributionSet set, final SoftwareModuleType type) { + return softwareModuleRepository.findByAssignedToAndType(pageable, (JpaDistributionSet) set, + (JpaSoftwareModuleType) type); + } + + @Override + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + @Modifying + public SoftwareModuleMetadata createSoftwareModuleMetadata(final SoftwareModuleMetadata md) { + final JpaSoftwareModuleMetadata metadata = (JpaSoftwareModuleMetadata) md; + + if (softwareModuleMetadataRepository.exists(metadata.getId())) { + throwMetadataKeyAlreadyExists(metadata.getId().getKey()); + } + // merge base software module so optLockRevision gets updated and audit + // log written because + // modifying metadata is modifying the base software module itself for + // auditing purposes. + entityManager.merge((JpaSoftwareModule) metadata.getSoftwareModule()).setLastModifiedAt(-1L); + return softwareModuleMetadataRepository.save(metadata); + } + + @Override + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + @Modifying + public List createSoftwareModuleMetadata(final Collection md) { + @SuppressWarnings({ "unchecked", "rawtypes" }) + final Collection metadata = (Collection) md; + + for (final JpaSoftwareModuleMetadata softwareModuleMetadata : metadata) { + checkAndThrowAlreadyExistsIfSoftwareModuleMetadataExists(softwareModuleMetadata.getId()); + } + metadata.forEach(m -> entityManager.merge((JpaSoftwareModule) m.getSoftwareModule()).setLastModifiedAt(-1L)); + return new ArrayList<>(softwareModuleMetadataRepository.save(metadata)); + } + + @Override + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + @Modifying + public SoftwareModuleMetadata updateSoftwareModuleMetadata(final SoftwareModuleMetadata md) { + final JpaSoftwareModuleMetadata metadata = (JpaSoftwareModuleMetadata) md; + + // check if exists otherwise throw entity not found exception + findSoftwareModuleMetadata(metadata.getId()); + // touch it to update the lock revision because we are modifying the + // software module + // indirectly + entityManager.merge((JpaSoftwareModule) metadata.getSoftwareModule()).setLastModifiedAt(-1L); + return softwareModuleMetadataRepository.save(metadata); + } + + @Override + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + @Modifying + public void deleteSoftwareModuleMetadata(final SoftwareModule softwareModule, final String key) { + softwareModuleMetadataRepository.delete(new SwMetadataCompositeKey(softwareModule, key)); + } + + @Override + public Page findSoftwareModuleMetadataBySoftwareModuleId(final Long swId, + final Pageable pageable) { + return softwareModuleMetadataRepository.findBySoftwareModuleId(swId, pageable); + } + + @Override + public Page findSoftwareModuleMetadataBySoftwareModuleId(final Long softwareModuleId, + final String rsqlParam, final Pageable pageable) { + + final Specification spec = RSQLUtility.parse(rsqlParam, + SoftwareModuleMetadataFields.class); + return convertSmMdPage( + softwareModuleMetadataRepository + .findAll( + (Specification) (root, query, cb) -> cb.and( + cb.equal(root.get(JpaSoftwareModuleMetadata_.softwareModule) + .get(JpaSoftwareModule_.id), softwareModuleId), + spec.toPredicate(root, query, cb)), + pageable), + pageable); + } + + @Override + public SoftwareModuleMetadata findSoftwareModuleMetadata(final SoftwareModule softwareModule, final String key) { + return findSoftwareModuleMetadata(new SwMetadataCompositeKey(softwareModule, key)); + } + + private SoftwareModuleMetadata findSoftwareModuleMetadata(final SwMetadataCompositeKey id) { + final SoftwareModuleMetadata findOne = softwareModuleMetadataRepository.findOne(id); + if (findOne == null) { + throw new EntityNotFoundException("Metadata with key '" + id.getKey() + "' does not exist"); + } + return findOne; + } + + private void checkAndThrowAlreadyExistsIfSoftwareModuleMetadataExists(final SwMetadataCompositeKey metadataId) { + if (softwareModuleMetadataRepository.exists(metadataId)) { + throw new EntityAlreadyExistsException( + "Metadata entry with key '" + metadataId.getKey() + "' already exists"); + } + } + + private static void throwMetadataKeyAlreadyExists(final String metadataKey) { + throw new EntityAlreadyExistsException("Metadata entry with key '" + metadataKey + "' already exists"); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public void deleteSoftwareModule(final SoftwareModule bsm) { + deleteSoftwareModules(Sets.newHashSet(bsm.getId())); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public List createSoftwareModuleType(final Collection types) { + + return types.stream().map(this::createSoftwareModuleType).collect(Collectors.toList()); + } + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SystemManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSystemManagement.java similarity index 71% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SystemManagement.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSystemManagement.java index 3da592a3e..3fed3d858 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SystemManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSystemManagement.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import java.lang.reflect.Method; import java.math.BigDecimal; @@ -14,15 +14,19 @@ import java.util.List; import java.util.stream.Collectors; import javax.persistence.EntityManager; -import javax.validation.constraints.NotNull; import org.eclipse.hawkbit.cache.TenancyCacheManager; -import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; -import org.eclipse.hawkbit.report.model.SystemUsageReport; +import org.eclipse.hawkbit.repository.Constants; +import org.eclipse.hawkbit.repository.SystemManagement; +import org.eclipse.hawkbit.repository.TenantStatsManagement; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType; +import org.eclipse.hawkbit.repository.jpa.model.JpaTenantMetaData; 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.eclipse.persistence.config.PersistenceUnitProperties; import org.springframework.beans.factory.annotation.Autowired; @@ -33,19 +37,20 @@ import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.cache.interceptor.SimpleKeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.data.jpa.repository.Modifying; -import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; /** - * Central system management operations of the SP server. + * JPA implementation of {@link SystemManagement}. * */ @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) @Validated -public class SystemManagement { +@Service +public class JpaSystemManagement implements CurrentTenantCacheKeyGenerator, SystemManagement { @Autowired private EntityManager entityManager; @@ -105,14 +110,7 @@ public class SystemManagement { private final ThreadLocal createInitialTenant = new ThreadLocal<>(); - /** - * Calculated system usage statistics, both overall for the entire system - * and per tenant; - * - * @return SystemUsageReport of the current system - */ - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_SYSTEM_ADMIN) + @Override public SystemUsageReport getSystemUsageStatistics() { BigDecimal sumOfArtifacts = (BigDecimal) entityManager @@ -154,35 +152,18 @@ public class SystemManagement { })); } - /** - * Registers the key generator for the {@link #currentTenant()} method - * because this key generator is aware of the {@link #createInitialTenant} - * thread local in case we are currently creating a tenant and insert the - * default distribution set types. - * - * @return the {@link CurrentTenantKeyGenerator} - */ - @Bean + @Override @Transactional(propagation = Propagation.SUPPORTS) - public CurrentTenantKeyGenerator currentTenantKeyGenerator() { + @Bean + public KeyGenerator currentTenantKeyGenerator() { return new CurrentTenantKeyGenerator(); } - /** - * Returns {@link TenantMetaData} of given and current tenant. - * - * 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 - * @return - */ + @Override @Cacheable(value = "tenantMetadata", key = "#tenant.toUpperCase()") @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying - @NotNull - public TenantMetaData getTenantMetadata(@NotNull final String tenant) { + public TenantMetaData getTenantMetadata(final String tenant) { final TenantMetaData result = tenantMetaDataRepository.findByTenantIgnoreCase(tenant); // Create if it does not exist @@ -190,7 +171,7 @@ public class SystemManagement { try { createInitialTenant.set(tenant); cacheManager.getCache("currentTenant").evict(currentTenantKeyGenerator().generate(null, null)); - return tenantMetaDataRepository.save(new TenantMetaData(createStandardSoftwareDataSetup(), tenant)); + return tenantMetaDataRepository.save(new JpaTenantMetaData(createStandardSoftwareDataSetup(), tenant)); } finally { createInitialTenant.remove(); } @@ -199,28 +180,16 @@ public class SystemManagement { return result; } - /** - * - * @return list of all tenant names in the system. - */ - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_SYSTEM_ADMIN + SpringEvalExpressions.HAS_AUTH_OR - + SpringEvalExpressions.IS_SYSTEM_CODE) + @Override public List findTenants() { return tenantMetaDataRepository.findAll().stream().map(md -> md.getTenant()).collect(Collectors.toList()); } - /** - * Deletes all data related to a given tenant. - * - * @param tenant - * to delete - */ + @Override @CacheEvict(value = { "tenantMetadata" }, key = "#tenant.toUpperCase()") @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_SYSTEM_ADMIN) - public void deleteTenant(@NotNull final String tenant) { + public void deleteTenant(final String tenant) { cacheManager.evictCaches(tenant); cacheManager.getCache("currentTenant").evict(currentTenantKeyGenerator().generate(null, null)); tenantAware.runAsTenant(tenant, () -> { @@ -244,13 +213,10 @@ public class SystemManagement { }); } - /** - * @return {@link TenantMetaData} of {@link TenantAware#getCurrentTenant()} - */ + @Override @Cacheable(value = "tenantMetadata", keyGenerator = "tenantKeyGenerator") @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying - @NotNull public TenantMetaData getTenantMetadata() { if (tenantAware.getCurrentTenant() == null) { throw new IllegalStateException("Tenant not set"); @@ -259,13 +225,7 @@ public class SystemManagement { return getTenantMetadata(tenantAware.getCurrentTenant()); } - /** - * Checks if a specific tenant exists. The tenant will not be created lazy. - * - * @param tenant - * the tenant to check - * @return {@code true} in case the tenant exits or {@code false} if not - */ + @Override @Cacheable(value = "currentTenant", keyGenerator = "currentTenantKeyGenerator") // set transaction to not supported, due we call this in // BaseEntity#prePersist methods @@ -288,46 +248,16 @@ public class SystemManagement { return initialTenantCreation; } - /** - * Update call for {@link TenantMetaData}. - * - * @param metaData - * to update - * @return updated {@link TenantMetaData} entity - */ + @Override @CachePut(value = "tenantMetadata", key = "#metaData.tenant.toUpperCase()") @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying - @NotNull - public TenantMetaData updateTenantMetadata(@NotNull final TenantMetaData metaData) { + public TenantMetaData updateTenantMetadata(final TenantMetaData metaData) { if (!tenantMetaDataRepository.exists(metaData.getId())) { throw new EntityNotFoundException("Metadata does not exist: " + metaData.getId()); } - return tenantMetaDataRepository.save(metaData); - } - - private DistributionSetType createStandardSoftwareDataSetup() { - final SoftwareModuleType eclApp = softwareModuleTypeRepository.save(new SoftwareModuleType("application", - "ECL Application", "Edge Controller Linux base application type", 1)); - final SoftwareModuleType eclOs = softwareModuleTypeRepository - .save(new SoftwareModuleType("os", "ECL OS", "Edge Controller Linux operation system image type", 1)); - final SoftwareModuleType eclJvm = softwareModuleTypeRepository.save( - new SoftwareModuleType("runtime", "ECL JVM", "Edge Controller Linux java virtual machine type.", 1)); - - distributionSetTypeRepository.save( - new DistributionSetType("ecl_os", "OS only", "Standard Edge Controller Linux distribution set type.") - .addMandatoryModuleType(eclOs)); - - distributionSetTypeRepository.save(new DistributionSetType("ecl_os_app", "OS with optional app", - "Standard Edge Controller Linux distribution set type. OS only.").addMandatoryModuleType(eclOs) - .addOptionalModuleType(eclApp)); - - return distributionSetTypeRepository - .save(new DistributionSetType("ecl_os_app_jvm", "OS with optional app and jvm", - "Standard Edge Controller Linux distribution set type. OS with optional application.") - .addMandatoryModuleType(eclOs).addOptionalModuleType(eclApp) - .addOptionalModuleType(eclJvm)); + return tenantMetaDataRepository.save((JpaTenantMetaData) metaData); } /** @@ -338,7 +268,7 @@ public class SystemManagement { * currently created and not the one currently in the {@link TenantAware}. * */ - private class CurrentTenantKeyGenerator implements KeyGenerator { + public class CurrentTenantKeyGenerator implements KeyGenerator { @Override // Exception squid:S923 - override @SuppressWarnings({ "squid:S923" }) @@ -352,4 +282,22 @@ public class SystemManagement { initialTenantCreation.toUpperCase()); } } -} + + private DistributionSetType createStandardSoftwareDataSetup() { + final SoftwareModuleType app = softwareModuleTypeRepository + .save(new JpaSoftwareModuleType(Constants.SMT_DEFAULT_APP_KEY, Constants.SMT_DEFAULT_APP_NAME, + "Application Addons", Integer.MAX_VALUE)); + final SoftwareModuleType os = softwareModuleTypeRepository.save(new JpaSoftwareModuleType( + Constants.SMT_DEFAULT_OS_KEY, Constants.SMT_DEFAULT_OS_NAME, "Core firmware or operationg system", 1)); + + distributionSetTypeRepository + .save((JpaDistributionSetType) new JpaDistributionSetType(Constants.DST_DEFAULT_OS_ONLY_KEY, + Constants.DST_DEFAULT_OS_ONLY_NAME, "Default type with Firmware/OS only.") + .addMandatoryModuleType(os)); + + return distributionSetTypeRepository + .save((JpaDistributionSetType) new JpaDistributionSetType(Constants.DST_DEFAULT_OS_WITH_APPS_KEY, + Constants.DST_DEFAULT_OS_WITH_APPS_NAME, "Default type with Firmware/OS and optional app(s).") + .addMandatoryModuleType(os).addOptionalModuleType(app)); + } +} \ No newline at end of file diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTagManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTagManagement.java new file mode 100644 index 000000000..29fbb8a2b --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTagManagement.java @@ -0,0 +1,289 @@ +/** + * 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.jpa; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; + +import org.eclipse.hawkbit.repository.TagFields; +import org.eclipse.hawkbit.repository.TagManagement; +import org.eclipse.hawkbit.repository.eventbus.event.DistributionSetTagCreatedBulkEvent; +import org.eclipse.hawkbit.repository.eventbus.event.DistributionSetTagDeletedEvent; +import org.eclipse.hawkbit.repository.eventbus.event.DistributionSetTagUpdateEvent; +import org.eclipse.hawkbit.repository.eventbus.event.TargetTagCreatedBulkEvent; +import org.eclipse.hawkbit.repository.eventbus.event.TargetTagDeletedEvent; +import org.eclipse.hawkbit.repository.eventbus.event.TargetTagUpdateEvent; +import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; +import org.eclipse.hawkbit.repository.jpa.executor.AfterTransactionCommitExecutor; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag; +import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility; +import org.eclipse.hawkbit.repository.model.DistributionSetTag; +import org.eclipse.hawkbit.repository.model.TargetTag; +import org.eclipse.hawkbit.tenancy.TenantAware; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; + +import com.google.common.eventbus.EventBus; + +/** + * JP>A implementation of {@link TagManagement}. + * + */ +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) +@Validated +@Service +public class JpaTagManagement implements TagManagement { + + @Autowired + private TargetTagRepository targetTagRepository; + + @Autowired + private TargetRepository targetRepository; + + @Autowired + private DistributionSetTagRepository distributionSetTagRepository; + + @Autowired + private DistributionSetRepository distributionSetRepository; + + @Autowired + private EventBus eventBus; + + @Autowired + private TenantAware tenantAware; + + @Autowired + private AfterTransactionCommitExecutor afterCommit; + + @Override + public TargetTag findTargetTag(final String name) { + return targetTagRepository.findByNameEquals(name); + } + + @Override + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public TargetTag createTargetTag(final TargetTag targetTag) { + if (null != targetTag.getId()) { + throw new EntityAlreadyExistsException(); + } + + if (findTargetTag(targetTag.getName()) != null) { + throw new EntityAlreadyExistsException(); + } + + final TargetTag save = targetTagRepository.save((JpaTargetTag) targetTag); + + afterCommit + .afterCommit(() -> eventBus.post(new TargetTagCreatedBulkEvent(tenantAware.getCurrentTenant(), save))); + + return save; + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public List createTargetTags(final Collection tt) { + @SuppressWarnings({ "unchecked", "rawtypes" }) + final Collection targetTags = (Collection) tt; + + targetTags.forEach(tag -> { + if (tag.getId() != null) { + throw new EntityAlreadyExistsException(); + } + }); + + final List save = new ArrayList<>(targetTagRepository.save(targetTags)); + afterCommit + .afterCommit(() -> eventBus.post(new TargetTagCreatedBulkEvent(tenantAware.getCurrentTenant(), save))); + return save; + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public void deleteTargetTag(final String targetTagName) { + final JpaTargetTag tag = targetTagRepository.findByNameEquals(targetTagName); + + final List changed = new LinkedList<>(); + for (final JpaTarget target : targetRepository.findByTag(tag)) { + target.getTags().remove(tag); + changed.add(target); + } + + // save association delete + targetRepository.save(changed); + + // finally delete the tag itself + targetTagRepository.deleteByName(targetTagName); + + afterCommit.afterCommit(() -> eventBus.post(new TargetTagDeletedEvent(tag))); + + } + + @Override + public List findAllTargetTags() { + return new ArrayList<>(targetTagRepository.findAll()); + } + + @Override + public Page findAllTargetTags(final String rsqlParam, final Pageable pageable) { + + final Specification spec = RSQLUtility.parse(rsqlParam, TagFields.class); + return convertTPage(targetTagRepository.findAll(spec, pageable), pageable); + } + + private static Page convertTPage(final Page findAll, final Pageable pageable) { + return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + } + + private static Page convertDsPage(final Page findAll, + final Pageable pageable) { + return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + } + + @Override + public long countTargetTags() { + return targetTagRepository.count(); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public TargetTag updateTargetTag(final TargetTag targetTag) { + checkNotNull(targetTag.getName()); + checkNotNull(targetTag.getId()); + final TargetTag save = targetTagRepository.save((JpaTargetTag) targetTag); + afterCommit.afterCommit(() -> eventBus.post(new TargetTagUpdateEvent(save))); + return save; + } + + @Override + public DistributionSetTag findDistributionSetTag(final String name) { + return distributionSetTagRepository.findByNameEquals(name); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public DistributionSetTag createDistributionSetTag(final DistributionSetTag distributionSetTag) { + if (null != distributionSetTag.getId()) { + throw new EntityAlreadyExistsException(); + } + + if (distributionSetTagRepository.findByNameEquals(distributionSetTag.getName()) != null) { + throw new EntityAlreadyExistsException(); + } + + final DistributionSetTag save = distributionSetTagRepository.save((JpaDistributionSetTag) distributionSetTag); + + afterCommit.afterCommit( + () -> eventBus.post(new DistributionSetTagCreatedBulkEvent(tenantAware.getCurrentTenant(), save))); + return save; + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public List createDistributionSetTags(final Collection dst) { + + @SuppressWarnings({ "rawtypes", "unchecked" }) + final Collection distributionSetTags = (Collection) dst; + + for (final DistributionSetTag dsTag : distributionSetTags) { + if (dsTag.getId() != null) { + throw new EntityAlreadyExistsException(); + } + } + final List save = new ArrayList<>(distributionSetTagRepository.save(distributionSetTags)); + afterCommit.afterCommit( + () -> eventBus.post(new DistributionSetTagCreatedBulkEvent(tenantAware.getCurrentTenant(), save))); + + return save; + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public void deleteDistributionSetTag(final String tagName) { + final JpaDistributionSetTag tag = distributionSetTagRepository.findByNameEquals(tagName); + + final List changed = new LinkedList<>(); + for (final JpaDistributionSet set : distributionSetRepository.findByTag(tag)) { + set.getTags().remove(tag); + changed.add(set); + } + + // save association delete + distributionSetRepository.save(changed); + + distributionSetTagRepository.deleteByName(tagName); + + afterCommit.afterCommit(() -> eventBus.post(new DistributionSetTagDeletedEvent(tag))); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public DistributionSetTag updateDistributionSetTag(final DistributionSetTag distributionSetTag) { + checkNotNull(distributionSetTag.getName()); + checkNotNull(distributionSetTag.getId()); + final DistributionSetTag save = distributionSetTagRepository.save((JpaDistributionSetTag) distributionSetTag); + afterCommit.afterCommit(() -> eventBus.post(new DistributionSetTagUpdateEvent(save))); + + return save; + } + + @Override + public List findAllDistributionSetTags() { + return new ArrayList<>(distributionSetTagRepository.findAll()); + } + + @Override + public TargetTag findTargetTagById(final Long id) { + return targetTagRepository.findOne(id); + } + + @Override + public DistributionSetTag findDistributionSetTagById(final Long id) { + return distributionSetTagRepository.findOne(id); + } + + @Override + public Page findAllTargetTags(final Pageable pageable) { + return convertTPage(targetTagRepository.findAll(pageable), pageable); + } + + @Override + public Page findAllDistributionSetTags(final Pageable pageable) { + return convertDsPage(distributionSetTagRepository.findAll(pageable), pageable); + } + + @Override + public Page findAllDistributionSetTags(final String rsqlParam, final Pageable pageable) { + final Specification spec = RSQLUtility.parse(rsqlParam, TagFields.class); + + return convertDsPage(distributionSetTagRepository.findAll(spec, pageable), pageable); + } + +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTargetFilterQueryManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTargetFilterQueryManagement.java new file mode 100644 index 000000000..f418f5f4b --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTargetFilterQueryManagement.java @@ -0,0 +1,120 @@ +/** + * 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.jpa; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.hawkbit.repository.TargetFields; +import org.eclipse.hawkbit.repository.TargetFilterQueryManagement; +import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetFilterQuery; +import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility; +import org.eclipse.hawkbit.repository.jpa.specifications.SpecificationsBuilder; +import org.eclipse.hawkbit.repository.jpa.specifications.TargetFilterQuerySpecification; +import org.eclipse.hawkbit.repository.model.TargetFilterQuery; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.data.jpa.domain.Specifications; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.Assert; +import org.springframework.validation.annotation.Validated; + +import com.google.common.base.Strings; + +/** + * JPA implementation of {@link TargetFilterQueryManagement}. + * + */ +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) +@Validated +@Service +public class JpaTargetFilterQueryManagement implements TargetFilterQueryManagement { + + @Autowired + private TargetFilterQueryRepository targetFilterQueryRepository; + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public TargetFilterQuery createTargetFilterQuery(final TargetFilterQuery customTargetFilter) { + + if (targetFilterQueryRepository.findByName(customTargetFilter.getName()) != null) { + throw new EntityAlreadyExistsException(customTargetFilter.getName()); + } + return targetFilterQueryRepository.save((JpaTargetFilterQuery) customTargetFilter); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public void deleteTargetFilterQuery(final Long targetFilterQueryId) { + targetFilterQueryRepository.delete(targetFilterQueryId); + } + + @Override + public Page findAllTargetFilterQuery(final Pageable pageable) { + return convertPage(targetFilterQueryRepository.findAll(pageable), pageable); + } + + private static Page convertPage(final Page findAll, + final Pageable pageable) { + return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + } + + @Override + public Page findTargetFilterQueryByFilters(final Pageable pageable, final String name) { + final List> specList = new ArrayList<>(); + if (!Strings.isNullOrEmpty(name)) { + specList.add(TargetFilterQuerySpecification.likeName(name)); + } + return convertPage(findTargetFilterQueryByCriteriaAPI(pageable, specList), pageable); + } + + private Page findTargetFilterQueryByCriteriaAPI(final Pageable pageable, + final List> specList) { + if (specList == null || specList.isEmpty()) { + return targetFilterQueryRepository.findAll(pageable); + } + + final Specifications specs = SpecificationsBuilder.combineWithAnd(specList); + return targetFilterQueryRepository.findAll(specs, pageable); + } + + @Override + public TargetFilterQuery findTargetFilterQueryByName(final String targetFilterQueryName) { + return targetFilterQueryRepository.findByName(targetFilterQueryName); + } + + @Override + public TargetFilterQuery findTargetFilterQueryById(final Long targetFilterQueryId) { + return targetFilterQueryRepository.findOne(targetFilterQueryId); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public TargetFilterQuery updateTargetFilterQuery(final TargetFilterQuery targetFilterQuery) { + Assert.notNull(targetFilterQuery.getId()); + return targetFilterQueryRepository.save((JpaTargetFilterQuery) targetFilterQuery); + } + + @Override + public boolean verifyTargetFilterQuerySyntax(final String query) { + RSQLUtility.parse(query, TargetFields.class); + return true; + } + +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTargetManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTargetManagement.java new file mode 100644 index 000000000..892ddc771 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTargetManagement.java @@ -0,0 +1,674 @@ +/** + * 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.jpa; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +import javax.annotation.PreDestroy; +import javax.persistence.EntityManager; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Expression; +import javax.persistence.criteria.Join; +import javax.persistence.criteria.JoinType; +import javax.persistence.criteria.Order; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; + +import org.eclipse.hawkbit.repository.TargetFields; +import org.eclipse.hawkbit.repository.TargetManagement; +import org.eclipse.hawkbit.repository.eventbus.event.TargetTagAssigmentResultEvent; +import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; +import org.eclipse.hawkbit.repository.jpa.configuration.Constants; +import org.eclipse.hawkbit.repository.jpa.executor.AfterTransactionCommitExecutor; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet_; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetInfo; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetInfo_; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget_; +import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility; +import org.eclipse.hawkbit.repository.jpa.specifications.SpecificationsBuilder; +import org.eclipse.hawkbit.repository.jpa.specifications.TargetSpecifications; +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.TargetTag; +import org.eclipse.hawkbit.repository.model.TargetTagAssignmentResult; +import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Slice; +import org.springframework.data.domain.SliceImpl; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.Assert; +import org.springframework.validation.annotation.Validated; + +import com.google.common.base.Strings; +import com.google.common.collect.Lists; +import com.google.common.eventbus.EventBus; + +/** + * JPA implementation of {@link TargetManagement}. + * + */ +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) +@Validated +@Service +public class JpaTargetManagement implements TargetManagement { + + @Autowired + private EntityManager entityManager; + + @Autowired + private TargetRepository targetRepository; + + @Autowired + private TargetTagRepository targetTagRepository; + + @Autowired + private TargetInfoRepository targetInfoRepository; + + @Autowired + private NoCountPagingRepository criteriaNoCountDao; + + @Autowired + private EventBus eventBus; + + @Autowired + private AfterTransactionCommitExecutor afterCommit; + + @Override + public Target findTargetByControllerID(final String controllerId) { + return targetRepository.findByControllerId(controllerId); + } + + @Override + public Target findTargetByControllerIDWithDetails(final String controllerId) { + final Target result = targetRepository.findByControllerId(controllerId); + // load lazy relations + if (result != null) { + result.getTargetInfo().getControllerAttributes().size(); + if (result.getTargetInfo() != null && result.getTargetInfo().getInstalledDistributionSet() != null) { + result.getTargetInfo().getInstalledDistributionSet().getName(); + result.getTargetInfo().getInstalledDistributionSet().getModules().size(); + } + if (result.getAssignedDistributionSet() != null) { + result.getAssignedDistributionSet().getName(); + result.getAssignedDistributionSet().getModules().size(); + } + } + return result; + } + + @Override + public List findTargetByControllerID(final Collection controllerIDs) { + return new ArrayList<>(targetRepository + .findAll(TargetSpecifications.byControllerIdWithStatusAndAssignedInJoin(controllerIDs))); + } + + @Override + public Long countTargetsAll() { + return targetRepository.count(); + } + + @Override + public Slice findTargetsAll(final Pageable pageable) { + // workarround - no join fetch allowed that is why we need specification + // instead of query for + // count() of Pageable + final Specification spec = (root, query, cb) -> { + if (!query.getResultType().isAssignableFrom(Long.class)) { + root.fetch(JpaTarget_.targetInfo); + } + return cb.conjunction(); + }; + return convertPage(criteriaNoCountDao.findAll(spec, pageable, JpaTarget.class), pageable); + } + + @Override + public Slice findTargetsAll(final TargetFilterQuery targetFilterQuery, final Pageable pageable) { + return findTargetsBySpec(RSQLUtility.parse(targetFilterQuery.getQuery(), TargetFields.class), pageable); + } + + @Override + public Page findTargetsAll(final String targetFilterQuery, final Pageable pageable) { + return findTargetsBySpec(RSQLUtility.parse(targetFilterQuery, TargetFields.class), pageable); + } + + private Page findTargetsBySpec(final Specification spec, final Pageable pageable) { + return convertPage(targetRepository.findAll(spec, pageable), pageable); + } + + @Override + public List findTargetsByControllerIDsWithTags(final List controllerIDs) { + final List> partition = Lists.partition(controllerIDs, Constants.MAX_ENTRIES_IN_STATEMENT); + return partition.stream() + .map(ids -> targetRepository.findAll(TargetSpecifications.byControllerIdWithStatusAndTagsInJoin(ids))) + .flatMap(t -> t.stream()).collect(Collectors.toList()); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public Target updateTarget(final Target target) { + Assert.notNull(target.getId()); + + final JpaTarget toUpdate = (JpaTarget) target; + toUpdate.setNew(false); + return targetRepository.save(toUpdate); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public List updateTargets(final Collection targets) { + + @SuppressWarnings({ "unchecked", "rawtypes" }) + final Collection toUpdate = (Collection) targets; + + toUpdate.forEach(target -> target.setNew(false)); + + return new ArrayList<>(targetRepository.save(toUpdate)); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public void deleteTargets(final Long... targetIDs) { + // we need to select the target IDs first to check the if the targetIDs + // belonging to the + // tenant! Delete statement are not automatically enhanced with the + // @FilterDef of the + // hibernate session. + final List targetsForCurrentTenant = targetRepository.findAll(Lists.newArrayList(targetIDs)).stream() + .map(Target::getId).collect(Collectors.toList()); + if (!targetsForCurrentTenant.isEmpty()) { + targetInfoRepository.deleteByTargetIdIn(targetsForCurrentTenant); + targetRepository.deleteByIdIn(targetsForCurrentTenant); + } + } + + @Override + public Page findTargetByAssignedDistributionSet(final Long distributionSetID, final Pageable pageReq) { + return targetRepository.findByAssignedDistributionSetId(pageReq, distributionSetID); + } + + @Override + public Page findTargetByAssignedDistributionSet(final Long distributionSetID, final String rsqlParam, + final Pageable pageReq) { + + final Specification spec = RSQLUtility.parse(rsqlParam, TargetFields.class); + + return convertPage( + targetRepository + .findAll((Specification) (root, query, + cb) -> cb.and(TargetSpecifications.hasAssignedDistributionSet(distributionSetID) + .toPredicate(root, query, cb), spec.toPredicate(root, query, cb)), + pageReq), + pageReq); + } + + private static Page convertPage(final Page findAll, final Pageable pageable) { + return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, findAll.getTotalElements()); + } + + private static Slice convertPage(final Slice findAll, final Pageable pageable) { + return new PageImpl<>(new ArrayList<>(findAll.getContent()), pageable, 0); + } + + @Override + public Page findTargetByInstalledDistributionSet(final Long distributionSetID, final Pageable pageReq) { + return targetRepository.findByTargetInfoInstalledDistributionSetId(pageReq, distributionSetID); + } + + @Override + public Page findTargetByInstalledDistributionSet(final Long distributionSetId, final String rsqlParam, + final Pageable pageable) { + + final Specification spec = RSQLUtility.parse(rsqlParam, TargetFields.class); + + return convertPage( + targetRepository + .findAll((Specification) (root, query, + cb) -> cb.and(TargetSpecifications.hasInstalledDistributionSet(distributionSetId) + .toPredicate(root, query, cb), spec.toPredicate(root, query, cb)), + pageable), + pageable); + } + + @Override + public Page findTargetByUpdateStatus(final Pageable pageable, final TargetUpdateStatus status) { + return targetRepository.findByTargetInfoUpdateStatus(pageable, status); + } + + @Override + public Slice findTargetByFilters(final Pageable pageable, final Collection status, + final String searchText, final Long installedOrAssignedDistributionSetId, + final Boolean selectTargetWithNoTag, final String... tagNames) { + final List> specList = buildSpecificationList(status, searchText, + installedOrAssignedDistributionSetId, selectTargetWithNoTag, true, tagNames); + return findByCriteriaAPI(pageable, specList); + } + + @Override + public Long countTargetByFilters(final Collection status, final String searchText, + final Long installedOrAssignedDistributionSetId, final Boolean selectTargetWithNoTag, + final String... tagNames) { + final List> specList = buildSpecificationList(status, searchText, + installedOrAssignedDistributionSetId, selectTargetWithNoTag, true, tagNames); + return countByCriteriaAPI(specList); + } + + private static List> buildSpecificationList(final Collection status, + final String searchText, final Long installedOrAssignedDistributionSetId, + final Boolean selectTargetWithNoTag, final boolean fetch, final String... tagNames) { + final List> specList = new ArrayList<>(); + if (status != null && !status.isEmpty()) { + specList.add(TargetSpecifications.hasTargetUpdateStatus(status, fetch)); + } + if (installedOrAssignedDistributionSetId != null) { + specList.add( + TargetSpecifications.hasInstalledOrAssignedDistributionSet(installedOrAssignedDistributionSetId)); + } + if (!Strings.isNullOrEmpty(searchText)) { + specList.add(TargetSpecifications.likeNameOrDescriptionOrIp(searchText)); + } + if (selectTargetWithNoTag != null && (selectTargetWithNoTag || (tagNames != null && tagNames.length > 0))) { + specList.add(TargetSpecifications.hasTags(tagNames, selectTargetWithNoTag)); + } + return specList; + } + + private Slice findByCriteriaAPI(final Pageable pageable, final List> specList) { + if (specList == null || specList.isEmpty()) { + return convertPage(criteriaNoCountDao.findAll(pageable, JpaTarget.class), pageable); + } + return convertPage( + criteriaNoCountDao.findAll(SpecificationsBuilder.combineWithAnd(specList), pageable, JpaTarget.class), + pageable); + } + + private Long countByCriteriaAPI(final List> specList) { + if (specList == null || specList.isEmpty()) { + return targetRepository.count(); + } + + return targetRepository.count(SpecificationsBuilder.combineWithAnd(specList)); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public TargetTagAssignmentResult toggleTagAssignment(final Collection targets, final TargetTag tag) { + return toggleTagAssignment( + targets.stream().map(target -> target.getControllerId()).collect(Collectors.toList()), tag.getName()); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public TargetTagAssignmentResult toggleTagAssignment(final Collection targetIds, final String tagName) { + final TargetTag tag = targetTagRepository.findByNameEquals(tagName); + final List alreadyAssignedTargets = targetRepository.findByTagNameAndControllerIdIn(tagName, targetIds); + final List allTargets = targetRepository + .findAll(TargetSpecifications.byControllerIdWithStatusAndTagsInJoin(targetIds)); + + // all are already assigned -> unassign + if (alreadyAssignedTargets.size() == allTargets.size()) { + alreadyAssignedTargets.forEach(target -> target.getTags().remove(tag)); + final TargetTagAssignmentResult result = new TargetTagAssignmentResult(0, 0, alreadyAssignedTargets.size(), + Collections.emptyList(), alreadyAssignedTargets, tag); + + afterCommit.afterCommit(() -> eventBus.post(new TargetTagAssigmentResultEvent(result))); + return result; + } + + allTargets.removeAll(alreadyAssignedTargets); + // some or none are assigned -> assign + allTargets.forEach(target -> target.getTags().add(tag)); + final TargetTagAssignmentResult result = new TargetTagAssignmentResult(alreadyAssignedTargets.size(), + allTargets.size(), 0, new ArrayList<>(targetRepository.save(allTargets)), Collections.emptyList(), tag); + + afterCommit.afterCommit(() -> eventBus.post(new TargetTagAssigmentResultEvent(result))); + + // no reason to persist the tag + entityManager.detach(tag); + return result; + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public List assignTag(final Collection targetIds, final TargetTag tag) { + final List allTargets = targetRepository + .findAll(TargetSpecifications.byControllerIdWithStatusAndTagsInJoin(targetIds)); + + allTargets.forEach(target -> target.getTags().add(tag)); + final List save = new ArrayList<>(targetRepository.save(allTargets)); + + afterCommit.afterCommit(() -> { + final TargetTagAssignmentResult assigmentResult = new TargetTagAssignmentResult(0, save.size(), 0, save, + Collections.emptyList(), tag); + eventBus.post(new TargetTagAssigmentResultEvent(assigmentResult)); + }); + + return save; + } + + private List unAssignTag(final Collection targets, final TargetTag tag) { + final Collection toUnassign = (Collection) targets; + + toUnassign.forEach(target -> target.getTags().remove(tag)); + + final List save = new ArrayList<>(targetRepository.save(toUnassign)); + afterCommit.afterCommit(() -> { + final TargetTagAssignmentResult assigmentResult = new TargetTagAssignmentResult(0, 0, save.size(), + Collections.emptyList(), save, tag); + eventBus.post(new TargetTagAssigmentResultEvent(assigmentResult)); + }); + return save; + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public List unAssignAllTargetsByTag(final TargetTag tag) { + return unAssignTag(tag.getAssignedToTargets(), tag); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public Target unAssignTag(final String controllerID, final TargetTag targetTag) { + final List allTargets = new ArrayList<>(targetRepository + .findAll(TargetSpecifications.byControllerIdWithStatusAndTagsInJoin(Arrays.asList(controllerID)))); + final List unAssignTag = unAssignTag(allTargets, targetTag); + return unAssignTag.isEmpty() ? null : unAssignTag.get(0); + } + + @Override + public Slice findTargetsAllOrderByLinkedDistributionSet(final Pageable pageable, + final Long orderByDistributionId, final Long filterByDistributionId, + final Collection filterByStatus, final String filterBySearchText, + final Boolean selectTargetWithNoTag, final String... filterByTagNames) { + final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); + final CriteriaQuery query = cb.createQuery(JpaTarget.class); + final Root targetRoot = query.from(JpaTarget.class); + + // necessary joins for the select + final Join targetInfo = (Join) targetRoot + .fetch(JpaTarget_.targetInfo, JoinType.LEFT); + + // select case expression to retrieve the case value as a column to be + // able to order based on + // this column, installed first,... + final Expression selectCase = cb.selectCase() + .when(cb.equal(targetInfo.get(JpaTargetInfo_.installedDistributionSet).get(JpaDistributionSet_.id), + orderByDistributionId), 1) + .when(cb.equal(targetRoot.get(JpaTarget_.assignedDistributionSet).get(JpaDistributionSet_.id), + orderByDistributionId), 2) + .otherwise(100); + // multiselect statement order by the select case and controllerId + query.distinct(true); + // build the specifications and then to predicates necessary by the + // given filters + final Predicate[] specificationsForMultiSelect = specificationsToPredicate( + buildSpecificationList(filterByStatus, filterBySearchText, filterByDistributionId, + selectTargetWithNoTag, true, filterByTagNames), + targetRoot, query, cb); + + // if we have some predicates then add it to the where clause of the + // multiselect + if (specificationsForMultiSelect.length > 0) { + query.where(specificationsForMultiSelect); + } + // add the order to the multi select first based on the selectCase + query.orderBy(cb.asc(selectCase), cb.desc(targetRoot.get(JpaTarget_.id))); + // the result is a Object[] due the fact that the selectCase is an extra + // column, so it cannot + // be mapped directly to a Target entity because the selectCase is not a + // attribute of the + // Target entity, the the Object array contains the Target on the first + // index (case of the + // multiselect order) of the array and + // the 2nd contains the selectCase int value. + final int pageSize = pageable.getPageSize(); + final List resultList = entityManager.createQuery(query).setFirstResult(pageable.getOffset()) + .setMaxResults(pageSize + 1).getResultList(); + final boolean hasNext = resultList.size() > pageSize; + return new SliceImpl<>(new ArrayList<>(resultList), pageable, hasNext); + } + + private static Predicate[] specificationsToPredicate(final List> specifications, + final Root root, final CriteriaQuery query, final CriteriaBuilder cb) { + final Predicate[] predicates = new Predicate[specifications.size()]; + for (int index = 0; index < predicates.length; index++) { + predicates[index] = specifications.get(index).toPredicate(root, query, cb); + } + return predicates; + } + + @Override + public Long countTargetByAssignedDistributionSet(final Long distId) { + return targetRepository.countByAssignedDistributionSetId(distId); + } + + @Override + public Long countTargetByInstalledDistributionSet(final Long distId) { + return targetRepository.countByTargetInfoInstalledDistributionSetId(distId); + } + + @Override + public List findAllTargetIds() { + final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); + final CriteriaQuery query = cb.createQuery(TargetIdName.class); + final Root targetRoot = query.from(JpaTarget.class); + return entityManager.createQuery(query.multiselect(targetRoot.get(JpaTarget_.id), + targetRoot.get(JpaTarget_.controllerId), targetRoot.get(JpaTarget_.name))).getResultList(); + + } + + @Override + public List findAllTargetIdsByFilters(final Pageable pageRequest, + final Collection filterByStatus, final String filterBySearchText, + final Long installedOrAssignedDistributionSetId, final Boolean selectTargetWithNoTag, + final String... filterByTagNames) { + final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); + final CriteriaQuery query = cb.createQuery(Object[].class); + final Root targetRoot = query.from(JpaTarget.class); + List resultList; + + String sortProperty = JpaTarget_.id.getName(); + if (pageRequest.getSort() != null && pageRequest.getSort().iterator().hasNext()) { + sortProperty = pageRequest.getSort().iterator().next().getProperty(); + } + + final CriteriaQuery multiselect = query.multiselect(targetRoot.get(JpaTarget_.id), + targetRoot.get(JpaTarget_.controllerId), targetRoot.get(JpaTarget_.name), targetRoot.get(sortProperty)); + + final Predicate[] specificationsForMultiSelect = specificationsToPredicate( + buildSpecificationList(filterByStatus, filterBySearchText, installedOrAssignedDistributionSetId, + selectTargetWithNoTag, false, filterByTagNames), + targetRoot, multiselect, cb); + + // if we have some predicates then add it to the where clause of the + // multiselect + if (specificationsForMultiSelect.length > 0) { + multiselect.where(specificationsForMultiSelect); + } + + resultList = getTargetIdNameResultSet(pageRequest, cb, targetRoot, multiselect); + return resultList.parallelStream().map(o -> new TargetIdName((long) o[0], o[1].toString(), o[2].toString())) + .collect(Collectors.toList()); + } + + @Override + public List findAllTargetIdsByTargetFilterQuery(final Pageable pageRequest, + final TargetFilterQuery targetFilterQuery) { + final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); + final CriteriaQuery query = cb.createQuery(Object[].class); + final Root targetRoot = query.from(JpaTarget.class); + + String sortProperty = JpaTarget_.id.getName(); + if (pageRequest.getSort() != null && pageRequest.getSort().iterator().hasNext()) { + sortProperty = pageRequest.getSort().iterator().next().getProperty(); + } + + final CriteriaQuery multiselect = query.multiselect(targetRoot.get(JpaTarget_.id), + targetRoot.get(JpaTarget_.controllerId), targetRoot.get(JpaTarget_.name), targetRoot.get(sortProperty)); + + final Specification spec = RSQLUtility.parse(targetFilterQuery.getQuery(), TargetFields.class); + final List> specList = new ArrayList<>(); + specList.add(spec); + + final Predicate[] specificationsForMultiSelect = specificationsToPredicate(specList, targetRoot, multiselect, + cb); + + // if we have some predicates then add it to the where clause of the + // multiselect + if (specificationsForMultiSelect.length > 0) { + multiselect.where(specificationsForMultiSelect); + } + final List resultList = getTargetIdNameResultSet(pageRequest, cb, targetRoot, multiselect); + return resultList.parallelStream().map(o -> new TargetIdName((long) o[0], o[1].toString(), o[2].toString())) + .collect(Collectors.toList()); + } + + @PreDestroy + void destroy() { + eventBus.unregister(this); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + @CacheEvict(value = { "targetsCreatedOverPeriod" }, allEntries = true) + public Target createTarget(final Target t, final TargetUpdateStatus status, final Long lastTargetQuery, + final URI address) { + final JpaTarget target = (JpaTarget) t; + + if (targetRepository.findByControllerId(target.getControllerId()) != null) { + throw new EntityAlreadyExistsException(target.getControllerId()); + } + + target.setNew(true); + final JpaTarget savedTarget = targetRepository.save(target); + final JpaTargetInfo targetInfo = (JpaTargetInfo) savedTarget.getTargetInfo(); + targetInfo.setUpdateStatus(status); + if (lastTargetQuery != null) { + targetInfo.setLastTargetQuery(lastTargetQuery); + } + if (address != null) { + targetInfo.setAddress(address.toString()); + } + targetInfo.setNew(true); + final Target targetToReturn = targetInfoRepository.save(targetInfo).getTarget(); + targetInfo.setNew(false); + return targetToReturn; + + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + @CacheEvict(value = { "targetsCreatedOverPeriod" }, allEntries = true) + public Target createTarget(final Target target) { + return createTarget(target, TargetUpdateStatus.UNKNOWN, null, null); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public List createTargets(final Collection targets) { + if (!targets.isEmpty() && targetRepository.countByControllerIdIn( + targets.stream().map(target -> target.getControllerId()).collect(Collectors.toList())) > 0) { + throw new EntityAlreadyExistsException(); + } + final List savedTargets = new ArrayList<>(); + for (final Target t : targets) { + final Target myTarget = createTarget(t); + savedTargets.add(myTarget); + } + return savedTargets; + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public List createTargets(final Collection targets, final TargetUpdateStatus status, + final Long lastTargetQuery, final URI address) { + if (targetRepository.countByControllerIdIn( + targets.stream().map(target -> target.getControllerId()).collect(Collectors.toList())) > 0) { + throw new EntityAlreadyExistsException(); + } + final List savedTargets = new ArrayList<>(); + for (final Target t : targets) { + final Target myTarget = createTarget(t, status, lastTargetQuery, address); + savedTargets.add(myTarget); + } + return savedTargets; + } + + @Override + public List findTargetsByTag(final String tagName) { + final JpaTargetTag tag = targetTagRepository.findByNameEquals(tagName); + return new ArrayList<>(targetRepository.findByTag(tag)); + } + + @Override + public Long countTargetByTargetFilterQuery(final TargetFilterQuery targetFilterQuery) { + final Specification specs = RSQLUtility.parse(targetFilterQuery.getQuery(), TargetFields.class); + return targetRepository.count(specs); + } + + @Override + public Long countTargetByTargetFilterQuery(final String targetFilterQuery) { + final Specification specs = RSQLUtility.parse(targetFilterQuery, TargetFields.class); + return targetRepository.count(specs); + } + + private List getTargetIdNameResultSet(final Pageable pageRequest, final CriteriaBuilder cb, + final Root targetRoot, final CriteriaQuery multiselect) { + List resultList; + if (pageRequest.getSort() != null) { + final List orders = new ArrayList<>(); + final Sort sort = pageRequest.getSort(); + for (final Sort.Order sortOrder : sort) { + if (sortOrder.getDirection() == Direction.ASC) { + orders.add(cb.asc(targetRoot.get(sortOrder.getProperty()))); + } else { + orders.add(cb.desc(targetRoot.get(sortOrder.getProperty()))); + } + } + multiselect.orderBy(orders); + resultList = entityManager.createQuery(multiselect).setFirstResult(pageRequest.getOffset()) + .setMaxResults(pageRequest.getPageSize()).getResultList(); + } else { + resultList = entityManager.createQuery(multiselect).getResultList(); + } + return resultList; + } + +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTenantConfigurationManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTenantConfigurationManagement.java new file mode 100644 index 000000000..9f65091a4 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTenantConfigurationManagement.java @@ -0,0 +1,172 @@ +/** + * 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.jpa; + +import org.eclipse.hawkbit.repository.TenantConfigurationManagement; +import org.eclipse.hawkbit.repository.jpa.model.JpaTenantConfiguration; +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.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.context.ApplicationContext; +import org.springframework.context.EnvironmentAware; +import org.springframework.core.convert.support.ConfigurableConversionService; +import org.springframework.core.convert.support.DefaultConversionService; +import org.springframework.core.env.Environment; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; + +/** + * Central tenant configuration management operations of the SP server. + */ +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) +@Validated +@Service +public class JpaTenantConfigurationManagement implements EnvironmentAware, TenantConfigurationManagement { + + @Autowired + private TenantConfigurationRepository tenantConfigurationRepository; + + @Autowired + private ApplicationContext applicationContext; + + private static final ConfigurableConversionService conversionService = new DefaultConversionService(); + + private Environment environment; + + @Override + @Cacheable(value = "tenantConfiguration", key = "#configurationKey.getKeyName()") + public TenantConfigurationValue getConfigurationValue(final TenantConfigurationKey configurationKey, + final Class propertyType) { + validateTenantConfigurationDataType(configurationKey, propertyType); + + final TenantConfiguration tenantConfiguration = tenantConfigurationRepository + .findByKey(configurationKey.getKeyName()); + + return buildTenantConfigurationValueByKey(configurationKey, propertyType, tenantConfiguration); + } + + /** + * Validates the data type of the tenant configuration. If it is possible to + * cast to the given data type. + * + * @param configurationKey + * the key + * @param propertyType + * the class + */ + static void validateTenantConfigurationDataType(final TenantConfigurationKey configurationKey, + final Class propertyType) { + if (!configurationKey.getDataType().isAssignableFrom(propertyType)) { + throw new TenantConfigurationValidatorException( + String.format("Cannot parse the database value of type %s into the type %s.", + configurationKey.getDataType(), propertyType)); + } + } + + @Override + public TenantConfigurationValue buildTenantConfigurationValueByKey( + final TenantConfigurationKey configurationKey, final Class propertyType, + final TenantConfiguration tenantConfiguration) { + if (tenantConfiguration != null) { + return TenantConfigurationValue. builder().global(false).createdBy(tenantConfiguration.getCreatedBy()) + .createdAt(tenantConfiguration.getCreatedAt()) + .lastModifiedAt(tenantConfiguration.getLastModifiedAt()) + .lastModifiedBy(tenantConfiguration.getLastModifiedBy()) + .value(conversionService.convert(tenantConfiguration.getValue(), propertyType)).build(); + + } else if (configurationKey.getDefaultKeyName() != null) { + + return TenantConfigurationValue. builder().global(true).createdBy(null).createdAt(null) + .lastModifiedAt(null).lastModifiedBy(null) + .value(getGlobalConfigurationValue(configurationKey, propertyType)).build(); + } + return null; + } + + @Override + public TenantConfigurationValue getConfigurationValue(final TenantConfigurationKey configurationKey) { + return getConfigurationValue(configurationKey, configurationKey.getDataType()); + } + + @Override + public T getGlobalConfigurationValue(final TenantConfigurationKey configurationKey, + final Class propertyType) { + + if (!configurationKey.getDataType().isAssignableFrom(propertyType)) { + throw new TenantConfigurationValidatorException( + String.format("Cannot parse the database value of type %s into the type %s.", + configurationKey.getDataType(), propertyType)); + } + + final T valueInProperties = environment.getProperty(configurationKey.getDefaultKeyName(), propertyType); + + if (valueInProperties == null) { + return conversionService.convert(configurationKey.getDefaultValue(), propertyType); + } + + return valueInProperties; + } + + @Override + @CacheEvict(value = "tenantConfiguration", key = "#configurationKey.getKeyName()") + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + @Modifying + public TenantConfigurationValue addOrUpdateConfiguration(final TenantConfigurationKey configurationKey, + final T value) { + + if (!configurationKey.getDataType().isAssignableFrom(value.getClass())) { + throw new TenantConfigurationValidatorException(String.format( + "Cannot parse the value %s of type %s into the type %s defined by the configuration key.", value, + value.getClass(), configurationKey.getDataType())); + } + + configurationKey.validate(applicationContext, value); + + JpaTenantConfiguration tenantConfiguration = tenantConfigurationRepository + .findByKey(configurationKey.getKeyName()); + + if (tenantConfiguration == null) { + tenantConfiguration = new JpaTenantConfiguration(configurationKey.getKeyName(), value.toString()); + } else { + tenantConfiguration.setValue(value.toString()); + } + + final JpaTenantConfiguration updatedTenantConfiguration = tenantConfigurationRepository + .save(tenantConfiguration); + + @SuppressWarnings("unchecked") + final Class clazzT = (Class) value.getClass(); + + return TenantConfigurationValue. builder().global(false).createdBy(updatedTenantConfiguration.getCreatedBy()) + .createdAt(updatedTenantConfiguration.getCreatedAt()) + .lastModifiedAt(updatedTenantConfiguration.getLastModifiedAt()) + .lastModifiedBy(updatedTenantConfiguration.getLastModifiedBy()) + .value(conversionService.convert(updatedTenantConfiguration.getValue(), clazzT)).build(); + } + + @Override + @CacheEvict(value = "tenantConfiguration", key = "#configurationKey.getKeyName()") + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + @Modifying + public void deleteConfiguration(final TenantConfigurationKey configurationKey) { + tenantConfigurationRepository.deleteByKey(configurationKey.getKeyName()); + } + + @Override + public void setEnvironment(final Environment environment) { + this.environment = environment; + } +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantStatsManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTenantStatsManagement.java similarity index 71% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantStatsManagement.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTenantStatsManagement.java index 9d5bed905..e3866a8ad 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantStatsManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTenantStatsManagement.java @@ -6,22 +6,26 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import java.util.Optional; -import org.eclipse.hawkbit.report.model.TenantUsage; +import org.eclipse.hawkbit.repository.TenantStatsManagement; +import org.eclipse.hawkbit.repository.report.model.TenantUsage; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; /** - * Management service for stats of a single tenant. + * Management service for statistics of a single tenant. * */ @Validated -public class TenantStatsManagement { +@Service +public class JpaTenantStatsManagement implements TenantStatsManagement { @Autowired private TargetRepository targetRepository; @@ -32,16 +36,8 @@ public class TenantStatsManagement { @Autowired private ActionRepository actionRepository; - /** - * 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 - */ - @Transactional(propagation = Propagation.REQUIRES_NEW) + @Override + @Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_UNCOMMITTED) public TenantUsage getStatsOfTenant(final String tenant) { final TenantUsage result = new TenantUsage(tenant); diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/LocalArtifactRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/LocalArtifactRepository.java similarity index 90% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/LocalArtifactRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/LocalArtifactRepository.java index 4c106957d..e6eb62a27 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/LocalArtifactRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/LocalArtifactRepository.java @@ -6,11 +6,12 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import java.util.List; import java.util.Optional; +import org.eclipse.hawkbit.repository.jpa.model.JpaLocalArtifact; import org.eclipse.hawkbit.repository.model.LocalArtifact; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -23,7 +24,7 @@ import org.springframework.transaction.annotation.Transactional; * */ @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) -public interface LocalArtifactRepository extends BaseEntityRepository { +public interface LocalArtifactRepository extends BaseEntityRepository { /** * Counts artifacts size where the related software module is not @@ -31,7 +32,7 @@ public interface LocalArtifactRepository extends BaseEntityRepository getSumOfUndeletedArtifactSize(); /** @@ -60,7 +61,7 @@ public interface LocalArtifactRepository extends BaseEntityRepository, JpaSpecificationExecutor { + extends BaseEntityRepository, JpaSpecificationExecutor { /** * Retrieves all {@link RolloutGroup} referring a specific rollout in the @@ -36,7 +38,7 @@ public interface RolloutGroupRepository * the rollout the rolloutgroups belong to * @return the rollout groups belonging to a rollout ordered by ID ASC. */ - List findByRolloutOrderByIdAsc(final Rollout rollout); + List findByRolloutOrderByIdAsc(final JpaRollout rollout); /** * Retrieves all {@link RolloutGroup} referring a specific rollout in a @@ -48,7 +50,7 @@ public interface RolloutGroupRepository * the status of the rollout groups * @return the rollout groups belonging to a rollout in a specific status */ - List findByRolloutAndStatus(final Rollout rollout, final RolloutGroupStatus status); + List findByRolloutAndStatus(final Rollout rollout, final RolloutGroupStatus status); /** * Counts all {@link RolloutGroup} referring a specific rollout. @@ -57,7 +59,7 @@ public interface RolloutGroupRepository * the rollout the rolloutgroup belong to * @return the count of the rollout groups for a specific rollout */ - Long countByRollout(final Rollout rollout); + Long countByRollout(final JpaRollout rollout); /** * Counts all {@link RolloutGroup} referring a specific rollout in a @@ -70,7 +72,7 @@ public interface RolloutGroupRepository * @return the count of rollout groups belonging to a rollout in a specific * status */ - Long countByRolloutAndStatus(Rollout rollout, RolloutGroupStatus rolloutGroupStatus); + Long countByRolloutAndStatus(JpaRollout rollout, RolloutGroupStatus rolloutGroupStatus); /** * Counts all {@link RolloutGroup} referring a specific rollout in specific @@ -88,8 +90,8 @@ public interface RolloutGroupRepository * @return the count of rollout groups belonging to a rollout in specific * status */ - @Query("SELECT COUNT(r.id) FROM RolloutGroup r WHERE r.rollout = :rollout and (r.status = :status1 or r.status = :status2)") - Long countByRolloutAndStatusOrStatus(@Param("rollout") Rollout rollout, + @Query("SELECT COUNT(r.id) FROM JpaRolloutGroup r WHERE r.rollout = :rollout and (r.status = :status1 or r.status = :status2)") + Long countByRolloutAndStatusOrStatus(@Param("rollout") JpaRollout rollout, @Param("status1") RolloutGroupStatus rolloutGroupStatus1, @Param("status2") RolloutGroupStatus rolloutGroupStatus2); @@ -103,7 +105,7 @@ public interface RolloutGroupRepository * the status of the rolloutgroups * @return The child {@link RolloutGroup}s in a specific status */ - List findByParentAndStatus(RolloutGroup rolloutGroup, RolloutGroupStatus status); + List findByParentAndStatus(JpaRolloutGroup rolloutGroup, RolloutGroupStatus status); /** * Retrieves all {@link RolloutGroup} for a specific rollout and status not @@ -116,7 +118,7 @@ public interface RolloutGroupRepository * @return rolloutgroup referring to a rollout and not having a specific * status ordered by ID DESC. */ - List findByRolloutAndStatusNotOrderByIdDesc(Rollout rollout, RolloutGroupStatus notStatus); + List findByRolloutAndStatusNotOrderByIdDesc(JpaRollout rollout, RolloutGroupStatus notStatus); /** * Retrieves all {@link RolloutGroup} for a specific rollout. @@ -127,6 +129,6 @@ public interface RolloutGroupRepository * the page request to sort, limit the result * @return a page of found {@link RolloutGroup} or {@code empty}. */ - Page findByRolloutId(final Long rolloutId, Pageable page); + Page findByRolloutId(final Long rolloutId, Pageable page); } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutRepository.java similarity index 82% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutRepository.java index 5a22f5ab5..74d47d99a 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutRepository.java @@ -6,10 +6,11 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import java.util.List; +import org.eclipse.hawkbit.repository.jpa.model.JpaRollout; import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.Rollout.RolloutStatus; import org.springframework.data.domain.Page; @@ -25,7 +26,8 @@ import org.springframework.transaction.annotation.Transactional; * The repository interface for the {@link Rollout} model. */ @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) -public interface RolloutRepository extends BaseEntityRepository, JpaSpecificationExecutor { +public interface RolloutRepository + extends BaseEntityRepository, JpaSpecificationExecutor { /** * Updates the {@code lastCheck} field of the {@link Rollout} for rollouts @@ -42,7 +44,7 @@ public interface RolloutRepository extends BaseEntityRepository, */ @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @Query("UPDATE Rollout r SET r.lastCheck = :lastCheck WHERE r.lastCheck < (:lastCheck - :delay) AND r.status=:status") + @Query("UPDATE JpaRollout r SET r.lastCheck = :lastCheck WHERE r.lastCheck < (:lastCheck - :delay) AND r.status=:status") int updateLastCheck(@Param("lastCheck") final long lastCheck, @Param("delay") final long delay, @Param("status") final RolloutStatus status); @@ -57,7 +59,7 @@ public interface RolloutRepository extends BaseEntityRepository, * @return the list of {@link Rollout} for specific lastCheck time and * status */ - List findByLastCheckAndStatus(long lastCheck, RolloutStatus status); + List findByLastCheckAndStatus(long lastCheck, RolloutStatus status); /** * Retrieves all {@link Rollout} for a specific {@code name} @@ -66,7 +68,7 @@ public interface RolloutRepository extends BaseEntityRepository, * the rollout name * @return {@link Rollout} for specific name */ - Page findByName(final Pageable pageable, String name); + Page findByName(final Pageable pageable, String name); /** * Retrieves all {@link Rollout} for a specific {@code name} @@ -75,7 +77,7 @@ public interface RolloutRepository extends BaseEntityRepository, * the rollout name * @return {@link Rollout} for specific name */ - Rollout findByName(String name); + JpaRollout findByName(String name); /** * Retrieves all {@link Rollout} for a specific status. @@ -84,5 +86,5 @@ public interface RolloutRepository extends BaseEntityRepository, * the status of the rollouts to retrieve * @return a list of {@link Rollout} having the given status */ - List findByStatus(final RolloutStatus status); + List findByStatus(final RolloutStatus status); } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutTargetGroupRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutTargetGroupRepository.java similarity index 83% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutTargetGroupRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutTargetGroupRepository.java index 14d9b8353..8cb267c69 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutTargetGroupRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutTargetGroupRepository.java @@ -6,10 +6,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; -import org.eclipse.hawkbit.repository.model.RolloutTargetGroup; -import org.eclipse.hawkbit.repository.model.RolloutTargetGroupId; +import org.eclipse.hawkbit.repository.jpa.model.RolloutTargetGroup; +import org.eclipse.hawkbit.repository.jpa.model.RolloutTargetGroupId; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.CrudRepository; import org.springframework.transaction.annotation.Isolation; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareModuleMetadataRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleMetadataRepository.java similarity index 79% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareModuleMetadataRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleMetadataRepository.java index c40a96e92..c962b31ec 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareModuleMetadataRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleMetadataRepository.java @@ -6,12 +6,13 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import java.util.List; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleMetadata; +import org.eclipse.hawkbit.repository.jpa.model.SwMetadataCompositeKey; import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; -import org.eclipse.hawkbit.repository.model.SwMetadataCompositeKey; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; @@ -25,8 +26,8 @@ import org.springframework.transaction.annotation.Transactional; */ @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface SoftwareModuleMetadataRepository - extends PagingAndSortingRepository, - JpaSpecificationExecutor { + extends PagingAndSortingRepository, + JpaSpecificationExecutor { /** * Saves all given entities. @@ -37,7 +38,7 @@ public interface SoftwareModuleMetadataRepository * in case the given entity is (@literal null}. */ @Override - List save(Iterable entities); + List save(Iterable entities); /** * finds all software module meta data of the given software module id. diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareModuleRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleRepository.java similarity index 76% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareModuleRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleRepository.java index 95b01c270..08c84b349 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareModuleRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleRepository.java @@ -6,10 +6,13 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import java.util.List; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; @@ -30,7 +33,7 @@ import org.springframework.transaction.annotation.Transactional; */ @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface SoftwareModuleRepository - extends BaseEntityRepository, JpaSpecificationExecutor { + extends BaseEntityRepository, JpaSpecificationExecutor { /** * Counts all {@link SoftwareModule}s based on the given {@link Type}. @@ -39,7 +42,7 @@ public interface SoftwareModuleRepository * to count for * @return number of {@link SoftwareModule}s */ - Long countByType(SoftwareModuleType type); + Long countByType(JpaSoftwareModuleType type); /** * Retrieves {@link SoftwareModule} by filtering on name AND version AND @@ -54,7 +57,7 @@ public interface SoftwareModuleRepository * @return the found {@link SoftwareModule} with the given name AND version * AND type */ - SoftwareModule findOneByNameAndVersionAndType(String name, String version, SoftwareModuleType type); + JpaSoftwareModule findOneByNameAndVersionAndType(String name, String version, JpaSoftwareModuleType type); /** * deletes the {@link SoftwareModule}s with the given IDs. @@ -69,7 +72,7 @@ public interface SoftwareModuleRepository */ @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @Query("UPDATE SoftwareModule b SET b.deleted = 1, b.lastModifiedAt = :lastModifiedAt, b.lastModifiedBy = :lastModifiedBy WHERE b.id IN :ids") + @Query("UPDATE JpaSoftwareModule b SET b.deleted = 1, b.lastModifiedAt = :lastModifiedAt, b.lastModifiedBy = :lastModifiedBy WHERE b.id IN :ids") void deleteSoftwareModule(@Param("lastModifiedAt") Long modifiedAt, @Param("lastModifiedBy") String modifiedBy, @Param("ids") final Long... ids); @@ -81,7 +84,7 @@ public interface SoftwareModuleRepository * @return all {@link SoftwareModule}s that are assigned to given * {@link DistributionSet}. */ - Page findByAssignedTo(Pageable pageable, DistributionSet set); + Page findByAssignedTo(Pageable pageable, JpaDistributionSet set); /** * @@ -92,7 +95,7 @@ public interface SoftwareModuleRepository * {@link DistributionSet} */ @EntityGraph(value = "SoftwareModule.artifacts", type = EntityGraphType.LOAD) - List findByAssignedTo(DistributionSet set); + List findByAssignedTo(JpaDistributionSet set); /** * @param pageable @@ -104,7 +107,7 @@ public interface SoftwareModuleRepository * @return all {@link SoftwareModule}s that are assigned to given * {@link DistributionSet} filtered by {@link SoftwareModuleType}. */ - Page findByAssignedToAndType(Pageable pageable, DistributionSet set, SoftwareModuleType type); + Page findByAssignedToAndType(Pageable pageable, JpaDistributionSet set, JpaSoftwareModuleType type); /** * retrieves all software modules with a given {@link SoftwareModuleType} @@ -117,11 +120,11 @@ public interface SoftwareModuleRepository * @return {@link List} of found {@link SoftwareModule}s */ // Workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=349477 - @Query("SELECT sm FROM SoftwareModule sm WHERE sm.id IN ?1 and sm.type = ?2") - List findByIdInAndType(Iterable ids, SoftwareModuleType type); + @Query("SELECT sm FROM JpaSoftwareModule sm WHERE sm.id IN ?1 and sm.type = ?2") + List findByIdInAndType(Iterable ids, JpaSoftwareModuleType type); @Override - List save(Iterable entities); + List save(Iterable entities); /** * retrieves all software modules with a given @@ -132,6 +135,6 @@ public interface SoftwareModuleRepository * @return {@link List} of found {@link SoftwareModule}s */ // Workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=349477 - @Query("SELECT sm FROM SoftwareModule sm WHERE sm.id IN ?1") - List findByIdIn(Iterable ids); + @Query("SELECT sm FROM JpaSoftwareModule sm WHERE sm.id IN ?1") + List findByIdIn(Iterable ids); } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareModuleTypeRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleTypeRepository.java similarity index 84% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareModuleTypeRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleTypeRepository.java index ac9425a08..c4ecfbd74 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareModuleTypeRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleTypeRepository.java @@ -6,8 +6,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -21,7 +22,7 @@ import org.springframework.transaction.annotation.Transactional; */ @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface SoftwareModuleTypeRepository - extends BaseEntityRepository, JpaSpecificationExecutor { + extends BaseEntityRepository, JpaSpecificationExecutor { /** * @param pageable @@ -47,7 +48,7 @@ public interface SoftwareModuleTypeRepository * @return all {@link SoftwareModuleType}s in the repository with given * {@link SoftwareModuleType#getKey()} */ - SoftwareModuleType findByKey(String key); + JpaSoftwareModuleType findByKey(String key); /** * @@ -56,5 +57,5 @@ public interface SoftwareModuleTypeRepository * @return all {@link SoftwareModuleType}s in the repository with given * {@link SoftwareModuleType#getName()} */ - SoftwareModuleType findByName(String name); + JpaSoftwareModuleType findByName(String name); } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryRepository.java similarity index 78% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryRepository.java index 3604785cd..1f2fec8d8 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryRepository.java @@ -6,8 +6,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetFilterQuery; import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.springframework.data.domain.Page; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; @@ -21,7 +22,7 @@ import org.springframework.transaction.annotation.Transactional; */ @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface TargetFilterQueryRepository - extends BaseEntityRepository, JpaSpecificationExecutor { + extends BaseEntityRepository, JpaSpecificationExecutor { /** * Find customer target filter by name @@ -35,11 +36,11 @@ public interface TargetFilterQueryRepository * Find list of all custom target filters. */ @Override - Page findAll(); + Page findAll(); @Override @Modifying @Transactional - S save(S entity); + S save(S entity); } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetInfoRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetInfoRepository.java similarity index 88% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetInfoRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetInfoRepository.java index 436f1e7b6..815fa3961 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetInfoRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetInfoRepository.java @@ -6,13 +6,14 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import java.util.Collection; import java.util.List; import javax.persistence.Entity; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetInfo; import org.eclipse.hawkbit.repository.model.TargetInfo; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.springframework.cache.annotation.CacheEvict; @@ -42,7 +43,7 @@ public interface TargetInfoRepository { */ @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @Query("update TargetInfo ti set ti.updateStatus = :status where ti.targetId in :targets and ti.updateStatus != :status") + @Query("update JpaTargetInfo ti set ti.updateStatus = :status where ti.targetId in :targets and ti.updateStatus != :status") void setTargetUpdateStatus(@Param("status") TargetUpdateStatus status, @Param("targets") List targets); /** @@ -54,7 +55,7 @@ public interface TargetInfoRepository { * @return persisted or updated {@link Entity} */ @CacheEvict(value = { "targetStatus", "distributionUsageInstalled", "targetsLastPoll" }, allEntries = true) - S save(S entity); + S save(S entity); /** * Deletes info entries by ID. diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetRepository.java similarity index 83% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetRepository.java index 5e37902ab..0d84a3cad 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetRepository.java @@ -6,16 +6,18 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import java.util.Collection; import java.util.List; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; +import org.eclipse.hawkbit.repository.jpa.model.JpaRolloutGroup; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag; import org.eclipse.hawkbit.repository.model.DistributionSet; -import org.eclipse.hawkbit.repository.model.RolloutGroup; import org.eclipse.hawkbit.repository.model.Tag; import org.eclipse.hawkbit.repository.model.Target; -import org.eclipse.hawkbit.repository.model.TargetTag; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.repository.model.TargetWithActionStatus; import org.springframework.cache.annotation.CacheEvict; @@ -35,7 +37,7 @@ import org.springframework.transaction.annotation.Transactional; * */ @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) -public interface TargetRepository extends BaseEntityRepository, JpaSpecificationExecutor { +public interface TargetRepository extends BaseEntityRepository, JpaSpecificationExecutor { /** * Loads {@link Target} including details {@link EntityGraph} by given ID. @@ -45,7 +47,7 @@ public interface TargetRepository extends BaseEntityRepository, Jp * @return found {@link Target} or null if not found. */ @EntityGraph(value = "Target.detail", type = EntityGraphType.LOAD) - Target findByControllerId(String controllerID); + JpaTarget findByControllerId(String controllerID); /** * Finds targets by given list of {@link Target#getControllerId()}s. @@ -65,7 +67,7 @@ public interface TargetRepository extends BaseEntityRepository, Jp @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) // Workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=349477 - @Query("DELETE FROM Target t WHERE t.id IN ?1") + @Query("DELETE FROM JpaTarget t WHERE t.id IN ?1") void deleteByIdIn(final Collection targetIDs); /** @@ -75,8 +77,8 @@ public interface TargetRepository extends BaseEntityRepository, Jp * to be found * @return list of found targets */ - @Query(value = "SELECT DISTINCT t FROM Target t JOIN t.tags tt WHERE tt = :tag") - List findByTag(@Param("tag") final TargetTag tag); + @Query(value = "SELECT DISTINCT t FROM JpaTarget t JOIN t.tags tt WHERE tt = :tag") + List findByTag(@Param("tag") final JpaTargetTag tag); /** * Finds all {@link Target}s based on given {@link Target#getControllerId()} @@ -88,7 +90,7 @@ public interface TargetRepository extends BaseEntityRepository, Jp * to search for * @return {@link List} of found {@link Target}s. */ - @Query(value = "SELECT DISTINCT t from Target t JOIN t.tags tt WHERE tt.name = :tagname AND t.controllerId IN :targets") + @Query(value = "SELECT DISTINCT t from JpaTarget t JOIN t.tags tt WHERE tt.name = :tagname AND t.controllerId IN :targets") List findByTagNameAndControllerIdIn(@Param("tagname") final String tag, @Param("targets") final Collection controllerIds); @@ -114,7 +116,7 @@ public interface TargetRepository extends BaseEntityRepository, Jp * * @return found targets */ - Page findByTargetInfoInstalledDistributionSet(final Pageable pageable, final DistributionSet set); + Page findByTargetInfoInstalledDistributionSet(final Pageable pageable, final JpaDistributionSet set); /** * retrieves the {@link Target}s which has the {@link DistributionSet} @@ -138,7 +140,7 @@ public interface TargetRepository extends BaseEntityRepository, Jp * * @return found targets */ - Page findByAssignedDistributionSet(final Pageable pageable, final DistributionSet set); + Page findByAssignedDistributionSet(final Pageable pageable, final JpaDistributionSet set); /** * Saves all given {@link Target}s. @@ -154,7 +156,7 @@ public interface TargetRepository extends BaseEntityRepository, Jp @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) @CacheEvict(value = { "targetStatus", "distributionUsageInstalled", "targetsLastPoll" }, allEntries = true) - List save(Iterable entities); + List save(Iterable entities); /** * Saves a given entity. Use the returned instance for further operations as @@ -168,7 +170,7 @@ public interface TargetRepository extends BaseEntityRepository, Jp @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) @CacheEvict(value = { "targetStatus", "distributionUsageInstalled", "targetsLastPoll" }, allEntries = true) - S save(S entity); + S save(S entity); /** * Finds all targets that have defined {@link DistributionSet} assigned. @@ -199,7 +201,7 @@ public interface TargetRepository extends BaseEntityRepository, Jp * @return number of found {@link Target}s with given * {@link Target#getControllerId()}s */ - @Query("SELECT COUNT(t) FROM Target t WHERE t.controllerId IN ?1") + @Query("SELECT COUNT(t) FROM JpaTarget t WHERE t.controllerId IN ?1") Long countByControllerIdIn(final Collection ids); /** @@ -228,7 +230,7 @@ public interface TargetRepository extends BaseEntityRepository, Jp * @return found targets */ Page findByAssignedDistributionSetOrTargetInfoInstalledDistributionSet(final Pageable pageable, - final DistributionSet assigned, final DistributionSet installed); + final JpaDistributionSet assigned, final JpaDistributionSet installed); /** * Finds all targets that have defined {@link DistributionSet} assigned or @@ -255,12 +257,12 @@ public interface TargetRepository extends BaseEntityRepository, Jp * @see org.springframework.data.repository.CrudRepository#findAll() */ @Override - List findAll(); + List findAll(); @Override // Workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=349477 - @Query("SELECT t FROM Target t WHERE t.id IN ?1") - List findAll(Iterable ids); + @Query("SELECT t FROM JpaTarget t WHERE t.id IN ?1") + List findAll(Iterable ids); /** * Sets {@link Target#getAssignedDistributionSet()}. @@ -276,11 +278,11 @@ public interface TargetRepository extends BaseEntityRepository, Jp */ @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @Query("UPDATE Target t SET t.assignedDistributionSet = :set, t.lastModifiedAt = :lastModifiedAt, t.lastModifiedBy = :lastModifiedBy WHERE t.id IN :targets") - void setAssignedDistributionSet(@Param("set") DistributionSet set, @Param("lastModifiedAt") Long modifiedAt, + @Query("UPDATE JpaTarget t SET t.assignedDistributionSet = :set, t.lastModifiedAt = :lastModifiedAt, t.lastModifiedBy = :lastModifiedBy WHERE t.id IN :targets") + void setAssignedDistributionSet(@Param("set") JpaDistributionSet set, @Param("lastModifiedAt") Long modifiedAt, @Param("lastModifiedBy") String modifiedBy, @Param("targets") Collection targets); - List findByRolloutTargetGroupRolloutGroup(final RolloutGroup rolloutGroup); + List findByRolloutTargetGroupRolloutGroup(final JpaRolloutGroup rolloutGroup); /** * @@ -304,7 +306,7 @@ public interface TargetRepository extends BaseEntityRepository, Jp * the page request parameter * @return a page of all targets related to a rollout group */ - Page findByActionsRolloutGroup(RolloutGroup rolloutGroup, Pageable page); + Page findByActionsRolloutGroup(JpaRolloutGroup rolloutGroup, Pageable page); /** * Find all targets with action status for a specific group. @@ -315,7 +317,7 @@ public interface TargetRepository extends BaseEntityRepository, Jp * the ID of the rollout group * @return targets with action status */ - @Query("select DISTINCT NEW org.eclipse.hawkbit.repository.model.TargetWithActionStatus(a.target,a.status) from Action a inner join fetch a.target t where a.rolloutGroup.id = :rolloutGroupId") + @Query("select DISTINCT NEW org.eclipse.hawkbit.repository.model.TargetWithActionStatus(a.target,a.status) from JpaAction a inner join fetch a.target t where a.rolloutGroup.id = :rolloutGroupId") Page findTargetsWithActionStatusByRolloutGroupId(final Pageable pageable, @Param("rolloutGroupId") Long rolloutGroupId); } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetTagRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetTagRepository.java similarity index 79% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetTagRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetTagRepository.java index e0f03ee78..6b9e021b1 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetTagRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetTagRepository.java @@ -6,10 +6,11 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import java.util.List; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag; import org.eclipse.hawkbit.repository.model.TargetTag; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; @@ -22,7 +23,7 @@ import org.springframework.transaction.annotation.Transactional; */ @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface TargetTagRepository - extends BaseEntityRepository, JpaSpecificationExecutor { + extends BaseEntityRepository, JpaSpecificationExecutor { /** * deletes the {@link TargetTag}s with the given tag names. @@ -42,7 +43,7 @@ public interface TargetTagRepository * to filter on * @return the {@link TargetTag} if found, otherwise null */ - TargetTag findByNameEquals(final String tagName); + JpaTargetTag findByNameEquals(final String tagName); /** * Returns all instances of the type. @@ -50,8 +51,8 @@ public interface TargetTagRepository * @return all entities */ @Override - List findAll(); + List findAll(); @Override - List save(Iterable entities); + List save(Iterable entities); } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantConfigurationRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TenantConfigurationRepository.java similarity index 83% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantConfigurationRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TenantConfigurationRepository.java index 0497ea924..bd99cb918 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantConfigurationRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TenantConfigurationRepository.java @@ -6,10 +6,11 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import java.util.List; +import org.eclipse.hawkbit.repository.jpa.model.JpaTenantConfiguration; import org.eclipse.hawkbit.repository.model.TenantConfiguration; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; @@ -19,7 +20,7 @@ import org.springframework.transaction.annotation.Transactional; * */ @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) -public interface TenantConfigurationRepository extends BaseEntityRepository { +public interface TenantConfigurationRepository extends BaseEntityRepository { /** * Finds a specific {@link TenantConfiguration} by the configuration key. @@ -28,10 +29,10 @@ public interface TenantConfigurationRepository extends BaseEntityRepository findAll(); + List findAll(); /** * Deletes a tenant configuration by tenant and key. diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantKeyGenerator.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TenantKeyGenerator.java similarity index 95% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantKeyGenerator.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TenantKeyGenerator.java index 3265b622c..0478d99d7 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantKeyGenerator.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TenantKeyGenerator.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import java.lang.reflect.Method; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantMetaDataRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TenantMetaDataRepository.java similarity index 89% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantMetaDataRepository.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TenantMetaDataRepository.java index 4aa4c48dc..353f6500b 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantMetaDataRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TenantMetaDataRepository.java @@ -6,10 +6,11 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import java.util.List; +import org.eclipse.hawkbit.repository.jpa.model.JpaTenantMetaData; import org.eclipse.hawkbit.repository.model.TenantMetaData; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.transaction.annotation.Isolation; @@ -20,7 +21,7 @@ import org.springframework.transaction.annotation.Transactional; * */ @Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) -public interface TenantMetaDataRepository extends PagingAndSortingRepository { +public interface TenantMetaDataRepository extends PagingAndSortingRepository { /** * Search {@link TenantMetaData} by tenant name. @@ -42,7 +43,7 @@ public interface TenantMetaDataRepository extends PagingAndSortingRepository findAll(); + List findAll(); /** * @param tenant diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/aspects/ExceptionMappingAspectHandler.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/aspects/ExceptionMappingAspectHandler.java similarity index 99% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/aspects/ExceptionMappingAspectHandler.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/aspects/ExceptionMappingAspectHandler.java index c3da509aa..be21cdfe7 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/aspects/ExceptionMappingAspectHandler.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/aspects/ExceptionMappingAspectHandler.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.aspects; +package org.eclipse.hawkbit.repository.jpa.aspects; import java.sql.SQLException; import java.util.ArrayList; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/cache/CacheField.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/cache/CacheField.java similarity index 89% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/cache/CacheField.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/cache/CacheField.java index 8909c1125..b4e322c77 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/cache/CacheField.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/cache/CacheField.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.cache; +package org.eclipse.hawkbit.repository.jpa.cache; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; @@ -14,7 +14,7 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; -import org.eclipse.hawkbit.eventbus.CacheFieldEntityListener; +import org.eclipse.hawkbit.repository.jpa.model.CacheFieldEntityListener; import org.springframework.cache.CacheManager; import org.springframework.data.annotation.Transient; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/cache/CacheKeys.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/cache/CacheKeys.java similarity index 89% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/cache/CacheKeys.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/cache/CacheKeys.java index 9cb53a317..021a17a9d 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/cache/CacheKeys.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/cache/CacheKeys.java @@ -6,12 +6,12 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.cache; +package org.eclipse.hawkbit.repository.jpa.cache; -import org.eclipse.hawkbit.eventbus.CacheFieldEntityListener; +import org.eclipse.hawkbit.repository.jpa.model.CacheFieldEntityListener; /** - * Constants for cache keys used in multiple classes. + * RepositoryConstants for cache keys used in multiple classes. * * * diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/cache/CacheWriteNotify.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/cache/CacheWriteNotify.java similarity index 97% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/cache/CacheWriteNotify.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/cache/CacheWriteNotify.java index bf690e07e..fdaf868e8 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/cache/CacheWriteNotify.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/cache/CacheWriteNotify.java @@ -6,10 +6,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.cache; +package org.eclipse.hawkbit.repository.jpa.cache; import org.eclipse.hawkbit.eventbus.event.DownloadProgressEvent; -import org.eclipse.hawkbit.eventbus.event.RolloutGroupCreatedEvent; +import org.eclipse.hawkbit.repository.eventbus.event.RolloutGroupCreatedEvent; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.ActionStatus; import org.eclipse.hawkbit.repository.model.Rollout; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/Constants.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/configuration/Constants.java similarity index 94% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/Constants.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/configuration/Constants.java index ef0b70438..fb6a319f9 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/Constants.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/configuration/Constants.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit; +package org.eclipse.hawkbit.repository.jpa.configuration; /** * A constant class which holds only static constants used within the SP server. diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/MultiTenantJpaTransactionManager.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/configuration/MultiTenantJpaTransactionManager.java similarity index 96% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/MultiTenantJpaTransactionManager.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/configuration/MultiTenantJpaTransactionManager.java index b3821e5f3..e8547c52b 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/MultiTenantJpaTransactionManager.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/configuration/MultiTenantJpaTransactionManager.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit; +package org.eclipse.hawkbit.repository.jpa.configuration; import javax.persistence.EntityManager; import javax.transaction.Transaction; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/EntityChangeEventListener.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/eventbus/EntityChangeEventListener.java similarity index 86% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/EntityChangeEventListener.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/eventbus/EntityChangeEventListener.java index 7bfbd957e..5f41063d2 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/EntityChangeEventListener.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/eventbus/EntityChangeEventListener.java @@ -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; +package org.eclipse.hawkbit.repository.jpa.eventbus; import java.util.Collection; @@ -15,11 +15,12 @@ import javax.persistence.EntityManager; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; -import org.eclipse.hawkbit.eventbus.event.TargetCreatedEvent; import org.eclipse.hawkbit.eventbus.event.TargetDeletedEvent; -import org.eclipse.hawkbit.eventbus.event.TargetInfoUpdateEvent; -import org.eclipse.hawkbit.executor.AfterTransactionCommitExecutor; -import org.eclipse.hawkbit.repository.TargetRepository; +import org.eclipse.hawkbit.repository.eventbus.event.TargetCreatedEvent; +import org.eclipse.hawkbit.repository.eventbus.event.TargetInfoUpdateEvent; +import org.eclipse.hawkbit.repository.jpa.TargetRepository; +import org.eclipse.hawkbit.repository.jpa.executor.AfterTransactionCommitExecutor; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetInfo; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetInfo; import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity; @@ -66,7 +67,7 @@ public class EntityChangeEventListener { * in case exception happens in the * {@link ProceedingJoinPoint#proceed()} */ - @Around("execution(* org.eclipse.hawkbit.repository.TargetInfoRepository.save(..))") + @Around("execution(* org.eclipse.hawkbit.repository.jpa.TargetInfoRepository.save(..))") // Exception squid:S00112 - Is aspectJ proxy @SuppressWarnings({ "squid:S00112" }) public Object targetCreated(final ProceedingJoinPoint joinpoint) throws Throwable { @@ -93,7 +94,7 @@ public class EntityChangeEventListener { * in case exception happens in the * {@link ProceedingJoinPoint#proceed()} */ - @Around("execution(* org.eclipse.hawkbit.repository.TargetRepository.deleteByIdIn(..))") + @Around("execution(* org.eclipse.hawkbit.repository.jpa.TargetRepository.deleteByIdIn(..))") // Exception squid:S00112 - Is aspectJ proxy @SuppressWarnings({ "squid:S00112" }) public Object targetDeletedById(final ProceedingJoinPoint joinpoint) throws Throwable { @@ -115,8 +116,8 @@ public class EntityChangeEventListener { * in case exception happens in the * {@link ProceedingJoinPoint#proceed()} */ - @Around("execution(* org.eclipse.hawkbit.repository.TargetRepository.delete(..))") - // Exception squid:S00112 - Is aspectJ proxy + @Around("execution(* org.eclipse.hawkbit.repository.jpa.TargetRepository.delete(..))") + // Exception squid:S00112 - Is aspectJ proxy @SuppressWarnings({ "squid:S00112", "unchecked" }) public Object targetDeleted(final ProceedingJoinPoint joinpoint) throws Throwable { final String currentTenant = tenantAware.getCurrentTenant(); @@ -146,8 +147,8 @@ public class EntityChangeEventListener { afterCommit.afterCommit(() -> eventBus.post(new TargetDeletedEvent(tenant, targetId))); } - private boolean isTargetInfoNew(final Object targetInfo) { - return ((TargetInfo) targetInfo).isNew(); + private static boolean isTargetInfoNew(final Object targetInfo) { + return ((JpaTargetInfo) targetInfo).isNew(); } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/EventMerger.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/eventbus/EventMerger.java similarity index 90% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/EventMerger.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/eventbus/EventMerger.java index fe4cf4b34..6a4302c5b 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/EventMerger.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/eventbus/EventMerger.java @@ -6,13 +6,21 @@ * 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.jpa.eventbus; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.eclipse.hawkbit.eventbus.EventSubscriber; +import org.eclipse.hawkbit.eventbus.event.Event; +import org.eclipse.hawkbit.repository.eventbus.event.ActionCreatedEvent; +import org.eclipse.hawkbit.repository.eventbus.event.ActionPropertyChangeEvent; +import org.eclipse.hawkbit.repository.eventbus.event.RolloutChangeEvent; +import org.eclipse.hawkbit.repository.eventbus.event.RolloutGroupChangeEvent; +import org.eclipse.hawkbit.repository.eventbus.event.RolloutGroupCreatedEvent; +import org.eclipse.hawkbit.repository.eventbus.event.RolloutGroupPropertyChangeEvent; +import org.eclipse.hawkbit.repository.eventbus.event.RolloutPropertyChangeEvent; import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.RolloutGroup; import org.springframework.beans.factory.annotation.Autowired; @@ -28,10 +36,8 @@ import com.google.common.eventbus.Subscribe; * interested in all fine grained events, e.g. UI code. The UI code is not * interested in handling the flood of events, so collecting the events and * merge them to one event together and post them in a fixed interval is easier - * to consume e.g. for push notifcations on UI. + * to consume e.g. for push notifications on UI. * - * @author Michael Hirsch - * */ @EventSubscriber public class EventMerger { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/executor/AfterTransactionCommitDefaultServiceExecutor.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/executor/AfterTransactionCommitDefaultServiceExecutor.java similarity index 95% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/executor/AfterTransactionCommitDefaultServiceExecutor.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/executor/AfterTransactionCommitDefaultServiceExecutor.java index 0d65b291e..6c58a0207 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/executor/AfterTransactionCommitDefaultServiceExecutor.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/executor/AfterTransactionCommitDefaultServiceExecutor.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.executor; +package org.eclipse.hawkbit.repository.jpa.executor; import java.util.ArrayList; import java.util.List; @@ -45,6 +45,8 @@ public class AfterTransactionCommitDefaultServiceExecutor extends TransactionSyn } @Override + // Exception squid:S1217 - we want to run this synchronous + @SuppressWarnings("squid:S1217") public void afterCommit(final Runnable runnable) { LOGGER.debug("Submitting new runnable {} to run after transaction commit", runnable); if (TransactionSynchronizationManager.isSynchronizationActive()) { @@ -58,6 +60,7 @@ public class AfterTransactionCommitDefaultServiceExecutor extends TransactionSyn return; } LOGGER.info("Transaction synchronization is NOT ACTIVE/ INACTIVE. Executing right now runnable {}", runnable); + runnable.run(); } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/executor/AfterTransactionCommitExecutor.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/executor/AfterTransactionCommitExecutor.java similarity index 93% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/executor/AfterTransactionCommitExecutor.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/executor/AfterTransactionCommitExecutor.java index ab5c67bab..34b0e8d5f 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/executor/AfterTransactionCommitExecutor.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/executor/AfterTransactionCommitExecutor.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.executor; +package org.eclipse.hawkbit.repository.jpa.executor; /** * diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Artifact.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaArtifact.java similarity index 74% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Artifact.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaArtifact.java index b384a3100..6ead1df9e 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Artifact.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaArtifact.java @@ -6,17 +6,23 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import javax.persistence.Column; import javax.persistence.MappedSuperclass; +import org.eclipse.hawkbit.repository.model.Artifact; +import org.eclipse.hawkbit.repository.model.SoftwareModule; + /** * Tenant specific locally stored artifact representation that is used by * {@link SoftwareModule}. */ @MappedSuperclass -public abstract class Artifact extends TenantAwareBaseEntity { +// exception squid:S2160 - BaseEntity equals/hashcode is handling correctly for +// sub entities +@SuppressWarnings("squid:S2160") +public abstract class AbstractJpaArtifact extends AbstractJpaTenantAwareBaseEntity implements Artifact { private static final long serialVersionUID = 1L; @Column(name = "sha1_hash", length = 40, nullable = true) @@ -28,12 +34,15 @@ public abstract class Artifact extends TenantAwareBaseEntity { @Column(name = "file_size") private Long size; + @Override public abstract SoftwareModule getSoftwareModule(); + @Override public String getMd5Hash() { return md5Hash; } + @Override public String getSha1Hash() { return sha1Hash; } @@ -46,6 +55,7 @@ public abstract class Artifact extends TenantAwareBaseEntity { this.sha1Hash = sha1Hash; } + @Override public Long getSize() { return size; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/BaseEntity.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaBaseEntity.java similarity index 87% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/BaseEntity.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaBaseEntity.java index 65300c6c4..257828c6f 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/BaseEntity.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaBaseEntity.java @@ -6,9 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; - -import java.io.Serializable; +package org.eclipse.hawkbit.repository.jpa.model; import javax.persistence.Access; import javax.persistence.AccessType; @@ -20,14 +18,12 @@ import javax.persistence.Id; import javax.persistence.MappedSuperclass; import javax.persistence.Version; -import org.eclipse.hawkbit.eventbus.CacheFieldEntityListener; -import org.eclipse.hawkbit.eventbus.EntityPropertyChangeListener; +import org.eclipse.hawkbit.repository.model.BaseEntity; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; -import org.springframework.hateoas.Identifiable; /** * Holder of the base attributes common to all entities. @@ -36,7 +32,7 @@ import org.springframework.hateoas.Identifiable; @MappedSuperclass @Access(AccessType.FIELD) @EntityListeners({ AuditingEntityListener.class, CacheFieldEntityListener.class, EntityPropertyChangeListener.class }) -public abstract class BaseEntity implements Serializable, Identifiable { +public abstract class AbstractJpaBaseEntity implements BaseEntity { private static final long serialVersionUID = 1L; @Id @@ -56,28 +52,32 @@ public abstract class BaseEntity implements Serializable, Identifiable { /** * Default constructor needed for JPA entities. */ - public BaseEntity() { + public AbstractJpaBaseEntity() { // Default constructor needed for JPA entities. } + @Override @Access(AccessType.PROPERTY) @Column(name = "created_at", insertable = true, updatable = false) public Long getCreatedAt() { return createdAt; } + @Override @Access(AccessType.PROPERTY) @Column(name = "created_by", insertable = true, updatable = false, length = 40) public String getCreatedBy() { return createdBy; } + @Override @Access(AccessType.PROPERTY) @Column(name = "last_modified_at", insertable = false, updatable = true) public Long getLastModifiedAt() { return lastModifiedAt; } + @Override @Access(AccessType.PROPERTY) @Column(name = "last_modified_by", insertable = false, updatable = true, length = 40) public String getLastModifiedBy() { @@ -104,12 +104,12 @@ public abstract class BaseEntity implements Serializable, Identifiable { this.lastModifiedAt = lastModifiedAt; } + @Override public long getOptLockRevision() { return optLockRevision; } - // for test purposes only - void setOptLockRevision(final long optLockRevision) { + public void setOptLockRevision(final long optLockRevision) { this.optLockRevision = optLockRevision; } @@ -135,7 +135,9 @@ public abstract class BaseEntity implements Serializable, Identifiable { * @see java.lang.Object#hashCode() */ @Override - public int hashCode() { // NOSONAR - as this is generated code + // Exception squid:S864 - generated code + @SuppressWarnings({ "squid:S864" }) + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (id == null ? 0 : id.hashCode()); @@ -152,8 +154,7 @@ public abstract class BaseEntity implements Serializable, Identifiable { * @see java.lang.Object#equals(java.lang.Object) */ @Override - public boolean equals(final Object obj) { // NOSONAR - as this is generated - // code + public boolean equals(final Object obj) { if (this == obj) { return true; } @@ -163,7 +164,7 @@ public abstract class BaseEntity implements Serializable, Identifiable { if (!(this.getClass().isInstance(obj))) { return false; } - final BaseEntity other = (BaseEntity) obj; + final AbstractJpaBaseEntity other = (AbstractJpaBaseEntity) obj; if (id == null) { if (other.id != null) { return false; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/MetaData.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaMetaData.java similarity index 84% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/MetaData.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaMetaData.java index c41a0e8c9..5a3f23ac3 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/MetaData.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaMetaData.java @@ -6,21 +6,21 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; - -import java.io.Serializable; +package org.eclipse.hawkbit.repository.jpa.model; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.MappedSuperclass; +import org.eclipse.hawkbit.repository.model.MetaData; + /** * Meta data for entities. * */ @MappedSuperclass -public abstract class MetaData implements Serializable { +public abstract class AbstractJpaMetaData implements MetaData { private static final long serialVersionUID = 1L; @Id @@ -31,28 +31,32 @@ public abstract class MetaData implements Serializable { @Basic private String value; - public MetaData(final String key, final String value) { + public AbstractJpaMetaData(final String key, final String value) { super(); this.key = key; this.value = value; } - public MetaData() { + public AbstractJpaMetaData() { // Default constructor needed for JPA entities } + @Override public String getKey() { return key; } + @Override public void setKey(final String key) { this.key = key; } + @Override public String getValue() { return value; } + @Override public void setValue(final String value) { this.value = value; } @@ -77,7 +81,7 @@ public abstract class MetaData implements Serializable { if (!(this.getClass().isInstance(obj))) { return false; } - final MetaData other = (MetaData) obj; + final AbstractJpaMetaData other = (AbstractJpaMetaData) obj; if (key == null) { if (other.key != null) { return false; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/NamedEntity.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedEntity.java similarity index 70% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/NamedEntity.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedEntity.java index e14d88161..ebf5eac3c 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/NamedEntity.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedEntity.java @@ -6,17 +6,23 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import javax.persistence.Column; import javax.persistence.MappedSuperclass; +import org.eclipse.hawkbit.repository.model.NamedEntity; +import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity; + /** * {@link TenantAwareBaseEntity} extension for all entities that are named in * addition to their technical ID. */ @MappedSuperclass -public abstract class NamedEntity extends TenantAwareBaseEntity { +// exception squid:S2160 - BaseEntity equals/hashcode is handling correctly for +// sub entities +@SuppressWarnings("squid:S2160") +public abstract class AbstractJpaNamedEntity extends AbstractJpaTenantAwareBaseEntity implements NamedEntity { private static final long serialVersionUID = 1L; @Column(name = "name", nullable = false, length = 64) @@ -28,7 +34,7 @@ public abstract class NamedEntity extends TenantAwareBaseEntity { /** * Default constructor. */ - public NamedEntity() { + public AbstractJpaNamedEntity() { super(); } @@ -40,23 +46,27 @@ public abstract class NamedEntity extends TenantAwareBaseEntity { * @param description * of the {@link NamedEntity} */ - public NamedEntity(final String name, final String description) { + public AbstractJpaNamedEntity(final String name, final String description) { this.name = name; this.description = description; } + @Override public String getDescription() { return description; } + @Override public String getName() { return name; } + @Override public void setDescription(final String description) { this.description = description; } + @Override public void setName(final String name) { this.name = name; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/NamedVersionedEntity.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedVersionedEntity.java similarity index 64% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/NamedVersionedEntity.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedVersionedEntity.java index fa56da197..ffdb1dfa6 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/NamedVersionedEntity.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedVersionedEntity.java @@ -6,17 +6,23 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import javax.persistence.Column; import javax.persistence.MappedSuperclass; +import org.eclipse.hawkbit.repository.model.NamedEntity; +import org.eclipse.hawkbit.repository.model.NamedVersionedEntity; + /** * Extension for {@link NamedEntity} that are versioned. * */ @MappedSuperclass -public abstract class NamedVersionedEntity extends NamedEntity { +// exception squid:S2160 - BaseEntity equals/hashcode is handling correctly for +// sub entities +@SuppressWarnings("squid:S2160") +public abstract class AbstractJpaNamedVersionedEntity extends AbstractJpaNamedEntity implements NamedVersionedEntity { private static final long serialVersionUID = 1L; @Column(name = "version", nullable = false, length = 64) @@ -31,19 +37,21 @@ public abstract class NamedVersionedEntity extends NamedEntity { * of the entity * @param description */ - public NamedVersionedEntity(final String name, final String version, final String description) { + public AbstractJpaNamedVersionedEntity(final String name, final String version, final String description) { super(name, description); this.version = version; } - NamedVersionedEntity() { + AbstractJpaNamedVersionedEntity() { super(); } + @Override public String getVersion() { return version; } + @Override public void setVersion(final String version) { this.version = version; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Tag.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaTag.java similarity index 73% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Tag.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaTag.java index 23489ea12..b2e8163da 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Tag.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaTag.java @@ -6,12 +6,12 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import javax.persistence.Column; import javax.persistence.MappedSuperclass; -import org.springframework.hateoas.Identifiable; +import org.eclipse.hawkbit.repository.model.Tag; /** * A Tag can be used as describing and organizational meta information for any @@ -19,13 +19,16 @@ import org.springframework.hateoas.Identifiable; * */ @MappedSuperclass -public abstract class Tag extends NamedEntity implements Identifiable { +// exception squid:S2160 - BaseEntity equals/hashcode is handling correctly for +// sub entities +@SuppressWarnings("squid:S2160") +public abstract class AbstractJpaTag extends AbstractJpaNamedEntity implements Tag { private static final long serialVersionUID = 1L; @Column(name = "colour", nullable = true, length = 16) private String colour; - protected Tag() { + protected AbstractJpaTag() { super(); } @@ -39,15 +42,17 @@ public abstract class Tag extends NamedEntity implements Identifiable { * @param colour * of tag in UI */ - public Tag(final String name, final String description, final String colour) { + public AbstractJpaTag(final String name, final String description, final String colour) { super(name, description); this.colour = colour; } + @Override public String getColour() { return colour; } + @Override public void setColour(final String colour) { this.colour = colour; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantAwareBaseEntity.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaTenantAwareBaseEntity.java similarity index 84% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantAwareBaseEntity.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaTenantAwareBaseEntity.java index d03a4938a..ccd4a30b1 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantAwareBaseEntity.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaTenantAwareBaseEntity.java @@ -6,15 +6,16 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import javax.persistence.Column; import javax.persistence.MappedSuperclass; import javax.persistence.PrePersist; import org.eclipse.hawkbit.repository.exception.TenantNotExistException; -import org.eclipse.hawkbit.repository.model.helper.SystemManagementHolder; -import org.eclipse.hawkbit.repository.model.helper.TenantAwareHolder; +import org.eclipse.hawkbit.repository.jpa.model.helper.SystemManagementHolder; +import org.eclipse.hawkbit.repository.jpa.model.helper.TenantAwareHolder; +import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity; import org.eclipse.persistence.annotations.Multitenant; import org.eclipse.persistence.annotations.MultitenantType; import org.eclipse.persistence.annotations.TenantDiscriminatorColumn; @@ -26,7 +27,7 @@ import org.eclipse.persistence.annotations.TenantDiscriminatorColumn; @MappedSuperclass @TenantDiscriminatorColumn(name = "tenant", length = 40) @Multitenant(MultitenantType.SINGLE_TABLE) -public abstract class TenantAwareBaseEntity extends BaseEntity { +public abstract class AbstractJpaTenantAwareBaseEntity extends AbstractJpaBaseEntity implements TenantAwareBaseEntity { private static final long serialVersionUID = 1L; @Column(name = "tenant", nullable = false, insertable = false, updatable = false, length = 40) @@ -35,7 +36,7 @@ public abstract class TenantAwareBaseEntity extends BaseEntity { /** * Default constructor needed for JPA entities. */ - public TenantAwareBaseEntity() { + public AbstractJpaTenantAwareBaseEntity() { // Default constructor needed for JPA entities. } @@ -57,6 +58,7 @@ public abstract class TenantAwareBaseEntity extends BaseEntity { setTenant(currentTenant.toUpperCase()); } + @Override public String getTenant() { return tenant; } @@ -95,11 +97,13 @@ public abstract class TenantAwareBaseEntity extends BaseEntity { * @see org.eclipse.hawkbit.repository.model.BaseEntity#equals(java.lang.Object) */ @Override + // exception squid:S2259 - obj is checked for null in super + @SuppressWarnings("squid:S2259") public boolean equals(final Object obj) { if (!super.equals(obj)) { return false; } - final TenantAwareBaseEntity other = (TenantAwareBaseEntity) obj; + final AbstractJpaTenantAwareBaseEntity other = (AbstractJpaTenantAwareBaseEntity) obj; if (tenant == null) { if (other.tenant != null) { return false; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/CacheFieldEntityListener.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/CacheFieldEntityListener.java similarity index 75% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/CacheFieldEntityListener.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/CacheFieldEntityListener.java index 7275cb4ec..b303f33a4 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/CacheFieldEntityListener.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/CacheFieldEntityListener.java @@ -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; +package org.eclipse.hawkbit.repository.jpa.model; import java.io.Serializable; import java.lang.reflect.Field; @@ -15,9 +15,9 @@ import javax.persistence.PostLoad; import javax.persistence.PostRemove; import org.apache.commons.lang3.reflect.FieldUtils; -import org.eclipse.hawkbit.cache.CacheField; -import org.eclipse.hawkbit.cache.CacheKeys; -import org.eclipse.hawkbit.repository.model.helper.CacheManagerHolder; +import org.eclipse.hawkbit.repository.jpa.cache.CacheField; +import org.eclipse.hawkbit.repository.jpa.cache.CacheKeys; +import org.eclipse.hawkbit.repository.jpa.model.helper.CacheManagerHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.Cache; @@ -53,16 +53,11 @@ public class CacheFieldEntityListener { @SuppressWarnings("rawtypes") final String id = ((Identifiable) target).getId().toString(); final Class type = target.getClass(); - findCacheFields(type, id, new CacheFieldCallback() { - @Override - public void fromCache(final Field field, final String cacheKey, final Serializable id) - throws IllegalAccessException { - final Cache cache = cacheManager.getCache(type.getName()); - final ValueWrapper valueWrapper = cache - .get(CacheKeys.entitySpecificCacheKey(id.toString(), cacheKey)); - if (valueWrapper != null && valueWrapper.get() != null) { - FieldUtils.writeField(field, target, valueWrapper.get(), true); - } + findCacheFields(type, id, (field, cacheKey, id1) -> { + final Cache cache = cacheManager.getCache(type.getName()); + final ValueWrapper valueWrapper = cache.get(CacheKeys.entitySpecificCacheKey(id1.toString(), cacheKey)); + if (valueWrapper != null && valueWrapper.get() != null) { + FieldUtils.writeField(field, target, valueWrapper.get(), true); } }); } @@ -82,13 +77,9 @@ public class CacheFieldEntityListener { @SuppressWarnings("rawtypes") final String id = ((Identifiable) target).getId().toString(); final Class type = target.getClass(); - findCacheFields(type, id, new CacheFieldCallback() { - @Override - public void fromCache(final Field field, final String cacheKey, final Serializable id) - throws IllegalAccessException { - final Cache cache = cacheManager.getCache(type.getName()); - cache.evict(CacheKeys.entitySpecificCacheKey(id.toString(), cacheKey)); - } + findCacheFields(type, id, (field, cacheKey, id1) -> { + final Cache cache = cacheManager.getCache(type.getName()); + cache.evict(CacheKeys.entitySpecificCacheKey(id1.toString(), cacheKey)); }); } } @@ -109,6 +100,7 @@ public class CacheFieldEntityListener { } } + @FunctionalInterface private interface CacheFieldCallback { /** * callback methods which is called by the diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTypeElement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/DistributionSetTypeElement.java similarity index 86% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTypeElement.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/DistributionSetTypeElement.java index 8414a6f1a..26a603078 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTypeElement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/DistributionSetTypeElement.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import java.io.Serializable; @@ -21,6 +21,10 @@ import javax.persistence.ManyToOne; import javax.persistence.MapsId; import javax.persistence.Table; +import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.repository.model.DistributionSetType; +import org.eclipse.hawkbit.repository.model.SoftwareModuleType; + /** * Relation element between a {@link DistributionSetType} and its * {@link SoftwareModuleType} elements. @@ -40,12 +44,12 @@ public class DistributionSetTypeElement implements Serializable { @MapsId("dsType") @ManyToOne(optional = false, fetch = FetchType.LAZY) @JoinColumn(name = "distribution_set_type", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_type_element_dstype")) - private DistributionSetType dsType; + private JpaDistributionSetType dsType; @MapsId("smType") @ManyToOne(optional = false, fetch = FetchType.LAZY) @JoinColumn(name = "software_module_type", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_type_element_smtype")) - private SoftwareModuleType smType; + private JpaSoftwareModuleType smType; public DistributionSetTypeElement() { // Default constructor for JPA @@ -62,7 +66,7 @@ public class DistributionSetTypeElement implements Serializable { * to true if the {@link SoftwareModuleType} if * mandatory element in the {@link DistributionSet}. */ - public DistributionSetTypeElement(final DistributionSetType dsType, final SoftwareModuleType smType, + public DistributionSetTypeElement(final JpaDistributionSetType dsType, final JpaSoftwareModuleType smType, final boolean mandatory) { super(); key = new DistributionSetTypeElementCompositeKey(dsType, smType); diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTypeElementCompositeKey.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/DistributionSetTypeElementCompositeKey.java similarity index 89% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTypeElementCompositeKey.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/DistributionSetTypeElementCompositeKey.java index 2ee1aba0d..f94a3784a 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTypeElementCompositeKey.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/DistributionSetTypeElementCompositeKey.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import java.io.Serializable; @@ -40,7 +40,7 @@ public class DistributionSetTypeElementCompositeKey implements Serializable { * @param smType * in the key */ - DistributionSetTypeElementCompositeKey(final DistributionSetType dsType, final SoftwareModuleType smType) { + DistributionSetTypeElementCompositeKey(final JpaDistributionSetType dsType, final JpaSoftwareModuleType smType) { super(); this.dsType = dsType.getId(); this.smType = smType.getId(); diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DsMetadataCompositeKey.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/DsMetadataCompositeKey.java similarity index 95% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DsMetadataCompositeKey.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/DsMetadataCompositeKey.java index adc37d65a..52ad217c0 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DsMetadataCompositeKey.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/DsMetadataCompositeKey.java @@ -6,10 +6,12 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import java.io.Serializable; +import org.eclipse.hawkbit.repository.model.DistributionSet; + /** * The DistributionSet Metadata composite key which contains the meta data key * and the ID of the DistributionSet itself. diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/EntityPropertyChangeListener.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/EntityPropertyChangeListener.java similarity index 78% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/EntityPropertyChangeListener.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/EntityPropertyChangeListener.java index 28b5e677c..2dd0fdb40 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/EntityPropertyChangeListener.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/EntityPropertyChangeListener.java @@ -6,23 +6,23 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.eventbus; +package org.eclipse.hawkbit.repository.jpa.model; import java.util.Map; import java.util.stream.Collectors; -import org.eclipse.hawkbit.eventbus.event.AbstractPropertyChangeEvent; -import org.eclipse.hawkbit.eventbus.event.ActionCreatedEvent; -import org.eclipse.hawkbit.eventbus.event.ActionPropertyChangeEvent; -import org.eclipse.hawkbit.eventbus.event.RolloutGroupPropertyChangeEvent; -import org.eclipse.hawkbit.eventbus.event.RolloutPropertyChangeEvent; -import org.eclipse.hawkbit.executor.AfterTransactionCommitExecutor; +import org.eclipse.hawkbit.repository.eventbus.event.AbstractPropertyChangeEvent; +import org.eclipse.hawkbit.repository.eventbus.event.ActionCreatedEvent; +import org.eclipse.hawkbit.repository.eventbus.event.ActionPropertyChangeEvent; +import org.eclipse.hawkbit.repository.eventbus.event.RolloutGroupPropertyChangeEvent; +import org.eclipse.hawkbit.repository.eventbus.event.RolloutPropertyChangeEvent; +import org.eclipse.hawkbit.repository.jpa.executor.AfterTransactionCommitExecutor; +import org.eclipse.hawkbit.repository.jpa.model.helper.AfterTransactionCommitExecutorHolder; +import org.eclipse.hawkbit.repository.jpa.model.helper.EventBusHolder; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.RolloutGroup; import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity; -import org.eclipse.hawkbit.repository.model.helper.AfterTransactionCommitExecutorHolder; -import org.eclipse.hawkbit.repository.model.helper.EventBusHolder; import org.eclipse.persistence.descriptors.DescriptorEvent; import org.eclipse.persistence.descriptors.DescriptorEventAdapter; import org.eclipse.persistence.internal.sessions.ObjectChangeSet; @@ -52,13 +52,13 @@ public class EntityPropertyChangeListener extends DescriptorEventAdapter { @Override public void postUpdate(final DescriptorEvent event) { - if (event.getObject().getClass().equals(Action.class)) { + if (event.getObject().getClass().equals(JpaAction.class)) { getAfterTransactionCommmitExecutor().afterCommit(() -> getEventBus().post( new ActionPropertyChangeEvent((Action) event.getObject(), getChangeSet(Action.class, event)))); - } else if (event.getObject().getClass().equals(Rollout.class)) { + } else if (event.getObject().getClass().equals(JpaRollout.class)) { getAfterTransactionCommmitExecutor().afterCommit(() -> getEventBus().post( new RolloutPropertyChangeEvent((Rollout) event.getObject(), getChangeSet(Rollout.class, event)))); - } else if (event.getObject().getClass().equals(RolloutGroup.class)) { + } else if (event.getObject().getClass().equals(JpaRolloutGroup.class)) { getAfterTransactionCommmitExecutor().afterCommit( () -> getEventBus().post(new RolloutGroupPropertyChangeEvent((RolloutGroup) event.getObject(), getChangeSet(RolloutGroup.class, event)))); diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Action.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaAction.java similarity index 51% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Action.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaAction.java index eedb36037..2b8744618 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Action.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaAction.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import java.util.List; @@ -29,21 +29,18 @@ import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; -import org.eclipse.hawkbit.cache.CacheField; -import org.eclipse.hawkbit.cache.CacheKeys; +import org.eclipse.hawkbit.repository.jpa.cache.CacheField; +import org.eclipse.hawkbit.repository.jpa.cache.CacheKeys; +import org.eclipse.hawkbit.repository.model.Action; +import org.eclipse.hawkbit.repository.model.ActionStatus; +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.Target; import org.eclipse.persistence.annotations.CascadeOnDelete; /** - *

- * Applicable transition changes of the {@link SoftwareModule}s state of a - * {@link Target}, e.g. install, uninstall, update and preparations for the - * transition change, i.e. download. - *

- * - *

- * Actions are managed by the SP server and applied to the targets by the - * client. - *

+ * JPA implementation of {@link Action}. */ @Table(name = "sp_action", indexes = { @Index(name = "sp_idx_action_01", columnList = "tenant,distribution_set"), @Index(name = "sp_idx_action_02", columnList = "tenant,target,active"), @@ -52,24 +49,19 @@ import org.eclipse.persistence.annotations.CascadeOnDelete; @NamedEntityGraph(name = "Action.all", attributeNodes = { @NamedAttributeNode("distributionSet"), @NamedAttributeNode(value = "target", subgraph = "target.ds") }, subgraphs = @NamedSubgraph(name = "target.ds", attributeNodes = @NamedAttributeNode("assignedDistributionSet"))) }) @Entity -public class Action extends TenantAwareBaseEntity { +// exception squid:S2160 - BaseEntity equals/hashcode is handling correctly for +// sub entities +@SuppressWarnings("squid:S2160") +public class JpaAction extends AbstractJpaTenantAwareBaseEntity implements Action { private static final long serialVersionUID = 1L; - /** - * indicating that target action has no force time {@link #hasForcedTime()}. - */ - public static final long NO_FORCE_TIME = 0L; - - /** - * the {@link DistributionSet} which should be installed by this action. - */ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "distribution_set", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_action_ds")) - private DistributionSet distributionSet; + private JpaDistributionSet distributionSet; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "target", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_action_target")) - private Target target; + private JpaTarget target; @Column(name = "active") private boolean active; @@ -85,17 +77,17 @@ public class Action extends TenantAwareBaseEntity { private Status status; @CascadeOnDelete - @OneToMany(mappedBy = "action", targetEntity = ActionStatus.class, fetch = FetchType.LAZY, cascade = { + @OneToMany(mappedBy = "action", targetEntity = JpaActionStatus.class, fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE }) private List actionStatus; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "rolloutgroup", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_action_rolloutgroup")) - private RolloutGroup rolloutGroup; + private JpaRolloutGroup rolloutGroup; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "rollout", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_action_rollout")) - private Rollout rollout; + private JpaRollout rollout; /** * Note: filled only in {@link Status#DOWNLOAD}. @@ -104,41 +96,31 @@ public class Action extends TenantAwareBaseEntity { @CacheField(key = CacheKeys.DOWNLOAD_PROGRESS_PERCENT) private int downloadProgressPercent; - /** - * @return the distributionSet - */ + @Override public DistributionSet getDistributionSet() { return distributionSet; } - /** - * @param distributionSet - * the distributionSet to set - */ + @Override public void setDistributionSet(final DistributionSet distributionSet) { - this.distributionSet = distributionSet; - } - - /** - * @return true when action is in state {@link Status#CANCELING} or - * {@link Status#CANCELED}, false otherwise - */ - public boolean isCancelingOrCanceled() { - return status == Status.CANCELING || status == Status.CANCELED; + this.distributionSet = (JpaDistributionSet) distributionSet; } public void setActive(final boolean active) { this.active = active; } + @Override public Status getStatus() { return status; } + @Override public void setStatus(final Status status) { this.status = status; } + @Override public int getDownloadProgressPercent() { return downloadProgressPercent; } @@ -147,6 +129,7 @@ public class Action extends TenantAwareBaseEntity { this.downloadProgressPercent = downloadProgressPercent; } + @Override public boolean isActive() { return active; } @@ -155,25 +138,27 @@ public class Action extends TenantAwareBaseEntity { this.actionType = actionType; } - /** - * @return the actionType - */ + @Override public ActionType getActionType() { return actionType; } + @Override public List getActionStatus() { return actionStatus; } + @Override public void setTarget(final Target target) { - this.target = target; + this.target = (JpaTarget) target; } + @Override public Target getTarget() { return target; } + @Override public long getForcedTime() { return forcedTime; } @@ -182,63 +167,22 @@ public class Action extends TenantAwareBaseEntity { this.forcedTime = forcedTime; } + @Override public RolloutGroup getRolloutGroup() { return rolloutGroup; } public void setRolloutGroup(final RolloutGroup rolloutGroup) { - this.rolloutGroup = rolloutGroup; + this.rolloutGroup = (JpaRolloutGroup) rolloutGroup; } + @Override public Rollout getRollout() { return rollout; } public void setRollout(final Rollout rollout) { - this.rollout = rollout; - } - - /** - * checks if the {@link #forcedTime} is hit by the given - * {@code hitTimeMillis}, by means if the given milliseconds are greater - * than the forcedTime. - * - * @param hitTimeMillis - * the milliseconds, mostly the - * {@link System#currentTimeMillis()} - * @return {@code true} if this {@link #type} is in - * {@link ActionType#TIMEFORCED} and the given {@code hitTimeMillis} - * is greater than the {@link #forcedTime} otherwise {@code false} - */ - public boolean isHitAutoForceTime(final long hitTimeMillis) { - if (actionType == ActionType.TIMEFORCED) { - return hitTimeMillis >= forcedTime; - } - return false; - } - - /** - * @return {@code true} if either the {@link #type} is - * {@link ActionType#FORCED} or {@link ActionType#TIMEFORCED} but - * then if the {@link #forcedTime} has been exceeded otherwise - * always {@code false} - */ - public boolean isForce() { - switch (actionType) { - case FORCED: - return true; - case TIMEFORCED: - return isHitAutoForceTime(System.currentTimeMillis()); - default: - return false; - } - } - - /** - * @return true when action is forced, false otherwise - */ - public boolean isForced() { - return actionType == ActionType.FORCED; + this.rollout = (JpaRollout) rollout; } @Override @@ -246,67 +190,4 @@ public class Action extends TenantAwareBaseEntity { return "Action [distributionSet=" + distributionSet + ", getId()=" + getId() + "]"; } - /** - * Action status as reported by the controller. - * - * Be aware that JPA is persisting the ordinal number of the enum by means - * the ordered number in the enum. So don't re-order the enums within the - * Status enum declaration! - * - */ - public enum Status { - /** - * Action is finished successfully for this target. - */ - FINISHED, - - /** - * Action has failed for this target. - */ - ERROR, - - /** - * Action is still running but with warnings. - */ - WARNING, - - /** - * Action is still running for this target. - */ - RUNNING, - - /** - * Action has been canceled for this target. - */ - CANCELED, - - /** - * Action is in canceling state and waiting for controller confirmation. - */ - CANCELING, - - /** - * Action has been presented to the target. - */ - RETRIEVED, - - /** - * Action needs download by this target which has now started. - */ - DOWNLOAD, - - /** - * Action is in waiting state, e.g. the action is scheduled in a rollout - * but not yet activated. - */ - SCHEDULED; - } - - /** - * The action type for this action relation. - * - */ - public enum ActionType { - FORCED, SOFT, TIMEFORCED; - } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ActionStatus.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaActionStatus.java similarity index 79% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ActionStatus.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaActionStatus.java index c8d320abd..ef1ad3d1e 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ActionStatus.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaActionStatus.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import java.util.ArrayList; import java.util.List; @@ -25,7 +25,9 @@ import javax.persistence.NamedAttributeNode; import javax.persistence.NamedEntityGraph; import javax.persistence.Table; +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.persistence.annotations.CascadeOnDelete; import com.google.common.base.Splitter; @@ -38,7 +40,10 @@ import com.google.common.base.Splitter; @Index(name = "sp_idx_action_status_prim", columnList = "tenant,id") }) @NamedEntityGraph(name = "ActionStatus.withMessages", attributeNodes = { @NamedAttributeNode("messages") }) @Entity -public class ActionStatus extends TenantAwareBaseEntity { +// exception squid:S2160 - BaseEntity equals/hashcode is handling correctly for +// sub entities +@SuppressWarnings("squid:S2160") +public class JpaActionStatus extends AbstractJpaTenantAwareBaseEntity implements ActionStatus { private static final long serialVersionUID = 1L; @Column(name = "target_occurred_at") @@ -46,7 +51,7 @@ public class ActionStatus extends TenantAwareBaseEntity { @ManyToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "action", nullable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_act_stat_action")) - private Action action; + private JpaAction action; @Column(name = "status") private Status status; @@ -68,8 +73,8 @@ public class ActionStatus extends TenantAwareBaseEntity { * @param occurredAt * the occurred timestamp */ - public ActionStatus(final Action action, final Status status, final Long occurredAt) { - this.action = action; + public JpaActionStatus(final Action action, final Status status, final Long occurredAt) { + this.action = (JpaAction) action; this.status = status; this.occurredAt = occurredAt; } @@ -86,56 +91,58 @@ public class ActionStatus extends TenantAwareBaseEntity { * @param messages * the messages which should be added to this action status */ - public ActionStatus(final Action action, final Status status, final Long occurredAt, final String... messages) { + public JpaActionStatus(final JpaAction action, final Status status, final Long occurredAt, final String message) { this.action = action; this.status = status; this.occurredAt = occurredAt; - for (final String msg : messages) { - addMessage(msg); - } + addMessage(message); } /** * JPA default constructor. */ - public ActionStatus() { + public JpaActionStatus() { // JPA default constructor. } + @Override public Long getOccurredAt() { return occurredAt; } + @Override public void setOccurredAt(final Long occurredAt) { this.occurredAt = occurredAt; } - /** - * Adds message including splitting in case it exceeds 512 length. - * - * @param message - * to add - */ + @Override public final void addMessage(final String message) { - Splitter.fixedLength(512).split(message).forEach(messages::add); + if (message != null) { + Splitter.fixedLength(512).split(message).forEach(messages::add); + } } + @Override public List getMessages() { return messages; } + @Override public Action getAction() { return action; } + @Override public void setAction(final Action action) { - this.action = action; + this.action = (JpaAction) action; } + @Override public Status getStatus() { return status; } + @Override public void setStatus(final Status status) { this.status = status; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ActionWithStatusCount.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaActionWithStatusCount.java similarity index 64% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ActionWithStatusCount.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaActionWithStatusCount.java index 73eab32f9..32b01cbe2 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ActionWithStatusCount.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaActionWithStatusCount.java @@ -6,29 +6,25 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; +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; /** * Custom JPA Model for querying {@link Action} include the count of the * action's {@link ActionStatus}. * */ -public class ActionWithStatusCount { +public class JpaActionWithStatusCount implements ActionWithStatusCount { private final Long actionStatusCount; - private final Long actionId; - private final ActionType actionType; - private final boolean actionActive; - private final long actionForceTime; - private final Status actionStatus; - private final Long actionCreatedAt; - private final Long actionLastModifiedAt; private final Long dsId; private final String dsName; private final String dsVersion; - private final Action action; + private final JpaAction action; private final String rolloutName; /** @@ -60,82 +56,57 @@ public class ActionWithStatusCount { * @param rolloutName * the rollout name */ - - public ActionWithStatusCount(final Long actionId, final ActionType actionType, final boolean active, + // Exception squid:S00107 - needed this way for JPA to fill the view + @SuppressWarnings("squid:S00107") + public JpaActionWithStatusCount(final Long actionId, final ActionType actionType, final boolean active, final long forcedTime, final Status status, final Long actionCreatedAt, final Long actionLastModifiedAt, final Long dsId, final String dsName, final String dsVersion, final Long actionStatusCount, final String rolloutName) { - this.actionId = actionId; - this.actionType = actionType; - actionActive = active; - actionForceTime = forcedTime; - actionStatus = status; - this.actionCreatedAt = actionCreatedAt; - this.actionLastModifiedAt = actionLastModifiedAt; this.dsId = dsId; this.dsName = dsName; this.dsVersion = dsVersion; this.actionStatusCount = actionStatusCount; this.rolloutName = rolloutName; - action = new Action(); + action = new JpaAction(); action.setActionType(actionType); - action.setActive(actionActive); - action.setForcedTime(actionForceTime); - action.setStatus(actionStatus); + action.setActive(active); + action.setForcedTime(forcedTime); + action.setStatus(status); action.setId(actionId); + action.setActionType(actionType); + action.setCreatedAt(actionCreatedAt); + action.setLastModifiedAt(actionLastModifiedAt); + } + @Override public Action getAction() { return action; } - public Long getActionId() { - return actionId; - } - - public ActionType getActionType() { - return actionType; - } - - public boolean isActionActive() { - return actionActive; - } - - public long getActionForceTime() { - return actionForceTime; - } - - public Status getActionStatus() { - return actionStatus; - } - - public Long getActionCreatedAt() { - return actionCreatedAt; - } - - public Long getActionLastModifiedAt() { - return actionLastModifiedAt; - } - + @Override public Long getDsId() { return dsId; } + @Override public String getDsName() { return dsName; } + @Override public String getDsVersion() { return dsVersion; } + @Override public Long getActionStatusCount() { return actionStatusCount; } + @Override public String getRolloutName() { return rolloutName; } - } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSet.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSet.java similarity index 79% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSet.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSet.java index a9d390284..676215424 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSet.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSet.java @@ -6,9 +6,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; @@ -34,17 +35,19 @@ import javax.persistence.UniqueConstraint; import org.eclipse.hawkbit.repository.exception.DistributionSetTypeUndefinedException; import org.eclipse.hawkbit.repository.exception.UnsupportedSoftwareModuleForThisDistributionSetException; +import org.eclipse.hawkbit.repository.model.Action; +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.SoftwareModule; +import org.eclipse.hawkbit.repository.model.SoftwareModuleType; +import org.eclipse.hawkbit.repository.model.Target; +import org.eclipse.hawkbit.repository.model.TargetInfo; import org.eclipse.persistence.annotations.CascadeOnDelete; /** - *

- * The {@link DistributionSet} is defined in the SP repository and contains at - * least an OS and an Agent Hub. - *

- * - *

- * A {@link Target} has exactly one target {@link DistributionSet} assigned. - *

+ * Jpa implementation of {@link DistributionSet}. * */ @Entity @@ -55,52 +58,56 @@ import org.eclipse.persistence.annotations.CascadeOnDelete; @Index(name = "sp_idx_distribution_set_prim", columnList = "tenant,id") }) @NamedEntityGraph(name = "DistributionSet.detail", attributeNodes = { @NamedAttributeNode("modules"), @NamedAttributeNode("tags"), @NamedAttributeNode("type") }) -public class DistributionSet extends NamedVersionedEntity { +// exception squid:S2160 - BaseEntity equals/hashcode is handling correctly for +// sub entities +@SuppressWarnings("squid:S2160") +public class JpaDistributionSet extends AbstractJpaNamedVersionedEntity implements DistributionSet { private static final long serialVersionUID = 1L; @Column(name = "required_migration_step") - private boolean requiredMigrationStep = false; + private boolean requiredMigrationStep; - @ManyToMany(targetEntity = SoftwareModule.class, fetch = FetchType.LAZY) + @ManyToMany(targetEntity = JpaSoftwareModule.class, fetch = FetchType.LAZY) @JoinTable(name = "sp_ds_module", joinColumns = { @JoinColumn(name = "ds_id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_module_ds")) }, inverseJoinColumns = { @JoinColumn(name = "module_id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_module_module")) }) private final Set modules = new HashSet<>(); - @ManyToMany(targetEntity = DistributionSetTag.class) + @ManyToMany(targetEntity = JpaDistributionSetTag.class) @JoinTable(name = "sp_ds_dstag", joinColumns = { @JoinColumn(name = "ds", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_dstag_ds")) }, inverseJoinColumns = { @JoinColumn(name = "TAG", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_dstag_tag")) }) private Set tags = new HashSet<>(); @Column(name = "deleted") - private boolean deleted = false; + private boolean deleted; - @OneToMany(mappedBy = "assignedDistributionSet", targetEntity = Target.class, fetch = FetchType.LAZY) + @OneToMany(mappedBy = "assignedDistributionSet", targetEntity = JpaTarget.class, fetch = FetchType.LAZY) private List assignedToTargets; - @OneToMany(mappedBy = "installedDistributionSet", targetEntity = TargetInfo.class, fetch = FetchType.LAZY) + @OneToMany(mappedBy = "installedDistributionSet", targetEntity = JpaTargetInfo.class, fetch = FetchType.LAZY) private List installedAtTargets; - @OneToMany(mappedBy = "distributionSet", targetEntity = Action.class, fetch = FetchType.LAZY) + @OneToMany(mappedBy = "distributionSet", targetEntity = JpaAction.class, fetch = FetchType.LAZY) private List actions; @CascadeOnDelete - @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE }) + @OneToMany(fetch = FetchType.LAZY, targetEntity = JpaDistributionSetMetadata.class, cascade = { + CascadeType.REMOVE }) @JoinColumn(name = "ds_id", insertable = false, updatable = false) private final List metadata = new ArrayList<>(); - @ManyToOne(fetch = FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY, targetEntity = JpaDistributionSetType.class) @JoinColumn(name = "ds_id", nullable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_dstype_ds")) private DistributionSetType type; @Column(name = "complete") - private boolean complete = false; + private boolean complete; /** * Default constructor. */ - public DistributionSet() { + public JpaDistributionSet() { super(); } @@ -118,8 +125,8 @@ public class DistributionSet extends NamedVersionedEntity { * @param moduleList * {@link SoftwareModule}s of the {@link DistributionSet} */ - public DistributionSet(final String name, final String version, final String description, - final DistributionSetType type, final Iterable moduleList) { + public JpaDistributionSet(final String name, final String version, final String description, + final DistributionSetType type, final Collection moduleList) { super(name, version, description); this.type = type; @@ -131,17 +138,17 @@ public class DistributionSet extends NamedVersionedEntity { } } + @Override public Set getTags() { return tags; } + @Override public boolean isDeleted() { return deleted; } - /** - * @return immutable list of meta data elements. - */ + @Override public List getMetadata() { return Collections.unmodifiableList(metadata); } @@ -150,15 +157,18 @@ public class DistributionSet extends NamedVersionedEntity { return actions; } + @Override public boolean isRequiredMigrationStep() { return requiredMigrationStep; } + @Override public DistributionSet setDeleted(final boolean deleted) { this.deleted = deleted; return this; } + @Override public DistributionSet setRequiredMigrationStep(final boolean isRequiredMigrationStep) { requiredMigrationStep = isRequiredMigrationStep; return this; @@ -169,16 +179,12 @@ public class DistributionSet extends NamedVersionedEntity { return this; } - /** - * @return the assignedTargets - */ + @Override public List getAssignedTargets() { return assignedToTargets; } - /** - * @return the installedTargets - */ + @Override public List getInstalledTargets() { return installedAtTargets; } @@ -189,24 +195,12 @@ public class DistributionSet extends NamedVersionedEntity { + ", getId()=" + getId() + "]"; } - /** - * - * @return unmodifiableSet of {@link SoftwareModule}. - */ + @Override public Set getModules() { return Collections.unmodifiableSet(modules); } - public DistributionSetIdName getDistributionSetIdName() { - return new DistributionSetIdName(getId(), getName(), getVersion()); - } - - /** - * @param softwareModule - * @return true if the module was added and false - * if it already existed in the set - * - */ + @Override public boolean addModule(final SoftwareModule softwareModule) { // we cannot allow that modules are added without a type defined @@ -243,13 +237,7 @@ public class DistributionSet extends NamedVersionedEntity { return false; } - /** - * Removed given {@link SoftwareModule} from this DS instance. - * - * @param softwareModule - * to remove - * @return true if element was found and removed - */ + @Override public boolean removeModule(final SoftwareModule softwareModule) { final Optional found = modules.stream() .filter(module -> module.getId().equals(softwareModule.getId())).findFirst(); @@ -264,14 +252,7 @@ public class DistributionSet extends NamedVersionedEntity { } - /** - * Searches through modules for the given type. - * - * @param type - * to search for - * @return SoftwareModule of given type or null if not in the - * list. - */ + @Override public SoftwareModule findFirstModuleByType(final SoftwareModuleType type) { final Optional result = modules.stream().filter(module -> module.getType().equals(type)) .findFirst(); @@ -283,15 +264,19 @@ public class DistributionSet extends NamedVersionedEntity { return null; } + @Override public DistributionSetType getType() { return type; } + @Override public void setType(final DistributionSetType type) { this.type = type; } + @Override public boolean isComplete() { return complete; } + } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetMetadata.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetMetadata.java similarity index 70% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetMetadata.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetMetadata.java index 67a99506c..3f4323bbe 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetMetadata.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetMetadata.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import javax.persistence.ConstraintMode; import javax.persistence.Entity; @@ -18,6 +18,9 @@ import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; +import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.repository.model.DistributionSetMetadata; + /** * Meta data for {@link DistributionSet}. * @@ -25,21 +28,21 @@ import javax.persistence.Table; @IdClass(DsMetadataCompositeKey.class) @Entity @Table(name = "sp_ds_metadata") -public class DistributionSetMetadata extends MetaData { +public class JpaDistributionSetMetadata extends AbstractJpaMetaData implements DistributionSetMetadata { private static final long serialVersionUID = 1L; @Id @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "ds_id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_metadata_ds")) - private DistributionSet distributionSet; + private JpaDistributionSet distributionSet; - public DistributionSetMetadata() { + public JpaDistributionSetMetadata() { // default public constructor for JPA } - public DistributionSetMetadata(final String key, final DistributionSet distributionSet, final String value) { + public JpaDistributionSetMetadata(final String key, final DistributionSet distributionSet, final String value) { super(key, value); - this.distributionSet = distributionSet; + this.distributionSet = (JpaDistributionSet) distributionSet; } public DsMetadataCompositeKey getId() { @@ -47,9 +50,10 @@ public class DistributionSetMetadata extends MetaData { } public void setDistributionSet(final DistributionSet distributionSet) { - this.distributionSet = distributionSet; + this.distributionSet = (JpaDistributionSet) distributionSet; } + @Override public DistributionSet getDistributionSet() { return distributionSet; } @@ -63,11 +67,13 @@ public class DistributionSetMetadata extends MetaData { } @Override + // exception squid:S2259 - obj is checked for null in super + @SuppressWarnings("squid:S2259") public boolean equals(final Object obj) { if (!super.equals(obj)) { return false; } - final DistributionSetMetadata other = (DistributionSetMetadata) obj; + final JpaDistributionSetMetadata other = (JpaDistributionSetMetadata) obj; if (distributionSet == null) { if (other.distributionSet != null) { return false; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTag.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetTag.java similarity index 76% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTag.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetTag.java index 137fde5b9..1663fb620 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTag.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetTag.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import java.util.List; @@ -17,6 +17,9 @@ import javax.persistence.ManyToMany; import javax.persistence.Table; import javax.persistence.UniqueConstraint; +import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.repository.model.DistributionSetTag; + /** * A {@link DistributionSetTag} is used to describe DistributionSet attributes * and use them also for filtering the DistributionSet list. @@ -26,10 +29,10 @@ import javax.persistence.UniqueConstraint; @Table(name = "sp_distributionset_tag", indexes = { @Index(name = "sp_idx_distribution_set_tag_prim", columnList = "tenant,id") }, uniqueConstraints = @UniqueConstraint(columnNames = { "name", "tenant" }, name = "uk_ds_tag")) -public class DistributionSetTag extends Tag { +public class JpaDistributionSetTag extends AbstractJpaTag implements DistributionSetTag { private static final long serialVersionUID = 1L; - @ManyToMany(mappedBy = "tags", targetEntity = DistributionSet.class, fetch = FetchType.LAZY) + @ManyToMany(mappedBy = "tags", targetEntity = JpaDistributionSet.class, fetch = FetchType.LAZY) private List assignedToDistributionSet; /** @@ -38,7 +41,7 @@ public class DistributionSetTag extends Tag { * @param name * of the {@link DistributionSetTag} **/ - public DistributionSetTag(final String name) { + public JpaDistributionSetTag(final String name) { super(name, null, null); } @@ -52,14 +55,18 @@ public class DistributionSetTag extends Tag { * @param colour * of tag in UI */ - public DistributionSetTag(final String name, final String description, final String colour) { + public JpaDistributionSetTag(final String name, final String description, final String colour) { super(name, description, colour); } - DistributionSetTag() { - super(); + /** + * Default constructor for JPA. + */ + public JpaDistributionSetTag() { + // Default constructor for JPA. } + @Override public List getAssignedToDistributionSet() { return assignedToDistributionSet; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetType.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetType.java similarity index 50% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetType.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetType.java index 61d2fc58c..54aed44dd 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetType.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetType.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import java.util.HashSet; import java.util.Optional; @@ -23,6 +23,10 @@ import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.UniqueConstraint; +import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.repository.model.DistributionSetType; +import org.eclipse.hawkbit.repository.model.SoftwareModuleType; + /** * A distribution set type defines which software module types can or have to be * {@link DistributionSet}. @@ -34,7 +38,10 @@ import javax.persistence.UniqueConstraint; @Index(name = "sp_idx_distribution_set_type_prim", columnList = "tenant,id") }, uniqueConstraints = { @UniqueConstraint(columnNames = { "name", "tenant" }, name = "uk_dst_name"), @UniqueConstraint(columnNames = { "type_key", "tenant" }, name = "uk_dst_key") }) -public class DistributionSetType extends NamedEntity { +// exception squid:S2160 - BaseEntity equals/hashcode is handling correctly for +// sub entities +@SuppressWarnings("squid:S2160") +public class JpaDistributionSetType extends AbstractJpaNamedEntity implements DistributionSetType { private static final long serialVersionUID = 1L; @OneToMany(targetEntity = DistributionSetTypeElement.class, cascade = { @@ -49,9 +56,9 @@ public class DistributionSetType extends NamedEntity { private String colour; @Column(name = "deleted") - private boolean deleted = false; + private boolean deleted; - public DistributionSetType() { + public JpaDistributionSetType() { // default public constructor for JPA } @@ -65,7 +72,7 @@ public class DistributionSetType extends NamedEntity { * @param description * of the type */ - public DistributionSetType(final String key, final String name, final String description) { + public JpaDistributionSetType(final String key, final String name, final String description) { this(key, name, description, null); } @@ -81,162 +88,53 @@ public class DistributionSetType extends NamedEntity { * @param color * of the type. It will be null by default */ - public DistributionSetType(final String key, final String name, final String description, final String color) { + public JpaDistributionSetType(final String key, final String name, final String description, final String color) { super(name, description); this.key = key; colour = color; } - /** - * @return the deleted - */ + @Override public boolean isDeleted() { return deleted; } - /** - * @param deleted - * the deleted to set - */ public void setDeleted(final boolean deleted) { this.deleted = deleted; } + @Override public Set getMandatoryModuleTypes() { return elements.stream().filter(element -> element.isMandatory()).map(element -> element.getSmType()) .collect(Collectors.toSet()); } + @Override public Set getOptionalModuleTypes() { return elements.stream().filter(element -> !element.isMandatory()).map(element -> element.getSmType()) .collect(Collectors.toSet()); } - /** - * Checks if the given {@link SoftwareModuleType} is in this - * {@link DistributionSetType}. - * - * @param softwareModuleType - * search for - * @return true if found - */ - public boolean containsModuleType(final SoftwareModuleType softwareModuleType) { - for (final DistributionSetTypeElement distributionSetTypeElement : elements) { - if (distributionSetTypeElement.getSmType().equals(softwareModuleType)) { - return true; - } - - } - return false; - } - - /** - * Checks if the given {@link SoftwareModuleType} is in this - * {@link DistributionSetType} and defined as - * {@link DistributionSetTypeElement#isMandatory()}. - * - * @param softwareModuleType - * search for - * @return true if found - */ - public boolean containsMandatoryModuleType(final SoftwareModuleType softwareModuleType) { - return elements.stream().filter(element -> element.isMandatory()) - .filter(element -> element.getSmType().equals(softwareModuleType)).findFirst().isPresent(); - - } - - /** - * Checks if the given {@link SoftwareModuleType} is in this - * {@link DistributionSetType} and defined as - * {@link DistributionSetTypeElement#isMandatory()}. - * - * @param softwareModuleType - * search for by {@link SoftwareModuleType#getId()} - * @return true if found - */ - public boolean containsMandatoryModuleType(final Long softwareModuleTypeId) { - return elements.stream().filter(element -> element.isMandatory()) - .filter(element -> element.getSmType().getId().equals(softwareModuleTypeId)).findFirst().isPresent(); - - } - - /** - * Checks if the given {@link SoftwareModuleType} is in this - * {@link DistributionSetType} and NOT defined as - * {@link DistributionSetTypeElement#isMandatory()}. - * - * @param softwareModuleType - * search for - * @return true if found - */ - public boolean containsOptionalModuleType(final SoftwareModuleType softwareModuleType) { - return elements.stream().filter(element -> !element.isMandatory()) - .filter(element -> element.getSmType().equals(softwareModuleType)).findFirst().isPresent(); - - } - - /** - * Checks if the given {@link SoftwareModuleType} is in this - * {@link DistributionSetType} and NOT defined as - * {@link DistributionSetTypeElement#isMandatory()}. - * - * @param softwareModuleTypeId - * search by {@link SoftwareModuleType#getId()} - * @return true if found - */ - public boolean containsOptionalModuleType(final Long softwareModuleTypeId) { - return elements.stream().filter(element -> !element.isMandatory()) - .filter(element -> element.getSmType().getId().equals(softwareModuleTypeId)).findFirst().isPresent(); - - } - - /** - * Compares the modules of this {@link DistributionSetType} and the given - * one. - * - * @param dsType - * to compare with - * @return true if the lists are identical. - */ + @Override public boolean areModuleEntriesIdentical(final DistributionSetType dsType) { - return new HashSet(dsType.elements).equals(elements); + return new HashSet(((JpaDistributionSetType) dsType).elements).equals(elements); } - /** - * Adds {@link SoftwareModuleType} that is optional for the - * {@link DistributionSet}. - * - * @param smType - * to add - * @return updated instance - */ + @Override public DistributionSetType addOptionalModuleType(final SoftwareModuleType smType) { - elements.add(new DistributionSetTypeElement(this, smType, false)); + elements.add(new DistributionSetTypeElement(this, (JpaSoftwareModuleType) smType, false)); return this; } - /** - * Adds {@link SoftwareModuleType} that is mandatory for the - * {@link DistributionSet}. - * - * @param smType - * to add - * @return updated instance - */ + @Override public DistributionSetType addMandatoryModuleType(final SoftwareModuleType smType) { - elements.add(new DistributionSetTypeElement(this, smType, true)); + elements.add(new DistributionSetTypeElement(this, (JpaSoftwareModuleType) smType, true)); return this; } - /** - * Removes {@link SoftwareModuleType} from the list. - * - * @param smTypeId - * to remove - * @return updated instance - */ + @Override public DistributionSetType removeModuleType(final Long smTypeId) { // we search by id (standard equals compares also revison) final Optional found = elements.stream() @@ -249,29 +147,28 @@ public class DistributionSetType extends NamedEntity { return this; } + @Override public String getKey() { return key; } + @Override public void setKey(final String key) { this.key = key; } - /** - * @param distributionSet - * to check for completeness - * @return true if the all mandatory software module types are - * in the system. - */ + @Override public boolean checkComplete(final DistributionSet distributionSet) { return distributionSet.getModules().stream().map(module -> module.getType()).collect(Collectors.toList()) .containsAll(getMandatoryModuleTypes()); } + @Override public String getColour() { return colour; } + @Override public void setColour(final String colour) { this.colour = colour; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifact.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaExternalArtifact.java similarity index 76% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifact.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaExternalArtifact.java index 898c685a5..b8408cdcc 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifact.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaExternalArtifact.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import java.net.URL; @@ -21,6 +21,10 @@ import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.validation.constraints.NotNull; +import org.eclipse.hawkbit.repository.model.ExternalArtifact; +import org.eclipse.hawkbit.repository.model.ExternalArtifactProvider; +import org.eclipse.hawkbit.repository.model.SoftwareModule; + /** * External artifact representation with all the necessary information to * generate an artifact {@link URL} at runtime. @@ -29,12 +33,15 @@ import javax.validation.constraints.NotNull; @Table(name = "sp_external_artifact", indexes = { @Index(name = "sp_idx_external_artifact_prim", columnList = "id,tenant") }) @Entity -public class ExternalArtifact extends Artifact { +// exception squid:S2160 - BaseEntity equals/hashcode is handling correctly for +// sub entities +@SuppressWarnings("squid:S2160") +public class JpaExternalArtifact extends AbstractJpaArtifact implements ExternalArtifact { private static final long serialVersionUID = 1L; @ManyToOne @JoinColumn(name = "provider", nullable = false, updatable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_art_to_ext_provider")) - private ExternalArtifactProvider externalArtifactProvider; + private JpaExternalArtifactProvider externalArtifactProvider; @Column(name = "url_suffix", length = 512) private String urlSuffix; @@ -42,12 +49,12 @@ public class ExternalArtifact extends Artifact { // CascadeType.PERSIST as we register ourself at the BSM @ManyToOne(optional = false, cascade = { CascadeType.PERSIST }) @JoinColumn(name = "software_module", nullable = false, updatable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_external_assigned_sm")) - private SoftwareModule softwareModule; + private JpaSoftwareModule softwareModule; /** * Default constructor. */ - public ExternalArtifact() { + public JpaExternalArtifact() { super(); } @@ -61,10 +68,10 @@ public class ExternalArtifact extends Artifact { * @param softwareModule * of the artifact */ - public ExternalArtifact(@NotNull final ExternalArtifactProvider externalArtifactProvider, final String urlSuffix, + public JpaExternalArtifact(@NotNull final ExternalArtifactProvider externalArtifactProvider, final String urlSuffix, final SoftwareModule softwareModule) { setSoftwareModule(softwareModule); - this.externalArtifactProvider = externalArtifactProvider; + this.externalArtifactProvider = (JpaExternalArtifactProvider) externalArtifactProvider; if (urlSuffix != null) { this.urlSuffix = urlSuffix; @@ -82,23 +89,26 @@ public class ExternalArtifact extends Artifact { } public final void setSoftwareModule(final SoftwareModule softwareModule) { - this.softwareModule = softwareModule; + this.softwareModule = (JpaSoftwareModule) softwareModule; this.softwareModule.addArtifact(this); } + @Override public ExternalArtifactProvider getExternalArtifactProvider() { return externalArtifactProvider; } + @Override public String getUrl() { return new StringBuilder().append(externalArtifactProvider.getBasePath()).append(urlSuffix).toString(); } + @Override public String getUrlSuffix() { return urlSuffix; } - public void setExternalArtifactProvider(final ExternalArtifactProvider externalArtifactProvider) { + public void setExternalArtifactProvider(final JpaExternalArtifactProvider externalArtifactProvider) { this.externalArtifactProvider = externalArtifactProvider; } @@ -106,6 +116,7 @@ public class ExternalArtifact extends Artifact { * @param urlSuffix * the urlSuffix to set */ + @Override public void setUrlSuffix(final String urlSuffix) { this.urlSuffix = urlSuffix; } @@ -123,7 +134,7 @@ public class ExternalArtifact extends Artifact { if (!super.equals(obj)) { return false; } - if (!(obj instanceof ExternalArtifact)) { + if (!(obj instanceof JpaExternalArtifact)) { return false; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifactProvider.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaExternalArtifactProvider.java similarity index 73% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifactProvider.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaExternalArtifactProvider.java index 9fa8714ac..7a4e2a067 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifactProvider.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaExternalArtifactProvider.java @@ -6,23 +6,27 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Index; import javax.persistence.Table; +import org.eclipse.hawkbit.repository.model.ExternalArtifact; +import org.eclipse.hawkbit.repository.model.ExternalArtifactProvider; + /** - * External repositories for artifact storage. The SP server provides URLs for - * the targets to download from these external resources but does not access - * them itself. + * JPA implementation of {@link ExternalArtifactProvider}. * */ @Table(name = "sp_external_provider", indexes = { @Index(name = "sp_idx_external_provider_prim", columnList = "tenant,id") }) @Entity -public class ExternalArtifactProvider extends NamedEntity { +// exception squid:S2160 - BaseEntity equals/hashcode is handling correctly for +// sub entities +@SuppressWarnings("squid:S2160") +public class JpaExternalArtifactProvider extends AbstractJpaNamedEntity implements ExternalArtifactProvider { private static final long serialVersionUID = 1L; @Column(name = "base_url", length = 512, nullable = false) @@ -44,31 +48,35 @@ public class ExternalArtifactProvider extends NamedEntity { * that is used if {@link ExternalArtifact#getUrlSuffix()} is * empty. */ - public ExternalArtifactProvider(final String name, final String description, final String baseURL, + public JpaExternalArtifactProvider(final String name, final String description, final String baseURL, final String defaultUrlSuffix) { super(name, description); basePath = baseURL; defaultSuffix = defaultUrlSuffix; } - ExternalArtifactProvider() { + JpaExternalArtifactProvider() { super(); defaultSuffix = ""; basePath = ""; } + @Override public String getBasePath() { return basePath; } + @Override public String getDefaultSuffix() { return defaultSuffix; } + @Override public void setBasePath(final String basePath) { this.basePath = basePath; } + @Override public void setDefaultSuffix(final String defaultSuffix) { this.defaultSuffix = defaultSuffix; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/LocalArtifact.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaLocalArtifact.java similarity index 80% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/LocalArtifact.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaLocalArtifact.java index 8afcdc168..52cc01b20 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/LocalArtifact.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaLocalArtifact.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import javax.persistence.CascadeType; import javax.persistence.Column; @@ -19,22 +19,23 @@ import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.validation.constraints.NotNull; +import org.eclipse.hawkbit.repository.model.LocalArtifact; +import org.eclipse.hawkbit.repository.model.SoftwareModule; + import com.mongodb.gridfs.GridFS; import com.mongodb.gridfs.GridFSFile; /** - * Tenant specific locally stored artifact representation that is used by - * {@link SoftwareModule} . It contains all information that is provided by the - * user while all SP server generated information related to the artifact (hash, - * length) is stored directly with the binary itself. - * - * + * JPA implementation of {@link LocalArtifact}. * */ @Table(name = "sp_artifact", indexes = { @Index(name = "sp_idx_artifact_01", columnList = "tenant,software_module"), @Index(name = "sp_idx_artifact_prim", columnList = "tenant,id") }) @Entity -public class LocalArtifact extends Artifact { +// exception squid:S2160 - BaseEntity equals/hashcode is handling correctly for +// sub entities +@SuppressWarnings("squid:S2160") +public class JpaLocalArtifact extends AbstractJpaArtifact implements LocalArtifact { private static final long serialVersionUID = 1L; @NotNull @@ -47,12 +48,12 @@ public class LocalArtifact extends Artifact { @ManyToOne(optional = false, cascade = { CascadeType.PERSIST }) @JoinColumn(name = "software_module", nullable = false, updatable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_assigned_sm")) - private SoftwareModule softwareModule; + private JpaSoftwareModule softwareModule; /** * Default constructor. */ - public LocalArtifact() { + public JpaLocalArtifact() { super(); } @@ -66,7 +67,7 @@ public class LocalArtifact extends Artifact { * @param softwareModule * of this artifact */ - public LocalArtifact(@NotNull final String gridFsFileName, @NotNull final String filename, + public JpaLocalArtifact(@NotNull final String gridFsFileName, @NotNull final String filename, final SoftwareModule softwareModule) { setSoftwareModule(softwareModule); this.gridFsFileName = gridFsFileName; @@ -99,7 +100,7 @@ public class LocalArtifact extends Artifact { } public final void setSoftwareModule(final SoftwareModule softwareModule) { - this.softwareModule = softwareModule; + this.softwareModule = (JpaSoftwareModule) softwareModule; this.softwareModule.addArtifact(this); } @@ -107,6 +108,7 @@ public class LocalArtifact extends Artifact { return gridFsFileName; } + @Override public String getFilename() { return filename; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Rollout.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaRollout.java similarity index 77% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Rollout.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaRollout.java index a7f9b10cb..3cbe65717 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Rollout.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaRollout.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import java.util.List; @@ -25,23 +25,30 @@ import javax.persistence.Table; import javax.persistence.Transient; import javax.persistence.UniqueConstraint; -import org.eclipse.hawkbit.cache.CacheField; -import org.eclipse.hawkbit.cache.CacheKeys; +import org.eclipse.hawkbit.repository.jpa.cache.CacheField; +import org.eclipse.hawkbit.repository.jpa.cache.CacheKeys; import org.eclipse.hawkbit.repository.model.Action.ActionType; +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.TotalTargetCountStatus; /** - * @author Michael Hirsch + * JPA implementation of a {@link Rollout}. * */ @Entity @Table(name = "sp_rollout", indexes = { @Index(name = "sp_idx_rollout_01", columnList = "tenant,name") }, uniqueConstraints = @UniqueConstraint(columnNames = { "name", "tenant" }, name = "uk_rollout")) -public class Rollout extends NamedEntity { +// exception squid:S2160 - BaseEntity equals/hashcode is handling correctly for +// sub entities +@SuppressWarnings("squid:S2160") +public class JpaRollout extends AbstractJpaNamedEntity implements Rollout { private static final long serialVersionUID = 1L; - @OneToMany(targetEntity = RolloutGroup.class) + @OneToMany(targetEntity = JpaRolloutGroup.class) @JoinColumn(name = "rollout", insertable = false, updatable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_rollout_rolloutgroup")) private List rolloutGroups; @@ -50,13 +57,13 @@ public class Rollout extends NamedEntity { @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "distribution_set", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_rolltout_ds")) - private DistributionSet distributionSet; + private JpaDistributionSet distributionSet; @Column(name = "status") private RolloutStatus status = RolloutStatus.CREATING; @Column(name = "last_check") - private long lastCheck = 0L; + private long lastCheck; @Column(name = "action_type", nullable = false) @Enumerated(EnumType.STRING) @@ -70,23 +77,26 @@ public class Rollout extends NamedEntity { @Transient @CacheField(key = CacheKeys.ROLLOUT_GROUP_TOTAL) - private int rolloutGroupsTotal = 0; + private int rolloutGroupsTotal; @Transient @CacheField(key = CacheKeys.ROLLOUT_GROUP_CREATED) - private int rolloutGroupsCreated = 0; + private int rolloutGroupsCreated; @Transient private transient TotalTargetCountStatus totalTargetCountStatus; + @Override public DistributionSet getDistributionSet() { return distributionSet; } + @Override public void setDistributionSet(final DistributionSet distributionSet) { - this.distributionSet = distributionSet; + this.distributionSet = (JpaDistributionSet) distributionSet; } + @Override public List getRolloutGroups() { return rolloutGroups; } @@ -95,14 +105,17 @@ public class Rollout extends NamedEntity { this.rolloutGroups = rolloutGroups; } + @Override public String getTargetFilterQuery() { return targetFilterQuery; } + @Override public void setTargetFilterQuery(final String targetFilterQuery) { this.targetFilterQuery = targetFilterQuery; } + @Override public RolloutStatus getStatus() { return status; } @@ -119,22 +132,27 @@ public class Rollout extends NamedEntity { this.lastCheck = lastCheck; } + @Override public ActionType getActionType() { return actionType; } + @Override public void setActionType(final ActionType actionType) { this.actionType = actionType; } + @Override public long getForcedTime() { return forcedTime; } + @Override public void setForcedTime(final long forcedTime) { this.forcedTime = forcedTime; } + @Override public long getTotalTargets() { return totalTargets; } @@ -151,6 +169,7 @@ public class Rollout extends NamedEntity { this.rolloutGroupsTotal = rolloutGroupsTotal; } + @Override public int getRolloutGroupsCreated() { return rolloutGroupsCreated; } @@ -159,6 +178,7 @@ public class Rollout extends NamedEntity { this.rolloutGroupsCreated = rolloutGroupsCreated; } + @Override public TotalTargetCountStatus getTotalTargetCountStatus() { if (totalTargetCountStatus == null) { totalTargetCountStatus = new TotalTargetCountStatus(totalTargets); @@ -177,58 +197,4 @@ public class Rollout extends NamedEntity { + ", getName()=" + getName() + ", getId()=" + getId() + "]"; } - /** - * - * State machine for rollout. - * - */ - public enum RolloutStatus { - - /** - * Rollouts is beeing created. - */ - CREATING, - - /** - * Rollout is ready to start. - */ - READY, - - /** - * Rollout is paused. - */ - PAUSED, - - /** - * Rollout is starting. - */ - STARTING, - - /** - * Rollout is stopped. - */ - STOPPED, - - /** - * Rollout is running. - */ - RUNNING, - - /** - * Rollout is finished. - */ - FINISHED, - - /** - * Rollout could not created due errors, might be database problem due - * asynchronous creating. - */ - ERROR_CREATING, - - /** - * Rollout could not started due errors, might be database problem due - * asynchronous starting. - */ - ERROR_STARTING; - } } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaRolloutGroup.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaRolloutGroup.java new file mode 100644 index 000000000..79da6630a --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaRolloutGroup.java @@ -0,0 +1,239 @@ +/** + * 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.jpa.model; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.ConstraintMode; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.ForeignKey; +import javax.persistence.Index; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.Table; +import javax.persistence.Transient; +import javax.persistence.UniqueConstraint; + +import org.eclipse.hawkbit.repository.model.Rollout; +import org.eclipse.hawkbit.repository.model.RolloutGroup; +import org.eclipse.hawkbit.repository.model.TotalTargetCountStatus; + +/** + * JPA entity definition of persisting a group of an rollout. + * + */ +@Entity +@Table(name = "sp_rolloutgroup", indexes = { + @Index(name = "sp_idx_rolloutgroup_01", columnList = "tenant,name") }, uniqueConstraints = @UniqueConstraint(columnNames = { + "name", "rollout", "tenant" }, name = "uk_rolloutgroup")) +// exception squid:S2160 - BaseEntity equals/hashcode is handling correctly for +// sub entities +@SuppressWarnings("squid:S2160") +public class JpaRolloutGroup extends AbstractJpaNamedEntity implements RolloutGroup { + + private static final long serialVersionUID = 1L; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "rollout", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_rolloutgroup_rollout")) + private JpaRollout rollout; + + @Column(name = "status") + private RolloutGroupStatus status = RolloutGroupStatus.READY; + + @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST }, targetEntity = RolloutTargetGroup.class) + @JoinColumn(name = "rolloutGroup_Id", insertable = false, updatable = false) + private final List rolloutTargetGroup = new ArrayList<>(); + + @ManyToOne(fetch = FetchType.LAZY) + private JpaRolloutGroup parent; + + @Column(name = "success_condition", nullable = false) + private RolloutGroupSuccessCondition successCondition = RolloutGroupSuccessCondition.THRESHOLD; + + @Column(name = "success_condition_exp", length = 512, nullable = false) + private String successConditionExp; + + @Column(name = "success_action", nullable = false) + private RolloutGroupSuccessAction successAction = RolloutGroupSuccessAction.NEXTGROUP; + + @Column(name = "success_action_exp", length = 512, nullable = false) + private String successActionExp; + + @Column(name = "error_condition") + private RolloutGroupErrorCondition errorCondition; + + @Column(name = "error_condition_exp", length = 512) + private String errorConditionExp; + + @Column(name = "error_action") + private RolloutGroupErrorAction errorAction; + + @Column(name = "error_action_exp", length = 512) + private String errorActionExp; + + @Column(name = "total_targets") + private long totalTargets; + + @Transient + private transient TotalTargetCountStatus totalTargetCountStatus; + + @Override + public Rollout getRollout() { + return rollout; + } + + @Override + public void setRollout(final Rollout rollout) { + this.rollout = (JpaRollout) rollout; + } + + @Override + public RolloutGroupStatus getStatus() { + return status; + } + + @Override + public void setStatus(final RolloutGroupStatus status) { + this.status = status; + } + + public List getRolloutTargetGroup() { + return rolloutTargetGroup; + } + + @Override + public RolloutGroup getParent() { + return parent; + } + + public void setParent(final RolloutGroup parent) { + this.parent = (JpaRolloutGroup) parent; + } + + @Override + public RolloutGroupSuccessCondition getSuccessCondition() { + return successCondition; + } + + @Override + public void setSuccessCondition(final RolloutGroupSuccessCondition finishCondition) { + successCondition = finishCondition; + } + + @Override + public String getSuccessConditionExp() { + return successConditionExp; + } + + @Override + public void setSuccessConditionExp(final String finishExp) { + successConditionExp = finishExp; + } + + @Override + public RolloutGroupErrorCondition getErrorCondition() { + return errorCondition; + } + + @Override + public void setErrorCondition(final RolloutGroupErrorCondition errorCondition) { + this.errorCondition = errorCondition; + } + + @Override + public String getErrorConditionExp() { + return errorConditionExp; + } + + @Override + public void setErrorConditionExp(final String errorExp) { + errorConditionExp = errorExp; + } + + @Override + public RolloutGroupErrorAction getErrorAction() { + return errorAction; + } + + @Override + public void setErrorAction(final RolloutGroupErrorAction errorAction) { + this.errorAction = errorAction; + } + + @Override + public String getErrorActionExp() { + return errorActionExp; + } + + @Override + public void setErrorActionExp(final String errorActionExp) { + this.errorActionExp = errorActionExp; + } + + @Override + public RolloutGroupSuccessAction getSuccessAction() { + return successAction; + } + + @Override + public String getSuccessActionExp() { + return successActionExp; + } + + @Override + public long getTotalTargets() { + return totalTargets; + } + + public void setTotalTargets(final long totalTargets) { + this.totalTargets = totalTargets; + } + + public void setSuccessAction(final RolloutGroupSuccessAction successAction) { + this.successAction = successAction; + } + + public void setSuccessActionExp(final String successActionExp) { + this.successActionExp = successActionExp; + } + + /** + * @return the totalTargetCountStatus + */ + @Override + public TotalTargetCountStatus getTotalTargetCountStatus() { + if (totalTargetCountStatus == null) { + totalTargetCountStatus = new TotalTargetCountStatus(totalTargets); + } + return totalTargetCountStatus; + } + + /** + * @param totalTargetCountStatus + * the totalTargetCountStatus to set + */ + @Override + public void setTotalTargetCountStatus(final TotalTargetCountStatus totalTargetCountStatus) { + this.totalTargetCountStatus = totalTargetCountStatus; + } + + @Override + public String toString() { + return "RolloutGroup [rollout=" + rollout + ", status=" + status + ", rolloutTargetGroup=" + rolloutTargetGroup + + ", parent=" + parent + ", finishCondition=" + successCondition + ", finishExp=" + successConditionExp + + ", errorCondition=" + errorCondition + ", errorExp=" + errorConditionExp + ", getName()=" + getName() + + ", getId()=" + getId() + "]"; + } + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModule.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModule.java similarity index 82% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModule.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModule.java index 327bff3db..80156edb8 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModule.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModule.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import java.util.ArrayList; import java.util.Collections; @@ -29,6 +29,13 @@ import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.UniqueConstraint; +import org.eclipse.hawkbit.repository.model.Artifact; +import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.repository.model.ExternalArtifact; +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.SoftwareModuleType; import org.eclipse.persistence.annotations.CascadeOnDelete; /** @@ -43,37 +50,40 @@ import org.eclipse.persistence.annotations.CascadeOnDelete; @Index(name = "sp_idx_base_sw_module_02", columnList = "tenant,deleted,module_type"), @Index(name = "sp_idx_base_sw_module_prim", columnList = "tenant,id") }) @NamedEntityGraph(name = "SoftwareModule.artifacts", attributeNodes = { @NamedAttributeNode("artifacts") }) -public class SoftwareModule extends NamedVersionedEntity { +// exception squid:S2160 - BaseEntity equals/hashcode is handling correctly for +// sub entities +@SuppressWarnings("squid:S2160") +public class JpaSoftwareModule extends AbstractJpaNamedVersionedEntity implements SoftwareModule { private static final long serialVersionUID = 1L; @ManyToOne @JoinColumn(name = "module_type", nullable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_module_type")) - private SoftwareModuleType type; + private JpaSoftwareModuleType type; - @ManyToMany(mappedBy = "modules", targetEntity = DistributionSet.class, fetch = FetchType.LAZY) + @ManyToMany(mappedBy = "modules", targetEntity = JpaDistributionSet.class, fetch = FetchType.LAZY) private final List assignedTo = new ArrayList<>(); @Column(name = "deleted") - private boolean deleted = false; + private boolean deleted; @Column(name = "vendor", nullable = true, length = 256) private String vendor; - @OneToMany(mappedBy = "softwareModule", cascade = { CascadeType.ALL }, targetEntity = LocalArtifact.class) + @OneToMany(mappedBy = "softwareModule", cascade = { CascadeType.ALL }, targetEntity = JpaLocalArtifact.class) private List artifacts; - @OneToMany(mappedBy = "softwareModule", cascade = { CascadeType.ALL }, targetEntity = ExternalArtifact.class) + @OneToMany(mappedBy = "softwareModule", cascade = { CascadeType.ALL }, targetEntity = JpaExternalArtifact.class) private List externalArtifacts; @CascadeOnDelete - @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE }) + @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE }, targetEntity = JpaSoftwareModuleMetadata.class) @JoinColumn(name = "sw_id", insertable = false, updatable = false) private final List metadata = new ArrayList<>(); /** * Default constructor. */ - public SoftwareModule() { + public JpaSoftwareModule() { super(); } @@ -91,17 +101,18 @@ public class SoftwareModule extends NamedVersionedEntity { * @param vendor * of the {@link SoftwareModule} */ - public SoftwareModule(final SoftwareModuleType type, final String name, final String version, + public JpaSoftwareModule(final SoftwareModuleType type, final String name, final String version, final String description, final String vendor) { super(name, version, description); this.vendor = vendor; - this.type = type; + this.type = (JpaSoftwareModuleType) type; } /** * @param artifact * is added to the assigned {@link Artifact}s. */ + @Override public void addArtifact(final LocalArtifact artifact) { if (null == artifacts) { artifacts = new ArrayList<>(4); @@ -116,6 +127,7 @@ public class SoftwareModule extends NamedVersionedEntity { * @param artifact * is added to the assigned {@link Artifact}s. */ + @Override public void addArtifact(final ExternalArtifact artifact) { if (null == externalArtifacts) { externalArtifacts = new ArrayList<>(4); @@ -132,6 +144,7 @@ public class SoftwareModule extends NamedVersionedEntity { * to look for * @return found {@link Artifact} */ + @Override public Optional getLocalArtifact(final Long artifactId) { if (null == artifacts) { return Optional.empty(); @@ -145,6 +158,7 @@ public class SoftwareModule extends NamedVersionedEntity { * to look for * @return found {@link Artifact} */ + @Override public Optional getLocalArtifactByFilename(final String fileName) { if (null == artifacts) { return Optional.empty(); @@ -157,6 +171,7 @@ public class SoftwareModule extends NamedVersionedEntity { /** * @return the artifacts */ + @Override public List getArtifacts() { final List result = new ArrayList<>(); result.addAll(artifacts); @@ -168,6 +183,7 @@ public class SoftwareModule extends NamedVersionedEntity { /** * @return local artifacts only */ + @Override public List getLocalArtifacts() { if (artifacts == null) { return Collections.emptyList(); @@ -176,6 +192,7 @@ public class SoftwareModule extends NamedVersionedEntity { return artifacts; } + @Override public String getVendor() { return vendor; } @@ -184,6 +201,7 @@ public class SoftwareModule extends NamedVersionedEntity { * @param artifact * is removed from the assigned {@link LocalArtifact}s. */ + @Override public void removeArtifact(final LocalArtifact artifact) { if (null != artifacts) { artifacts.remove(artifact); @@ -194,35 +212,42 @@ public class SoftwareModule extends NamedVersionedEntity { * @param artifact * is removed from the assigned {@link ExternalArtifact}s. */ + @Override public void removeArtifact(final ExternalArtifact artifact) { if (null != externalArtifacts) { externalArtifacts.remove(artifact); } } + @Override public void setVendor(final String vendor) { this.vendor = vendor; } + @Override public SoftwareModuleType getType() { return type; } + @Override public boolean isDeleted() { return deleted; } + @Override public void setDeleted(final boolean deleted) { this.deleted = deleted; } + @Override public void setType(final SoftwareModuleType type) { - this.type = type; + this.type = (JpaSoftwareModuleType) type; } /** * @return immutable list of meta data elements. */ + @Override public List getMetadata() { return Collections.unmodifiableList(metadata); } @@ -236,6 +261,7 @@ public class SoftwareModule extends NamedVersionedEntity { /** * @return the assignedTo */ + @Override public List getAssignedTo() { return assignedTo; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleMetadata.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModuleMetadata.java similarity index 74% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleMetadata.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModuleMetadata.java index 5ddd273d3..e8972eb97 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleMetadata.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModuleMetadata.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import javax.persistence.ConstraintMode; import javax.persistence.Entity; @@ -18,6 +18,9 @@ import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; +import org.eclipse.hawkbit.repository.model.SoftwareModule; +import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; + /** * Metadata for {@link SoftwareModule}. * @@ -25,19 +28,19 @@ import javax.persistence.Table; @IdClass(SwMetadataCompositeKey.class) @Entity @Table(name = "sp_sw_metadata") -public class SoftwareModuleMetadata extends MetaData { +public class JpaSoftwareModuleMetadata extends AbstractJpaMetaData implements SoftwareModuleMetadata { private static final long serialVersionUID = 1L; @Id - @ManyToOne(targetEntity = SoftwareModule.class, fetch = FetchType.LAZY) + @ManyToOne(targetEntity = JpaSoftwareModule.class, fetch = FetchType.LAZY) @JoinColumn(name = "sw_id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_metadata_sw")) private SoftwareModule softwareModule; - public SoftwareModuleMetadata() { + public JpaSoftwareModuleMetadata() { // default public constructor for JPA } - public SoftwareModuleMetadata(final String key, final SoftwareModule softwareModule, final String value) { + public JpaSoftwareModuleMetadata(final String key, final SoftwareModule softwareModule, final String value) { super(key, value); this.softwareModule = softwareModule; } @@ -46,10 +49,12 @@ public class SoftwareModuleMetadata extends MetaData { return new SwMetadataCompositeKey(softwareModule, getKey()); } + @Override public SoftwareModule getSoftwareModule() { return softwareModule; } + @Override public void setSoftwareModule(final SoftwareModule softwareModule) { this.softwareModule = softwareModule; } @@ -63,11 +68,13 @@ public class SoftwareModuleMetadata extends MetaData { } @Override + // exception squid:S2259 - obj is checked for null in super + @SuppressWarnings("squid:S2259") public boolean equals(final Object obj) { if (!super.equals(obj)) { return false; } - final SoftwareModuleMetadata other = (SoftwareModuleMetadata) obj; + final JpaSoftwareModuleMetadata other = (JpaSoftwareModuleMetadata) obj; if (softwareModule == null) { if (other.softwareModule != null) { return false; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleType.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModuleType.java similarity index 72% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleType.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModuleType.java index f31b74ff6..f2a716c40 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleType.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModuleType.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import javax.persistence.Column; import javax.persistence.Entity; @@ -14,6 +14,8 @@ import javax.persistence.Index; import javax.persistence.Table; import javax.persistence.UniqueConstraint; +import org.eclipse.hawkbit.repository.model.SoftwareModuleType; + /** * Type of a software modules. * @@ -24,7 +26,10 @@ import javax.persistence.UniqueConstraint; @Index(name = "sp_idx_software_module_type_prim", columnList = "tenant,id") }, uniqueConstraints = { @UniqueConstraint(columnNames = { "type_key", "tenant" }, name = "uk_smt_type_key"), @UniqueConstraint(columnNames = { "name", "tenant" }, name = "uk_smt_name") }) -public class SoftwareModuleType extends NamedEntity { +// exception squid:S2160 - BaseEntity equals/hashcode is handling correctly for +// sub entities +@SuppressWarnings("squid:S2160") +public class JpaSoftwareModuleType extends AbstractJpaNamedEntity implements SoftwareModuleType { private static final long serialVersionUID = 1L; @Column(name = "type_key", nullable = false, length = 64) @@ -37,7 +42,7 @@ public class SoftwareModuleType extends NamedEntity { private String colour; @Column(name = "deleted") - private boolean deleted = false; + private boolean deleted; /** * Constructor. @@ -51,7 +56,8 @@ public class SoftwareModuleType extends NamedEntity { * @param maxAssignments * assignments to a DS */ - public SoftwareModuleType(final String key, final String name, final String description, final int maxAssignments) { + public JpaSoftwareModuleType(final String key, final String name, final String description, + final int maxAssignments) { this(key, name, description, maxAssignments, null); } @@ -69,8 +75,8 @@ public class SoftwareModuleType extends NamedEntity { * @param colour * of the type. It will be null by default */ - public SoftwareModuleType(final String key, final String name, final String description, final int maxAssignments, - final String colour) { + public JpaSoftwareModuleType(final String key, final String name, final String description, + final int maxAssignments, final String colour) { super(); this.key = key; this.maxAssignments = maxAssignments; @@ -80,20 +86,28 @@ public class SoftwareModuleType extends NamedEntity { } /** - * Default Constructor. + * Default Constructor for JPA. */ - public SoftwareModuleType() { - super(); + public JpaSoftwareModuleType() { + // Default Constructor for JPA. } + @Override + public void setMaxAssignments(final int maxAssignments) { + this.maxAssignments = maxAssignments; + } + + @Override public String getKey() { return key; } + @Override public int getMaxAssignments() { return maxAssignments; } + @Override public boolean isDeleted() { return deleted; } @@ -102,10 +116,12 @@ public class SoftwareModuleType extends NamedEntity { this.deleted = deleted; } + @Override public String getColour() { return colour; } + @Override public void setColour(final String colour) { this.colour = colour; } @@ -114,4 +130,9 @@ public class SoftwareModuleType extends NamedEntity { public String toString() { return "SoftwareModuleType [key=" + key + ", getName()=" + getName() + ", getId()=" + getId() + "]"; } + + @Override + public void setKey(final String key) { + this.key = key; + } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Target.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTarget.java similarity index 80% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Target.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTarget.java index 8947ea6c3..94f50ff0d 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Target.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTarget.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import java.util.ArrayList; import java.util.HashSet; @@ -36,26 +36,19 @@ import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.eclipse.hawkbit.im.authentication.SpPermission; -import org.eclipse.hawkbit.repository.model.helper.SecurityChecker; -import org.eclipse.hawkbit.repository.model.helper.SecurityTokenGeneratorHolder; -import org.eclipse.hawkbit.repository.model.helper.SystemSecurityContextHolder; +import org.eclipse.hawkbit.repository.jpa.model.helper.SecurityChecker; +import org.eclipse.hawkbit.repository.jpa.model.helper.SecurityTokenGeneratorHolder; +import org.eclipse.hawkbit.repository.jpa.model.helper.SystemSecurityContextHolder; +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.TargetInfo; +import org.eclipse.hawkbit.repository.model.TargetTag; import org.eclipse.persistence.annotations.CascadeOnDelete; import org.springframework.data.domain.Persistable; /** - *

- * The {@link Target} is the target of all provisioning operations. It contains - * the currently installed {@link DistributionSet} (i.e. current state). In - * addition it holds the target {@link DistributionSet} that has to be - * provisioned next (i.e. target state). - *

- * - *

- * {@link #getStatus()}s() shows if the {@link Target} is - * {@link TargetStatus#IN_SYNC} or a provisioning is - * {@link TargetStatus#PENDING} or the target is only - * {@link TargetStatus#REGISTERED}, i.e. a target {@link DistributionSet} . - *

+ * JPA implementation of {@link Target}. * */ @Entity @@ -68,7 +61,10 @@ import org.springframework.data.domain.Persistable; "controller_id", "tenant" }, name = "uk_tenant_controller_id")) @NamedEntityGraph(name = "Target.detail", attributeNodes = { @NamedAttributeNode("tags"), @NamedAttributeNode(value = "assignedDistributionSet"), @NamedAttributeNode(value = "targetInfo") }) -public class Target extends NamedEntity implements Persistable { +// exception squid:S2160 - BaseEntity equals/hashcode is handling correctly for +// sub entities +@SuppressWarnings("squid:S2160") +public class JpaTarget extends AbstractJpaNamedEntity implements Persistable, Target { private static final long serialVersionUID = 1L; @Column(name = "controller_id", length = 64) @@ -77,34 +73,35 @@ public class Target extends NamedEntity implements Persistable { private String controllerId; @Transient - private boolean entityNew = false; + private boolean entityNew; - @ManyToMany(targetEntity = TargetTag.class) + @ManyToMany(targetEntity = JpaTargetTag.class) @JoinTable(name = "sp_target_target_tag", joinColumns = { @JoinColumn(name = "target", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_targ_targtag_target")) }, inverseJoinColumns = { @JoinColumn(name = "tag", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_targ_targtag_tag")) }) private Set tags = new HashSet<>(); @CascadeOnDelete - @OneToMany(fetch = FetchType.LAZY, orphanRemoval = true, cascade = { CascadeType.REMOVE }) + @OneToMany(fetch = FetchType.LAZY, orphanRemoval = true, cascade = { + CascadeType.REMOVE }, targetEntity = JpaAction.class) @JoinColumn(name = "target", insertable = false, updatable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_targ_act_hist_targ")) private final List actions = new ArrayList<>(); - @ManyToOne(optional = true, fetch = FetchType.LAZY, targetEntity = DistributionSet.class) + @ManyToOne(optional = true, fetch = FetchType.LAZY, targetEntity = JpaDistributionSet.class) @JoinColumn(name = "assigned_distribution_set", nullable = true, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_target_assign_ds")) - private DistributionSet assignedDistributionSet; + private JpaDistributionSet assignedDistributionSet; @CascadeOnDelete - @OneToOne(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY, targetEntity = TargetInfo.class) + @OneToOne(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY, targetEntity = JpaTargetInfo.class) @PrimaryKeyJoinColumn - private TargetInfo targetInfo = null; + private JpaTargetInfo targetInfo; /** * the security token of the target which allows if enabled to authenticate * with this security token. */ @Column(name = "sec_token", insertable = true, updatable = true, nullable = false, length = 128) - private String securityToken = null; + private String securityToken; @CascadeOnDelete @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE, CascadeType.PERSIST }) @@ -117,35 +114,38 @@ public class Target extends NamedEntity implements Persistable { * @param controllerId * controller ID of the {@link Target} */ - public Target(final String controllerId) { + public JpaTarget(final String controllerId) { this.controllerId = controllerId; setName(controllerId); securityToken = SecurityTokenGeneratorHolder.getInstance().generateToken(); - targetInfo = new TargetInfo(this); + targetInfo = new JpaTargetInfo(this); } /** * empty constructor for JPA. */ - Target() { + JpaTarget() { controllerId = null; securityToken = null; } + @Override public DistributionSet getAssignedDistributionSet() { return assignedDistributionSet; } + @Override public String getControllerId() { return controllerId; } + @Override public Set getTags() { return tags; } public void setAssignedDistributionSet(final DistributionSet assignedDistributionSet) { - this.assignedDistributionSet = assignedDistributionSet; + this.assignedDistributionSet = (JpaDistributionSet) assignedDistributionSet; } public void setControllerId(final String controllerId) { @@ -156,14 +156,11 @@ public class Target extends NamedEntity implements Persistable { this.tags = tags; } + @Override public List getActions() { return actions; } - public TargetIdName getTargetIdName() { - return new TargetIdName(getId(), getControllerId(), getName()); - } - @Override @Transient public boolean isNew() { @@ -181,6 +178,7 @@ public class Target extends NamedEntity implements Persistable { /** * @return the targetInfo */ + @Override public TargetInfo getTargetInfo() { return targetInfo; } @@ -190,7 +188,7 @@ public class Target extends NamedEntity implements Persistable { * the targetInfo to set */ public void setTargetInfo(final TargetInfo targetInfo) { - this.targetInfo = targetInfo; + this.targetInfo = (JpaTargetInfo) targetInfo; } /** @@ -199,6 +197,7 @@ public class Target extends NamedEntity implements Persistable { * or the current context is executed as system code, otherwise * {@code null}. */ + @Override public String getSecurityToken() { if (SystemSecurityContextHolder.getInstance().getSystemSecurityContext().isCurrentThreadSystemCode() || SecurityChecker.hasPermission(SpPermission.READ_TARGET_SEC_TOKEN)) { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetFilterQuery.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetFilterQuery.java similarity index 66% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetFilterQuery.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetFilterQuery.java index 021b9ca7f..38275c71a 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetFilterQuery.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetFilterQuery.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import javax.persistence.Column; import javax.persistence.Entity; @@ -14,6 +14,8 @@ import javax.persistence.Index; import javax.persistence.Table; import javax.persistence.UniqueConstraint; +import org.eclipse.hawkbit.repository.model.TargetFilterQuery; + /** * Stored target filter. * @@ -22,7 +24,10 @@ import javax.persistence.UniqueConstraint; @Table(name = "sp_target_filter_query", indexes = { @Index(name = "sp_idx_target_filter_query_01", columnList = "tenant,name") }, uniqueConstraints = @UniqueConstraint(columnNames = { "name", "tenant" }, name = "uk_tenant_custom_filter_name")) -public class TargetFilterQuery extends TenantAwareBaseEntity { +// exception squid:S2160 - BaseEntity equals/hashcode is handling correctly for +// sub entities +@SuppressWarnings("squid:S2160") +public class JpaTargetFilterQuery extends AbstractJpaTenantAwareBaseEntity implements TargetFilterQuery { private static final long serialVersionUID = 7493966984413479089L; @Column(name = "name", length = 64) @@ -31,27 +36,39 @@ public class TargetFilterQuery extends TenantAwareBaseEntity { @Column(name = "query", length = 1024) private String query; - public TargetFilterQuery() { + public JpaTargetFilterQuery() { // Default constructor for JPA. } - public TargetFilterQuery(final String name, final String query) { + /** + * Public constructor. + * + * @param name + * of the {@link TargetFilterQuery}. + * @param query + * of the {@link TargetFilterQuery}. + */ + public JpaTargetFilterQuery(final String name, final String query) { this.name = name; this.query = query; } + @Override public String getName() { return name; } + @Override public void setName(final String name) { this.name = name; } + @Override public String getQuery() { return query; } + @Override public void setQuery(final String query) { this.query = query; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetInfo.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetInfo.java similarity index 76% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetInfo.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetInfo.java index 00a501540..6b5a3d1af 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetInfo.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetInfo.java @@ -6,9 +6,8 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; -import java.io.Serializable; import java.net.URI; import java.time.Duration; import java.time.Instant; @@ -38,8 +37,13 @@ import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Transient; -import org.eclipse.hawkbit.repository.model.helper.SystemSecurityContextHolder; -import org.eclipse.hawkbit.repository.model.helper.TenantConfigurationManagementHolder; +import org.eclipse.hawkbit.repository.jpa.model.helper.SystemSecurityContextHolder; +import org.eclipse.hawkbit.repository.jpa.model.helper.TenantConfigurationManagementHolder; +import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.repository.model.PollStatus; +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.DurationHelper; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; import org.eclipse.persistence.annotations.CascadeOnDelete; @@ -59,7 +63,7 @@ import org.springframework.data.domain.Persistable; @Table(name = "sp_target_info", indexes = { @Index(name = "sp_idx_target_info_02", columnList = "target_id,update_status") }) @Entity -public class TargetInfo implements Persistable, Serializable { +public class JpaTargetInfo implements Persistable, TargetInfo { private static final long serialVersionUID = 1L; private static final Logger LOG = LoggerFactory.getLogger(TargetInfo.class); @@ -68,19 +72,20 @@ public class TargetInfo implements Persistable, Serializable { private Long targetId; @Transient - private boolean entityNew = false; + private boolean entityNew; @CascadeOnDelete - @OneToOne(cascade = { CascadeType.MERGE, CascadeType.REMOVE }, fetch = FetchType.LAZY, targetEntity = Target.class) + @OneToOne(cascade = { CascadeType.MERGE, + CascadeType.REMOVE }, fetch = FetchType.LAZY, targetEntity = JpaTarget.class) @JoinColumn(name = "target_id", nullable = false, updatable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_targ_stat_targ")) @MapsId - private Target target; + private JpaTarget target; @Column(name = "address", length = 512) - private String address = null; + private String address; @Column(name = "last_target_query") - private Long lastTargetQuery = null; + private Long lastTargetQuery; @Column(name = "install_date") private Long installationDate; @@ -91,7 +96,7 @@ public class TargetInfo implements Persistable, Serializable { @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "installed_distribution_set", nullable = true, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_target_inst_ds")) - private DistributionSet installedDistributionSet; + private JpaDistributionSet installedDistributionSet; /** * Read only on management API. Are commited by controller. @@ -116,12 +121,12 @@ public class TargetInfo implements Persistable, Serializable { * @param target * related to this status. */ - public TargetInfo(final Target target) { + public JpaTargetInfo(final JpaTarget target) { this.target = target; targetId = target.getId(); } - TargetInfo() { + JpaTargetInfo() { target = null; targetId = null; } @@ -148,6 +153,7 @@ public class TargetInfo implements Persistable, Serializable { /** * @return the ipAddress */ + @Override public URI getAddress() { if (address == null) { return null; @@ -184,14 +190,16 @@ public class TargetInfo implements Persistable, Serializable { this.targetId = targetId; } + @Override public Target getTarget() { return target; } - public void setTarget(final Target target) { + public void setTarget(final JpaTarget target) { this.target = target; } + @Override public Long getLastTargetQuery() { return lastTargetQuery; } @@ -204,14 +212,17 @@ public class TargetInfo implements Persistable, Serializable { this.requestControllerAttributes = requestControllerAttributes; } + @Override public Map getControllerAttributes() { return controllerAttributes; } + @Override public boolean isRequestControllerAttributes() { return requestControllerAttributes; } + @Override public Long getInstallationDate() { return installationDate; } @@ -220,6 +231,7 @@ public class TargetInfo implements Persistable, Serializable { this.installationDate = installationDate; } + @Override public TargetUpdateStatus getUpdateStatus() { return updateStatus; } @@ -228,11 +240,12 @@ public class TargetInfo implements Persistable, Serializable { this.updateStatus = updateStatus; } + @Override public DistributionSet getInstalledDistributionSet() { return installedDistributionSet; } - public void setInstalledDistributionSet(final DistributionSet installedDistributionSet) { + public void setInstalledDistributionSet(final JpaDistributionSet installedDistributionSet) { this.installedDistributionSet = installedDistributionSet; } @@ -242,6 +255,7 @@ public class TargetInfo implements Persistable, Serializable { * {@link #lastTargetQuery} is not set e.g. the target never polled * before this method returns {@code null} */ + @Override public PollStatus getPollStatus() { if (lastTargetQuery == null) { return null; @@ -263,63 +277,6 @@ public class TargetInfo implements Persistable, Serializable { }); } - /** - * The poll time object which holds all the necessary information around the - * target poll time, e.g. the last poll time, the next poll time and the - * overdue poll time. - * - */ - public static final class PollStatus { - private final LocalDateTime lastPollDate; - private final LocalDateTime nextPollDate; - private final LocalDateTime overdueDate; - private final LocalDateTime currentDate; - - private PollStatus(final LocalDateTime lastPollDate, final LocalDateTime nextPollDate, - final LocalDateTime overdueDate, final LocalDateTime currentDate) { - this.lastPollDate = lastPollDate; - this.nextPollDate = nextPollDate; - this.overdueDate = overdueDate; - this.currentDate = currentDate; - } - - /** - * calculates if the target poll time is overdue and the target has not - * been polled in the configured poll time interval. - * - * @return {@code true} if the current time is after the poll time - * overdue date otherwise {@code false}. - */ - public boolean isOverdue() { - return currentDate.isAfter(overdueDate); - } - - /** - * @return the lastPollDate - */ - public LocalDateTime getLastPollDate() { - return lastPollDate; - } - - public LocalDateTime getNextPollDate() { - return nextPollDate; - } - - public LocalDateTime getOverdueDate() { - return overdueDate; - } - - public LocalDateTime getCurrentDate() { - return currentDate; - } - - @Override - public String toString() { - return "PollTime [lastPollDate=" + lastPollDate + ", nextPollDate=" + nextPollDate + ", overdueDate=" - + overdueDate + ", currentDate=" + currentDate + "]"; - } - } - @Override public int hashCode() { final int prime = 31; @@ -340,7 +297,7 @@ public class TargetInfo implements Persistable, Serializable { if (!(obj instanceof TargetInfo)) { return false; } - final TargetInfo other = (TargetInfo) obj; + final JpaTargetInfo other = (JpaTargetInfo) obj; if (target == null) { if (other.target != null) { return false; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetTag.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetTag.java similarity index 78% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetTag.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetTag.java index 5a5a310d0..96989f14a 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetTag.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetTag.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import java.util.List; @@ -17,6 +17,9 @@ import javax.persistence.ManyToMany; import javax.persistence.Table; import javax.persistence.UniqueConstraint; +import org.eclipse.hawkbit.repository.model.Target; +import org.eclipse.hawkbit.repository.model.TargetTag; + /** * A {@link TargetTag} is used to describe Target attributes and use them also * for filtering the target list. @@ -26,10 +29,10 @@ import javax.persistence.UniqueConstraint; @Table(name = "sp_target_tag", indexes = { @Index(name = "sp_idx_target_tag_prim", columnList = "tenant,id") }, uniqueConstraints = @UniqueConstraint(columnNames = { "name", "tenant" }, name = "uk_targ_tag")) -public class TargetTag extends Tag { +public class JpaTargetTag extends AbstractJpaTag implements TargetTag { private static final long serialVersionUID = 1L; - @ManyToMany(mappedBy = "tags", targetEntity = Target.class, fetch = FetchType.LAZY) + @ManyToMany(mappedBy = "tags", targetEntity = JpaTarget.class, fetch = FetchType.LAZY) private List assignedToTargets; /** @@ -42,7 +45,7 @@ public class TargetTag extends Tag { * @param colour * of {@link TargetTag} */ - public TargetTag(final String name, final String description, final String colour) { + public JpaTargetTag(final String name, final String description, final String colour) { super(name, description, colour); } @@ -52,14 +55,15 @@ public class TargetTag extends Tag { * @param name * of the {@link TargetTag} **/ - public TargetTag(final String name) { + public JpaTargetTag(final String name) { super(name, null, null); } - TargetTag() { - super(); + public JpaTargetTag() { + // Default constructor for JPA. } + @Override public List getAssignedToTargets() { return assignedToTargets; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantConfiguration.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTenantConfiguration.java similarity index 74% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantConfiguration.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTenantConfiguration.java index 5a938563b..d6f9a7a97 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantConfiguration.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTenantConfiguration.java @@ -6,9 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; - -import java.io.Serializable; +package org.eclipse.hawkbit.repository.jpa.model; import javax.persistence.Basic; import javax.persistence.Column; @@ -16,6 +14,8 @@ import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.UniqueConstraint; +import org.eclipse.hawkbit.repository.model.TenantConfiguration; + /** * A JPA entity which stores the tenant specific configuration. * @@ -23,7 +23,10 @@ import javax.persistence.UniqueConstraint; @Entity @Table(name = "sp_tenant_configuration", uniqueConstraints = @UniqueConstraint(columnNames = { "conf_key", "tenant" }, name = "uk_tenant_key")) -public class TenantConfiguration extends TenantAwareBaseEntity implements Serializable { +// exception squid:S2160 - BaseEntity equals/hashcode is handling correctly for +// sub entities +@SuppressWarnings("squid:S2160") +public class JpaTenantConfiguration extends AbstractJpaTenantAwareBaseEntity implements TenantConfiguration { private static final long serialVersionUID = 1L; @Column(name = "conf_key", length = 128) @@ -36,7 +39,7 @@ public class TenantConfiguration extends TenantAwareBaseEntity implements Serial /** * JPA default constructor. */ - public TenantConfiguration() { + public JpaTenantConfiguration() { // JPA default constructor. } @@ -46,24 +49,28 @@ public class TenantConfiguration extends TenantAwareBaseEntity implements Serial * @param value * the value of this configuration */ - public TenantConfiguration(final String key, final String value) { + public JpaTenantConfiguration(final String key, final String value) { this.key = key; this.value = value; } + @Override public String getKey() { return key; } + @Override public void setKey(final String key) { this.key = key; } + @Override public String getValue() { return value; } + @Override public void setValue(final String value) { this.value = value; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantMetaData.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTenantMetaData.java similarity index 74% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantMetaData.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTenantMetaData.java index a9572c21c..9363a4db8 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantMetaData.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTenantMetaData.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import javax.persistence.Column; import javax.persistence.ConstraintMode; @@ -20,6 +20,10 @@ import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; +import org.eclipse.hawkbit.repository.model.DistributionSetType; +import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity; +import org.eclipse.hawkbit.repository.model.TenantMetaData; + /** * Tenant entity with meta data that is configured globally for the entire * tenant. This entity is not tenant aware to allow the system to access it @@ -32,7 +36,10 @@ import javax.persistence.UniqueConstraint; @Index(name = "sp_idx_tenant_prim", columnList = "tenant,id") }, uniqueConstraints = { @UniqueConstraint(columnNames = { "tenant" }, name = "uk_tenantmd_tenant") }) @Entity -public class TenantMetaData extends BaseEntity { +// exception squid:S2160 - BaseEntity equals/hashcode is handling correctly for +// sub entities +@SuppressWarnings("squid:S2160") +public class JpaTenantMetaData extends AbstractJpaBaseEntity implements TenantMetaData { private static final long serialVersionUID = 1L; @Column(name = "tenant", nullable = false, length = 40) @@ -40,12 +47,12 @@ public class TenantMetaData extends BaseEntity { @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "default_ds_type", nullable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_tenant_md_default_ds_type")) - private DistributionSetType defaultDsType; + private JpaDistributionSetType defaultDsType; /** * Default constructor needed for JPA entities. */ - public TenantMetaData() { + public JpaTenantMetaData() { // Default constructor needed for JPA entities. } @@ -56,20 +63,23 @@ public class TenantMetaData extends BaseEntity { * of this tenant * @param tenant */ - public TenantMetaData(final DistributionSetType defaultDsType, final String tenant) { + public JpaTenantMetaData(final DistributionSetType defaultDsType, final String tenant) { super(); - this.defaultDsType = defaultDsType; + this.defaultDsType = (JpaDistributionSetType) defaultDsType; this.tenant = tenant; } + @Override public DistributionSetType getDefaultDsType() { return defaultDsType; } + @Override public void setDefaultDsType(final DistributionSetType defaultDsType) { - this.defaultDsType = defaultDsType; + this.defaultDsType = (JpaDistributionSetType) defaultDsType; } + @Override public String getTenant() { return tenant; } @@ -77,24 +87,4 @@ public class TenantMetaData extends BaseEntity { public void setTenant(final String tenant) { this.tenant = tenant; } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + this.getClass().getName().hashCode(); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof TenantMetaData)) { - return false; - } - - return true; - } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutTargetGroup.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/RolloutTargetGroup.java similarity index 77% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutTargetGroup.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/RolloutTargetGroup.java index 7a46b15b1..0bb969c7f 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutTargetGroup.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/RolloutTargetGroup.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import java.io.Serializable; import java.util.List; @@ -24,6 +24,9 @@ import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; +import org.eclipse.hawkbit.repository.model.Action; +import org.eclipse.hawkbit.repository.model.RolloutGroup; +import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.persistence.annotations.ExistenceChecking; import org.eclipse.persistence.annotations.ExistenceType; @@ -41,16 +44,16 @@ public class RolloutTargetGroup implements Serializable { private static final long serialVersionUID = 1L; @Id - @ManyToOne(targetEntity = RolloutGroup.class, fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST }) - @JoinColumn(name = "rolloutGroup_Id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_rollouttargetgroup_group") ) + @ManyToOne(targetEntity = JpaRolloutGroup.class, fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST }) + @JoinColumn(name = "rolloutGroup_Id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_rollouttargetgroup_group")) private RolloutGroup rolloutGroup; @Id - @ManyToOne(targetEntity = Target.class, fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST }) - @JoinColumn(name = "target_id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_rollouttargetgroup_target") ) - private Target target; + @ManyToOne(targetEntity = JpaTarget.class, fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST }) + @JoinColumn(name = "target_id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_rollouttargetgroup_target")) + private JpaTarget target; - @OneToMany(targetEntity = Action.class, fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST }) + @OneToMany(targetEntity = JpaAction.class, fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST }) @JoinColumns(value = { @JoinColumn(name = "rolloutgroup", referencedColumnName = "rolloutGroup_Id"), @JoinColumn(name = "target", referencedColumnName = "target_id") }) private List actions; @@ -64,7 +67,7 @@ public class RolloutTargetGroup implements Serializable { public RolloutTargetGroup(final RolloutGroup rolloutGroup, final Target target) { this.rolloutGroup = rolloutGroup; - this.target = target; + this.target = (JpaTarget) target; } public RolloutTargetGroupId getId() { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutTargetGroupId.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/RolloutTargetGroupId.java similarity index 88% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutTargetGroupId.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/RolloutTargetGroupId.java index 88226142a..b4001d9dc 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutTargetGroupId.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/RolloutTargetGroupId.java @@ -6,10 +6,13 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import java.io.Serializable; +import org.eclipse.hawkbit.repository.model.RolloutGroup; +import org.eclipse.hawkbit.repository.model.Target; + /** * Combined unique key of the table {@link RolloutTargetGroup}. * @@ -47,4 +50,4 @@ public class RolloutTargetGroupId implements Serializable { public Long getTarget() { return target; } -} \ No newline at end of file +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SwMetadataCompositeKey.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/SwMetadataCompositeKey.java similarity index 96% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SwMetadataCompositeKey.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/SwMetadataCompositeKey.java index 90b3779a1..e9c63b511 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SwMetadataCompositeKey.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/SwMetadataCompositeKey.java @@ -6,10 +6,12 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import java.io.Serializable; +import org.eclipse.hawkbit.repository.model.SoftwareModule; + /** * The Software Module meta data composite key which contains the meta data key * and the ID of the software module itself. diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/AfterTransactionCommitExecutorHolder.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/AfterTransactionCommitExecutorHolder.java similarity index 87% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/AfterTransactionCommitExecutorHolder.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/AfterTransactionCommitExecutorHolder.java index 1282bc99d..a0e918585 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/AfterTransactionCommitExecutorHolder.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/AfterTransactionCommitExecutorHolder.java @@ -6,10 +6,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model.helper; +package org.eclipse.hawkbit.repository.jpa.model.helper; -import org.eclipse.hawkbit.eventbus.EntityPropertyChangeListener; -import org.eclipse.hawkbit.executor.AfterTransactionCommitExecutor; +import org.eclipse.hawkbit.repository.jpa.executor.AfterTransactionCommitExecutor; +import org.eclipse.hawkbit.repository.jpa.model.EntityPropertyChangeListener; import org.springframework.beans.factory.annotation.Autowired; /** diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/CacheManagerHolder.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/CacheManagerHolder.java similarity index 92% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/CacheManagerHolder.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/CacheManagerHolder.java index c8c081d95..64417c7d6 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/CacheManagerHolder.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/CacheManagerHolder.java @@ -6,9 +6,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model.helper; +package org.eclipse.hawkbit.repository.jpa.model.helper; -import org.eclipse.hawkbit.eventbus.CacheFieldEntityListener; +import org.eclipse.hawkbit.repository.jpa.model.CacheFieldEntityListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.CacheManager; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/SecurityChecker.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/SecurityChecker.java similarity index 96% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/SecurityChecker.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/SecurityChecker.java index 7c9763e6d..da4f223e6 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/SecurityChecker.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/SecurityChecker.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model.helper; +package org.eclipse.hawkbit.repository.jpa.model.helper; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/SecurityTokenGeneratorHolder.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/SecurityTokenGeneratorHolder.java similarity index 96% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/SecurityTokenGeneratorHolder.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/SecurityTokenGeneratorHolder.java index ffc1e308f..64c158c87 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/SecurityTokenGeneratorHolder.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/SecurityTokenGeneratorHolder.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model.helper; +package org.eclipse.hawkbit.repository.jpa.model.helper; import org.eclipse.hawkbit.security.SecurityTokenGenerator; import org.springframework.beans.factory.annotation.Autowired; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/SystemSecurityContextHolder.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/SystemSecurityContextHolder.java similarity index 95% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/SystemSecurityContextHolder.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/SystemSecurityContextHolder.java index 7d005e9bc..109c11280 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/SystemSecurityContextHolder.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/SystemSecurityContextHolder.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model.helper; +package org.eclipse.hawkbit.repository.jpa.model.helper; import org.eclipse.hawkbit.security.SystemSecurityContext; import org.springframework.beans.factory.annotation.Autowired; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/TenantAwareHolder.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/TenantAwareHolder.java similarity index 95% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/TenantAwareHolder.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/TenantAwareHolder.java index 5b85745d7..a034cd605 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/TenantAwareHolder.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/TenantAwareHolder.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model.helper; +package org.eclipse.hawkbit.repository.jpa.model.helper; import org.eclipse.hawkbit.tenancy.TenantAware; import org.springframework.beans.factory.annotation.Autowired; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/TenantConfigurationManagementHolder.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/TenantConfigurationManagementHolder.java similarity index 95% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/TenantConfigurationManagementHolder.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/TenantConfigurationManagementHolder.java index 700511db6..239274c45 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/TenantConfigurationManagementHolder.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/helper/TenantConfigurationManagementHolder.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model.helper; +package org.eclipse.hawkbit.repository.jpa.model.helper; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; import org.springframework.beans.factory.annotation.Autowired; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutScheduler.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/RolloutScheduler.java similarity index 87% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutScheduler.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/RolloutScheduler.java index 6671ad896..7335c1cb6 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutScheduler.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/RolloutScheduler.java @@ -6,10 +6,13 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa.rollout; import java.util.List; +import org.eclipse.hawkbit.repository.RolloutManagement; +import org.eclipse.hawkbit.repository.RolloutProperties; +import org.eclipse.hawkbit.repository.SystemManagement; import org.eclipse.hawkbit.security.SystemSecurityContext; import org.eclipse.hawkbit.tenancy.TenantAware; import org.slf4j.Logger; @@ -31,7 +34,7 @@ import org.springframework.stereotype.Component; @Profile("!test") public class RolloutScheduler { - private static final Logger logger = LoggerFactory.getLogger(RolloutScheduler.class); + private static final Logger LOGGER = LoggerFactory.getLogger(RolloutScheduler.class); @Autowired private TenantAware tenantAware; @@ -56,7 +59,7 @@ public class RolloutScheduler { */ @Scheduled(initialDelayString = RolloutProperties.Scheduler.PROP_SCHEDULER_DELAY_PLACEHOLDER, fixedDelayString = RolloutProperties.Scheduler.PROP_SCHEDULER_DELAY_PLACEHOLDER) public void rolloutScheduler() { - logger.debug("rollout schedule checker has been triggered."); + LOGGER.debug("rollout schedule checker has been triggered."); // run this code in system code privileged to have the necessary // permission to query and create entities. systemSecurityContext.runAsSystem(() -> { @@ -67,7 +70,7 @@ public class RolloutScheduler { // iterate through all tenants and execute the rollout check for // each tenant seperately. final List tenants = systemManagement.findTenants(); - logger.info("Checking rollouts for {} tenants", tenants.size()); + LOGGER.info("Checking rollouts for {} tenants", tenants.size()); for (final String tenant : tenants) { tenantAware.runAsTenant(tenant, () -> { rolloutManagement.checkRunningRollouts(rolloutProperties.getScheduler().getFixedDelay()); diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/PauseRolloutGroupAction.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/PauseRolloutGroupAction.java similarity index 74% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/PauseRolloutGroupAction.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/PauseRolloutGroupAction.java index af335cd0d..e20f632f8 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/PauseRolloutGroupAction.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/PauseRolloutGroupAction.java @@ -6,12 +6,11 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rollout.condition; +package org.eclipse.hawkbit.repository.jpa.rollout.condition; -import java.util.concurrent.Callable; - -import org.eclipse.hawkbit.repository.RolloutGroupRepository; import org.eclipse.hawkbit.repository.RolloutManagement; +import org.eclipse.hawkbit.repository.jpa.RolloutGroupRepository; +import org.eclipse.hawkbit.repository.jpa.model.JpaRolloutGroup; import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.RolloutGroup; import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupStatus; @@ -42,14 +41,11 @@ public class PauseRolloutGroupAction implements RolloutGroupActionEvaluator { @Override public void eval(final Rollout rollout, final RolloutGroup rolloutGroup, final String expression) { - systemSecurityContext.runAsSystem(new Callable() { - @Override - public Void call() throws Exception { - rolloutGroup.setStatus(RolloutGroupStatus.ERROR); - rolloutGroupRepository.save(rolloutGroup); - rolloutManagement.pauseRollout(rollout); - return null; - } + systemSecurityContext.runAsSystem(() -> { + rolloutGroup.setStatus(RolloutGroupStatus.ERROR); + rolloutGroupRepository.save((JpaRolloutGroup) rolloutGroup); + rolloutManagement.pauseRollout(rollout); + return null; }); } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/RolloutGroupActionEvaluator.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/RolloutGroupActionEvaluator.java similarity index 91% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/RolloutGroupActionEvaluator.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/RolloutGroupActionEvaluator.java index 1e2c98707..d375e68c5 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/RolloutGroupActionEvaluator.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/RolloutGroupActionEvaluator.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rollout.condition; +package org.eclipse.hawkbit.repository.jpa.rollout.condition; import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.RolloutGroup; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/RolloutGroupConditionEvaluator.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/RolloutGroupConditionEvaluator.java similarity index 87% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/RolloutGroupConditionEvaluator.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/RolloutGroupConditionEvaluator.java index 62c9050b1..0690f72ec 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/RolloutGroupConditionEvaluator.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/RolloutGroupConditionEvaluator.java @@ -6,14 +6,15 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rollout.condition; +package org.eclipse.hawkbit.repository.jpa.rollout.condition; import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.RolloutGroup; /** - * + * Verifies {@link RolloutGroup#getErrorConditionExp()}. */ +@FunctionalInterface public interface RolloutGroupConditionEvaluator { default boolean verifyExpression(final String expression) { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/StartNextGroupRolloutGroupSuccessAction.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/StartNextGroupRolloutGroupSuccessAction.java similarity index 89% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/StartNextGroupRolloutGroupSuccessAction.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/StartNextGroupRolloutGroupSuccessAction.java index 21c499d31..e12a26bac 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/StartNextGroupRolloutGroupSuccessAction.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/StartNextGroupRolloutGroupSuccessAction.java @@ -6,12 +6,13 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rollout.condition; +package org.eclipse.hawkbit.repository.jpa.rollout.condition; import java.util.List; import org.eclipse.hawkbit.repository.DeploymentManagement; -import org.eclipse.hawkbit.repository.RolloutGroupRepository; +import org.eclipse.hawkbit.repository.jpa.RolloutGroupRepository; +import org.eclipse.hawkbit.repository.jpa.model.JpaRolloutGroup; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.RolloutGroup; @@ -68,7 +69,7 @@ public class StartNextGroupRolloutGroupSuccessAction implements RolloutGroupActi final RolloutGroup nextGroup = action.getRolloutGroup(); logger.debug("Rolloutgroup {} is now running", nextGroup); nextGroup.setStatus(RolloutGroupStatus.RUNNING); - rolloutGroupRepository.save(nextGroup); + rolloutGroupRepository.save((JpaRolloutGroup) nextGroup); }); } else { logger.info("No actions to start for next rolloutgroup of parent {}", rolloutGroup); @@ -76,8 +77,8 @@ public class StartNextGroupRolloutGroupSuccessAction implements RolloutGroupActi // e.g. if targets has been deleted after the group has been // scheduled. If the group is empty now, we just finish the group if // there are not actions available for this group. - final List findByRolloutGroupParent = rolloutGroupRepository - .findByParentAndStatus(rolloutGroup, RolloutGroupStatus.SCHEDULED); + final List findByRolloutGroupParent = rolloutGroupRepository + .findByParentAndStatus((JpaRolloutGroup) rolloutGroup, RolloutGroupStatus.SCHEDULED); findByRolloutGroupParent.forEach(nextGroup -> { logger.debug("Rolloutgroup {} is finished, starting next group", nextGroup); nextGroup.setStatus(RolloutGroupStatus.FINISHED); diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/ThresholdRolloutGroupErrorCondition.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/ThresholdRolloutGroupErrorCondition.java similarity index 85% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/ThresholdRolloutGroupErrorCondition.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/ThresholdRolloutGroupErrorCondition.java index 6e63efa8e..cba134402 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/ThresholdRolloutGroupErrorCondition.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/ThresholdRolloutGroupErrorCondition.java @@ -6,9 +6,11 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rollout.condition; +package org.eclipse.hawkbit.repository.jpa.rollout.condition; -import org.eclipse.hawkbit.repository.ActionRepository; +import org.eclipse.hawkbit.repository.jpa.ActionRepository; +import org.eclipse.hawkbit.repository.jpa.model.JpaRollout; +import org.eclipse.hawkbit.repository.jpa.model.JpaRolloutGroup; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.RolloutGroup; @@ -30,7 +32,8 @@ public class ThresholdRolloutGroupErrorCondition implements RolloutGroupConditio @Override public boolean eval(final Rollout rollout, final RolloutGroup rolloutGroup, final String expression) { - final Long totalGroup = actionRepository.countByRolloutAndRolloutGroup(rollout, rolloutGroup); + final Long totalGroup = actionRepository.countByRolloutAndRolloutGroup((JpaRollout) rollout, + (JpaRolloutGroup) rolloutGroup); final Long error = actionRepository.countByRolloutIdAndRolloutGroupIdAndStatus(rollout.getId(), rolloutGroup.getId(), Action.Status.ERROR); try { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/ThresholdRolloutGroupSuccessCondition.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/ThresholdRolloutGroupSuccessCondition.java similarity index 94% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/ThresholdRolloutGroupSuccessCondition.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/ThresholdRolloutGroupSuccessCondition.java index fcf9762c6..3e098c701 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/rollout/condition/ThresholdRolloutGroupSuccessCondition.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/ThresholdRolloutGroupSuccessCondition.java @@ -6,9 +6,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rollout.condition; +package org.eclipse.hawkbit.repository.jpa.rollout.condition; -import org.eclipse.hawkbit.repository.ActionRepository; +import org.eclipse.hawkbit.repository.jpa.ActionRepository; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.RolloutGroup; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/rsql/PropertyMapper.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rsql/PropertyMapper.java similarity index 96% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/rsql/PropertyMapper.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rsql/PropertyMapper.java index ffa0e9212..db4417960 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/rsql/PropertyMapper.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rsql/PropertyMapper.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.rsql; +package org.eclipse.hawkbit.repository.jpa.rsql; import java.util.HashMap; import java.util.Map; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/rsql/RSQLUtility.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLUtility.java similarity index 99% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/rsql/RSQLUtility.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLUtility.java index 4edc46623..91e03342e 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/rsql/RSQLUtility.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLUtility.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.rsql; +package org.eclipse.hawkbit.repository.jpa.rsql; import java.util.ArrayList; import java.util.Arrays; @@ -26,6 +26,8 @@ import javax.persistence.criteria.Root; import org.eclipse.hawkbit.repository.FieldNameProvider; import org.eclipse.hawkbit.repository.FieldValueConverter; +import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException; +import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.SimpleTypeConverter; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/ActionSpecifications.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/specifications/ActionSpecifications.java similarity index 55% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/ActionSpecifications.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/specifications/ActionSpecifications.java index 62e7167f1..54d529d6c 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/ActionSpecifications.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/specifications/ActionSpecifications.java @@ -6,20 +6,22 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.specifications; +package org.eclipse.hawkbit.repository.jpa.specifications; import javax.persistence.criteria.Join; import javax.persistence.criteria.ListJoin; import javax.persistence.criteria.SetJoin; +import org.eclipse.hawkbit.repository.jpa.model.JpaAction; +import org.eclipse.hawkbit.repository.jpa.model.JpaAction_; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet_; +import org.eclipse.hawkbit.repository.jpa.model.JpaLocalArtifact; +import org.eclipse.hawkbit.repository.jpa.model.JpaLocalArtifact_; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule_; import org.eclipse.hawkbit.repository.model.Action; -import org.eclipse.hawkbit.repository.model.Action_; -import org.eclipse.hawkbit.repository.model.DistributionSet; -import org.eclipse.hawkbit.repository.model.DistributionSet_; import org.eclipse.hawkbit.repository.model.LocalArtifact; -import org.eclipse.hawkbit.repository.model.LocalArtifact_; -import org.eclipse.hawkbit.repository.model.SoftwareModule; -import org.eclipse.hawkbit.repository.model.SoftwareModule_; import org.eclipse.hawkbit.repository.model.Target; import org.springframework.data.jpa.domain.Specification; @@ -28,7 +30,7 @@ import org.springframework.data.jpa.domain.Specification; * Spring Data JPQL Specifications. * */ -public class ActionSpecifications { +public final class ActionSpecifications { private ActionSpecifications() { // utility class @@ -47,15 +49,16 @@ public class ActionSpecifications { * assigned * @return a specification to use with spring JPA */ - public static Specification hasTargetAssignedArtifact(final Target target, + public static Specification hasTargetAssignedArtifact(final Target target, final LocalArtifact localArtifact) { return (actionRoot, query, criteriaBuilder) -> { - final Join dsJoin = actionRoot.join(Action_.distributionSet); - final SetJoin modulesJoin = dsJoin.join(DistributionSet_.modules); - final ListJoin artifactsJoin = modulesJoin.join(SoftwareModule_.artifacts); + final Join dsJoin = actionRoot.join(JpaAction_.distributionSet); + final SetJoin modulesJoin = dsJoin.join(JpaDistributionSet_.modules); + final ListJoin artifactsJoin = modulesJoin + .join(JpaSoftwareModule_.artifacts); return criteriaBuilder.and( - criteriaBuilder.equal(artifactsJoin.get(LocalArtifact_.filename), localArtifact.getFilename()), - criteriaBuilder.equal(actionRoot.get(Action_.target), target)); + criteriaBuilder.equal(artifactsJoin.get(JpaLocalArtifact_.filename), localArtifact.getFilename()), + criteriaBuilder.equal(actionRoot.get(JpaAction_.target), target)); }; } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/DistributionSetSpecification.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/specifications/DistributionSetSpecification.java similarity index 58% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/DistributionSetSpecification.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/specifications/DistributionSetSpecification.java index b95f0b8e7..4ee849bcc 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/DistributionSetSpecification.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/specifications/DistributionSetSpecification.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.specifications; +package org.eclipse.hawkbit.repository.jpa.specifications; import java.util.Collection; @@ -18,15 +18,17 @@ import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.SetJoin; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag_; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet_; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetInfo; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetInfo_; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget_; import org.eclipse.hawkbit.repository.model.DistributionSet; -import org.eclipse.hawkbit.repository.model.DistributionSetTag; -import org.eclipse.hawkbit.repository.model.DistributionSetTag_; import org.eclipse.hawkbit.repository.model.DistributionSetType; -import org.eclipse.hawkbit.repository.model.DistributionSet_; -import org.eclipse.hawkbit.repository.model.Target; -import org.eclipse.hawkbit.repository.model.TargetInfo; -import org.eclipse.hawkbit.repository.model.TargetInfo_; -import org.eclipse.hawkbit.repository.model.Target_; import org.springframework.data.jpa.domain.Specification; /** @@ -48,8 +50,8 @@ public final class DistributionSetSpecification { * attribute is ignored * @return the {@link DistributionSet} {@link Specification} */ - public static Specification isDeleted(final Boolean isDeleted) { - return (targetRoot, query, cb) -> cb.equal(targetRoot. get(DistributionSet_.deleted), isDeleted); + public static Specification isDeleted(final Boolean isDeleted) { + return (targetRoot, query, cb) -> cb.equal(targetRoot. get(JpaDistributionSet_.deleted), isDeleted); } @@ -62,8 +64,8 @@ public final class DistributionSetSpecification { * the attribute is ignored * @return the {@link DistributionSet} {@link Specification} */ - public static Specification isCompleted(final Boolean isCompleted) { - return (targetRoot, query, cb) -> cb.equal(targetRoot. get(DistributionSet_.complete), isCompleted); + public static Specification isCompleted(final Boolean isCompleted) { + return (targetRoot, query, cb) -> cb.equal(targetRoot. get(JpaDistributionSet_.complete), isCompleted); } @@ -75,12 +77,12 @@ public final class DistributionSetSpecification { * to search * @return the {@link DistributionSet} {@link Specification} */ - public static Specification byId(final Long distid) { + public static Specification byId(final Long distid) { return (targetRoot, query, cb) -> { - final Predicate predicate = cb.equal(targetRoot. get(DistributionSet_.id), distid); - targetRoot.fetch(DistributionSet_.modules, JoinType.LEFT); - targetRoot.fetch(DistributionSet_.tags, JoinType.LEFT); - targetRoot.fetch(DistributionSet_.type, JoinType.LEFT); + final Predicate predicate = cb.equal(targetRoot. get(JpaDistributionSet_.id), distid); + targetRoot.fetch(JpaDistributionSet_.modules, JoinType.LEFT); + targetRoot.fetch(JpaDistributionSet_.tags, JoinType.LEFT); + targetRoot.fetch(JpaDistributionSet_.type, JoinType.LEFT); query.distinct(true); return predicate; @@ -95,12 +97,12 @@ public final class DistributionSetSpecification { * to search * @return the {@link DistributionSet} {@link Specification} */ - public static Specification byIds(final Collection distids) { + public static Specification byIds(final Collection distids) { return (targetRoot, query, cb) -> { - final Predicate predicate = targetRoot. get(DistributionSet_.id).in(distids); - targetRoot.fetch(DistributionSet_.modules, JoinType.LEFT); - targetRoot.fetch(DistributionSet_.tags, JoinType.LEFT); - targetRoot.fetch(DistributionSet_.type, JoinType.LEFT); + final Predicate predicate = targetRoot. get(JpaDistributionSet_.id).in(distids); + targetRoot.fetch(JpaDistributionSet_.modules, JoinType.LEFT); + targetRoot.fetch(JpaDistributionSet_.tags, JoinType.LEFT); + targetRoot.fetch(JpaDistributionSet_.type, JoinType.LEFT); query.distinct(true); return predicate; }; @@ -114,11 +116,11 @@ public final class DistributionSetSpecification { * to be filtered on * @return the {@link DistributionSet} {@link Specification} */ - public static Specification likeNameOrDescriptionOrVersion(final String subString) { + public static Specification likeNameOrDescriptionOrVersion(final String subString) { return (targetRoot, query, cb) -> cb.or( - cb.like(cb.lower(targetRoot. get(DistributionSet_.name)), subString.toLowerCase()), - cb.like(cb.lower(targetRoot. get(DistributionSet_.version)), subString.toLowerCase()), - cb.like(cb.lower(targetRoot. get(DistributionSet_.description)), subString.toLowerCase())); + cb.like(cb.lower(targetRoot. get(JpaDistributionSet_.name)), subString.toLowerCase()), + cb.like(cb.lower(targetRoot. get(JpaDistributionSet_.version)), subString.toLowerCase()), + cb.like(cb.lower(targetRoot. get(JpaDistributionSet_.description)), subString.toLowerCase())); } /** @@ -131,10 +133,10 @@ public final class DistributionSetSpecification { * flag to select distribution sets with no tag * @return the {@link DistributionSet} {@link Specification} */ - public static Specification hasTags(final Collection tagNames, + public static Specification hasTags(final Collection tagNames, final Boolean selectDSWithNoTag) { return (targetRoot, query, cb) -> { - final SetJoin tags = targetRoot.join(DistributionSet_.tags, + final SetJoin tags = targetRoot.join(JpaDistributionSet_.tags, JoinType.LEFT); final Predicate predicate = getPredicate(tags, tagNames, selectDSWithNoTag, cb); query.distinct(true); @@ -142,10 +144,10 @@ public final class DistributionSetSpecification { }; } - private static Predicate getPredicate(final SetJoin tags, + private static Predicate getPredicate(final SetJoin tags, final Collection tagNames, final Boolean selectDSWithNoTag, final CriteriaBuilder cb) { - tags.get(DistributionSetTag_.name); - final Path exp = tags.get(DistributionSetTag_.name); + tags.get(JpaDistributionSetTag_.name); + final Path exp = tags.get(JpaDistributionSetTag_.name); if (selectDSWithNoTag != null && selectDSWithNoTag) { if (tagNames != null) { return cb.or(exp.isNull(), exp.in(tagNames)); @@ -167,11 +169,11 @@ public final class DistributionSetSpecification { * to be filtered on * @return the {@link Specification} */ - public static Specification equalsNameAndVersionIgnoreCase(final String name, + public static Specification equalsNameAndVersionIgnoreCase(final String name, final String version) { return (targetRoot, query, cb) -> cb.and( - cb.equal(cb.lower(targetRoot. get(DistributionSet_.name)), name.toLowerCase()), - cb.equal(cb.lower(targetRoot. get(DistributionSet_.version)), version.toLowerCase())); + cb.equal(cb.lower(targetRoot. get(JpaDistributionSet_.name)), name.toLowerCase()), + cb.equal(cb.lower(targetRoot. get(JpaDistributionSet_.version)), version.toLowerCase())); } @@ -183,8 +185,9 @@ public final class DistributionSetSpecification { * to search * @return the {@link DistributionSet} {@link Specification} */ - public static Specification byType(final DistributionSetType type) { - return (targetRoot, query, cb) -> cb.equal(targetRoot. get(DistributionSet_.type), type); + public static Specification byType(final DistributionSetType type) { + return (targetRoot, query, cb) -> cb.equal(targetRoot. get(JpaDistributionSet_.type), + type); } @@ -195,12 +198,12 @@ public final class DistributionSetSpecification { * @return the specification to search for a distribution set which is * installed to the given targetId */ - public static Specification installedTarget(final String installedTargetId) { + public static Specification installedTarget(final String installedTargetId) { return (dsRoot, query, cb) -> { - final ListJoin installedTargetJoin = dsRoot - .join(DistributionSet_.installedAtTargets, JoinType.INNER); - final Join targetJoin = installedTargetJoin.join(TargetInfo_.target); - return cb.equal(targetJoin.get(Target_.controllerId), installedTargetId); + final ListJoin installedTargetJoin = dsRoot + .join(JpaDistributionSet_.installedAtTargets, JoinType.INNER); + final Join targetJoin = installedTargetJoin.join(JpaTargetInfo_.target); + return cb.equal(targetJoin.get(JpaTarget_.controllerId), installedTargetId); }; } @@ -211,11 +214,11 @@ public final class DistributionSetSpecification { * @return the specification to search for a distribution set which is * assigned to the given targetId */ - public static Specification assignedTarget(final String assignedTargetId) { + public static Specification assignedTarget(final String assignedTargetId) { return (dsRoot, query, cb) -> { - final ListJoin assignedTargetJoin = dsRoot.join(DistributionSet_.assignedToTargets, - JoinType.INNER); - return cb.equal(assignedTargetJoin.get(Target_.controllerId), assignedTargetId); + final ListJoin assignedTargetJoin = dsRoot + .join(JpaDistributionSet_.assignedToTargets, JoinType.INNER); + return cb.equal(assignedTargetJoin.get(JpaTarget_.controllerId), assignedTargetId); }; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/DistributionSetTypeSpecification.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/specifications/DistributionSetTypeSpecification.java similarity index 75% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/DistributionSetTypeSpecification.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/specifications/DistributionSetTypeSpecification.java index 13776deb0..0a8306faa 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/DistributionSetTypeSpecification.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/specifications/DistributionSetTypeSpecification.java @@ -6,11 +6,12 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.specifications; +package org.eclipse.hawkbit.repository.jpa.specifications; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType_; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetType; -import org.eclipse.hawkbit.repository.model.DistributionSetType_; import org.springframework.data.jpa.domain.Specification; /** @@ -31,8 +32,9 @@ public final class DistributionSetTypeSpecification { * attribute is ignored * @return the {@link DistributionSetType} {@link Specification} */ - public static Specification isDeleted(final Boolean isDeleted) { - return (targetRoot, query, cb) -> cb.equal(targetRoot. get(DistributionSetType_.deleted), isDeleted); + public static Specification isDeleted(final Boolean isDeleted) { + return (targetRoot, query, cb) -> cb.equal(targetRoot. get(JpaDistributionSetType_.deleted), + isDeleted); } /** @@ -44,8 +46,8 @@ public final class DistributionSetTypeSpecification { * to search * @return the {@link DistributionSet} {@link Specification} */ - public static Specification byId(final Long distid) { - return (targetRoot, query, cb) -> cb.equal(targetRoot. get(DistributionSetType_.id), distid); + public static Specification byId(final Long distid) { + return (targetRoot, query, cb) -> cb.equal(targetRoot. get(JpaDistributionSetType_.id), distid); } /** @@ -57,8 +59,8 @@ public final class DistributionSetTypeSpecification { * to search * @return the {@link DistributionSet} {@link Specification} */ - public static Specification byName(final String name) { - return (targetRoot, query, cb) -> cb.equal(targetRoot. get(DistributionSetType_.name), name); + public static Specification byName(final String name) { + return (targetRoot, query, cb) -> cb.equal(targetRoot. get(JpaDistributionSetType_.name), name); } /** @@ -70,8 +72,8 @@ public final class DistributionSetTypeSpecification { * to search * @return the {@link DistributionSet} {@link Specification} */ - public static Specification byKey(final String key) { - return (targetRoot, query, cb) -> cb.equal(targetRoot. get(DistributionSetType_.key), key); + public static Specification byKey(final String key) { + return (targetRoot, query, cb) -> cb.equal(targetRoot. get(JpaDistributionSetType_.key), key); } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/SoftwareModuleSpecification.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/specifications/SoftwareModuleSpecification.java similarity index 63% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/SoftwareModuleSpecification.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/specifications/SoftwareModuleSpecification.java index 680f97778..feba50ac8 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/SoftwareModuleSpecification.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/specifications/SoftwareModuleSpecification.java @@ -6,13 +6,14 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.specifications; +package org.eclipse.hawkbit.repository.jpa.specifications; import javax.persistence.criteria.Predicate; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule_; import org.eclipse.hawkbit.repository.model.SoftwareModule; -import org.eclipse.hawkbit.repository.model.SoftwareModuleType; -import org.eclipse.hawkbit.repository.model.SoftwareModule_; import org.springframework.data.jpa.domain.Specification; /** @@ -33,10 +34,10 @@ public final class SoftwareModuleSpecification { * to search for * @return the {@link SoftwareModule} {@link Specification} */ - public static Specification byId(final Long moduleId) { + public static Specification byId(final Long moduleId) { return (targetRoot, query, cb) -> { - final Predicate predicate = cb.equal(targetRoot. get(SoftwareModule_.id), moduleId); - targetRoot.fetch(SoftwareModule_.type); + final Predicate predicate = cb.equal(targetRoot. get(JpaSoftwareModule_.id), moduleId); + targetRoot.fetch(JpaSoftwareModule_.type); return predicate; }; } @@ -47,8 +48,8 @@ public final class SoftwareModuleSpecification { * * @return the {@link SoftwareModule} {@link Specification} */ - public static Specification isDeletedFalse() { - return (swRoot, query, cb) -> cb.equal(swRoot. get(SoftwareModule_.deleted), Boolean.FALSE); + public static Specification isDeletedFalse() { + return (swRoot, query, cb) -> cb.equal(swRoot. get(JpaSoftwareModule_.deleted), Boolean.FALSE); } /** @@ -59,10 +60,10 @@ public final class SoftwareModuleSpecification { * to be filtered on * @return the {@link SoftwareModule} {@link Specification} */ - public static Specification likeNameOrVersion(final String subString) { + public static Specification likeNameOrVersion(final String subString) { return (targetRoot, query, cb) -> cb.or( - cb.like(cb.lower(targetRoot. get(SoftwareModule_.name)), subString.toLowerCase()), - cb.like(cb.lower(targetRoot. get(SoftwareModule_.version)), subString.toLowerCase())); + cb.like(cb.lower(targetRoot. get(JpaSoftwareModule_.name)), subString.toLowerCase()), + cb.like(cb.lower(targetRoot. get(JpaSoftwareModule_.version)), subString.toLowerCase())); } /** @@ -73,8 +74,9 @@ public final class SoftwareModuleSpecification { * to be filtered on * @return the {@link SoftwareModule} {@link Specification} */ - public static Specification equalType(final SoftwareModuleType type) { - return (targetRoot, query, cb) -> cb.equal(targetRoot. get(SoftwareModule_.type), type); + public static Specification equalType(final JpaSoftwareModuleType type) { + return (targetRoot, query, cb) -> cb.equal(targetRoot. get(JpaSoftwareModule_.type), + type); } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/SpecificationsBuilder.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/specifications/SpecificationsBuilder.java similarity index 95% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/SpecificationsBuilder.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/specifications/SpecificationsBuilder.java index 83a4c6f8b..005942719 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/SpecificationsBuilder.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/specifications/SpecificationsBuilder.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.specifications; +package org.eclipse.hawkbit.repository.jpa.specifications; import java.util.List; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/TargetFilterQuerySpecification.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/specifications/TargetFilterQuerySpecification.java similarity index 51% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/TargetFilterQuerySpecification.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/specifications/TargetFilterQuerySpecification.java index 0b600c849..4b27c7fc7 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/TargetFilterQuerySpecification.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/specifications/TargetFilterQuerySpecification.java @@ -6,10 +6,11 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.specifications; +package org.eclipse.hawkbit.repository.jpa.specifications; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetFilterQuery; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetFilterQuery_; import org.eclipse.hawkbit.repository.model.TargetFilterQuery; -import org.eclipse.hawkbit.repository.model.TargetFilterQuery_; import org.springframework.data.jpa.domain.Specification; /** @@ -17,15 +18,23 @@ import org.springframework.data.jpa.domain.Specification; * Spring Data JPQL Specifications. * */ -public class TargetFilterQuerySpecification { +public final class TargetFilterQuerySpecification { private TargetFilterQuerySpecification() { // utility class } - public static Specification likeName(final String searchText) { + /** + * {@link Specification} for retrieving {@link JpaTargetFilterQuery}s based + * on is {@link JpaTargetFilterQuery#getName()}. + * + * @param searchText + * of the filter + * @return the {@link JpaTargetFilterQuery} {@link Specification} + */ + public static Specification likeName(final String searchText) { return (targetFilterQueryRoot, query, cb) -> { final String searchTextToLower = searchText.toLowerCase(); - return cb.like(cb.lower(targetFilterQueryRoot.get(TargetFilterQuery_.name)), searchTextToLower); + return cb.like(cb.lower(targetFilterQueryRoot.get(JpaTargetFilterQuery_.name)), searchTextToLower); }; } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/TargetSpecifications.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/specifications/TargetSpecifications.java similarity index 59% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/TargetSpecifications.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/specifications/TargetSpecifications.java index de894d3a3..6571f8668 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/TargetSpecifications.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/specifications/TargetSpecifications.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.specifications; +package org.eclipse.hawkbit.repository.jpa.specifications; import java.util.Collection; import java.util.List; @@ -20,15 +20,19 @@ import javax.persistence.criteria.Root; import javax.persistence.criteria.SetJoin; import javax.validation.constraints.NotNull; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet_; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetInfo; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetInfo_; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag_; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget_; import org.eclipse.hawkbit.repository.model.DistributionSet; -import org.eclipse.hawkbit.repository.model.DistributionSet_; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetInfo; -import org.eclipse.hawkbit.repository.model.TargetInfo_; import org.eclipse.hawkbit.repository.model.TargetTag; -import org.eclipse.hawkbit.repository.model.TargetTag_; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; -import org.eclipse.hawkbit.repository.model.Target_; import org.springframework.data.jpa.domain.Specification; /** @@ -50,10 +54,11 @@ public final class TargetSpecifications { * * @return the {@link Target} {@link Specification} */ - public static Specification byControllerIdWithStatusAndTagsInJoin(final Collection controllerIDs) { + public static Specification byControllerIdWithStatusAndTagsInJoin( + final Collection controllerIDs) { return (targetRoot, query, cb) -> { - final Predicate predicate = targetRoot.get(Target_.controllerId).in(controllerIDs); - targetRoot.fetch(Target_.tags, JoinType.LEFT); + final Predicate predicate = targetRoot.get(JpaTarget_.controllerId).in(controllerIDs); + targetRoot.fetch(JpaTarget_.tags, JoinType.LEFT); query.distinct(true); return predicate; }; @@ -68,12 +73,12 @@ public final class TargetSpecifications { * * @return the {@link Target} {@link Specification} */ - public static Specification byControllerIdWithStatusAndAssignedInJoin( + public static Specification byControllerIdWithStatusAndAssignedInJoin( final Collection controllerIDs) { return (targetRoot, query, cb) -> { - final Predicate predicate = targetRoot.get(Target_.controllerId).in(controllerIDs); - targetRoot.fetch(Target_.assignedDistributionSet); + final Predicate predicate = targetRoot.get(JpaTarget_.controllerId).in(controllerIDs); + targetRoot.fetch(JpaTarget_.assignedDistributionSet); return predicate; }; } @@ -89,19 +94,19 @@ public final class TargetSpecifications { * join it. * @return the {@link Target} {@link Specification} */ - public static Specification hasTargetUpdateStatus(final Collection updateStatus, + public static Specification hasTargetUpdateStatus(final Collection updateStatus, final boolean fetch) { return (targetRoot, query, cb) -> { if (!query.getResultType().isAssignableFrom(Long.class)) { if (fetch) { - targetRoot.fetch(Target_.targetInfo); + targetRoot.fetch(JpaTarget_.targetInfo); } else { - targetRoot.join(Target_.targetInfo); + targetRoot.join(JpaTarget_.targetInfo); } - return targetRoot.get(Target_.targetInfo).get(TargetInfo_.updateStatus).in(updateStatus); + return targetRoot.get(JpaTarget_.targetInfo).get(JpaTargetInfo_.updateStatus).in(updateStatus); } - final Join targetInfoJoin = targetRoot.join(Target_.targetInfo); - return targetInfoJoin.get(TargetInfo_.updateStatus).in(updateStatus); + final Join targetInfoJoin = targetRoot.join(JpaTarget_.targetInfo); + return targetInfoJoin.get(JpaTargetInfo_.updateStatus).in(updateStatus); }; } @@ -113,11 +118,11 @@ public final class TargetSpecifications { * to be filtered on * @return the {@link Target} {@link Specification} */ - public static Specification likeNameOrDescriptionOrIp(final String searchText) { + public static Specification likeNameOrDescriptionOrIp(final String searchText) { return (targetRoot, query, cb) -> { final String searchTextToLower = searchText.toLowerCase(); - return cb.or(cb.like(cb.lower(targetRoot.get(Target_.name)), searchTextToLower), - cb.like(cb.lower(targetRoot.get(Target_.description)), searchTextToLower)); + return cb.or(cb.like(cb.lower(targetRoot.get(JpaTarget_.name)), searchTextToLower), + cb.like(cb.lower(targetRoot.get(JpaTarget_.description)), searchTextToLower)); }; } @@ -129,14 +134,14 @@ public final class TargetSpecifications { * to be filtered on * @return the {@link Target} {@link Specification} */ - public static Specification hasInstalledOrAssignedDistributionSet(@NotNull final Long distributionId) { + public static Specification hasInstalledOrAssignedDistributionSet(@NotNull final Long distributionId) { return (targetRoot, query, cb) -> { - final Join targetInfoJoin = targetRoot.join(Target_.targetInfo); + final Join targetInfoJoin = targetRoot.join(JpaTarget_.targetInfo); return cb.or( - cb.equal(targetInfoJoin.get(TargetInfo_.installedDistributionSet).get(DistributionSet_.id), + cb.equal(targetInfoJoin.get(JpaTargetInfo_.installedDistributionSet).get(JpaDistributionSet_.id), distributionId), - cb.equal(targetRoot. get(Target_.assignedDistributionSet).get(DistributionSet_.id), - distributionId)); + cb.equal(targetRoot. get(JpaTarget_.assignedDistributionSet) + .get(JpaDistributionSet_.id), distributionId)); }; } @@ -150,13 +155,12 @@ public final class TargetSpecifications { * set that is not yet assigned * @return the {@link Target} {@link Specification} */ - public static Specification hasControllerIdAndAssignedDistributionSetIdNot(final List tIDs, + public static Specification hasControllerIdAndAssignedDistributionSetIdNot(final List tIDs, @NotNull final Long distributionId) { - return (targetRoot, query, cb) -> cb - .and(targetRoot.get(Target_.controllerId).in(tIDs), - cb.or(cb.notEqual(targetRoot. get(Target_.assignedDistributionSet) - .get(DistributionSet_.id), distributionId), - cb.isNull(targetRoot. get(Target_.assignedDistributionSet)))); + return (targetRoot, query, cb) -> cb.and(targetRoot.get(JpaTarget_.controllerId).in(tIDs), + cb.or(cb.notEqual(targetRoot. get(JpaTarget_.assignedDistributionSet) + .get(JpaDistributionSet_.id), distributionId), + cb.isNull(targetRoot. get(JpaTarget_.assignedDistributionSet)))); } /** @@ -169,7 +173,7 @@ public final class TargetSpecifications { * flag to get targets with no tag assigned * @return the {@link Target} {@link Specification} */ - public static Specification hasTags(final String[] tagNames, final Boolean selectTargetWithNoTag) { + public static Specification hasTags(final String[] tagNames, final Boolean selectTargetWithNoTag) { return (targetRoot, query, cb) -> { final Predicate predicate = getPredicate(targetRoot, cb, selectTargetWithNoTag, tagNames); query.distinct(true); @@ -177,10 +181,10 @@ public final class TargetSpecifications { }; } - private static Predicate getPredicate(final Root targetRoot, final CriteriaBuilder cb, + private static Predicate getPredicate(final Root targetRoot, final CriteriaBuilder cb, final Boolean selectTargetWithNoTag, final String[] tagNames) { - final SetJoin tags = targetRoot.join(Target_.tags, JoinType.LEFT); - final Path exp = tags.get(TargetTag_.name); + final SetJoin tags = targetRoot.join(JpaTarget_.tags, JoinType.LEFT); + final Path exp = tags.get(JpaTargetTag_.name); if (selectTargetWithNoTag) { if (tagNames != null) { return cb.or(exp.isNull(), exp.in(tagNames)); @@ -200,9 +204,9 @@ public final class TargetSpecifications { * the ID of the distribution set which must be assigned * @return the {@link Target} {@link Specification} */ - public static Specification hasAssignedDistributionSet(final Long distributionSetId) { + public static Specification hasAssignedDistributionSet(final Long distributionSetId) { return (targetRoot, query, cb) -> cb.equal( - targetRoot. get(Target_.assignedDistributionSet).get(DistributionSet_.id), + targetRoot. get(JpaTarget_.assignedDistributionSet).get(JpaDistributionSet_.id), distributionSetId); } @@ -214,10 +218,10 @@ public final class TargetSpecifications { * the ID of the distribution set which must be assigned * @return the {@link Target} {@link Specification} */ - public static Specification hasInstalledDistributionSet(final Long distributionSetId) { + public static Specification hasInstalledDistributionSet(final Long distributionSetId) { return (targetRoot, query, cb) -> { - final Join targetInfoJoin = targetRoot.join(Target_.targetInfo); - return cb.equal(targetInfoJoin.get(TargetInfo_.installedDistributionSet).get(DistributionSet_.id), + final Join targetInfoJoin = targetRoot.join(JpaTarget_.targetInfo); + return cb.equal(targetInfoJoin.get(JpaTargetInfo_.installedDistributionSet).get(JpaDistributionSet_.id), distributionSetId); }; } diff --git a/hawkbit-repository/src/main/resources/db/migration/H2/V1_0_1__init___H2.sql b/hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/H2/V1_0_1__init___H2.sql similarity index 100% rename from hawkbit-repository/src/main/resources/db/migration/H2/V1_0_1__init___H2.sql rename to hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/H2/V1_0_1__init___H2.sql diff --git a/hawkbit-repository/src/main/resources/db/migration/H2/V1_2_0__update_target_info_for_message___H2.sql b/hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/H2/V1_2_0__update_target_info_for_message___H2.sql similarity index 100% rename from hawkbit-repository/src/main/resources/db/migration/H2/V1_2_0__update_target_info_for_message___H2.sql rename to hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/H2/V1_2_0__update_target_info_for_message___H2.sql diff --git a/hawkbit-repository/src/main/resources/db/migration/H2/V1_4_0__cascade_delete___H2.sql b/hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/H2/V1_4_0__cascade_delete___H2.sql similarity index 100% rename from hawkbit-repository/src/main/resources/db/migration/H2/V1_4_0__cascade_delete___H2.sql rename to hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/H2/V1_4_0__cascade_delete___H2.sql diff --git a/hawkbit-repository/src/main/resources/db/migration/H2/V1_4_1__cascade_delete___H2.sql b/hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/H2/V1_4_1__cascade_delete___H2.sql similarity index 100% rename from hawkbit-repository/src/main/resources/db/migration/H2/V1_4_1__cascade_delete___H2.sql rename to hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/H2/V1_4_1__cascade_delete___H2.sql diff --git a/hawkbit-repository/src/main/resources/db/migration/H2/V1_5_0__target_filter_query___H2.sql b/hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/H2/V1_5_0__target_filter_query___H2.sql similarity index 100% rename from hawkbit-repository/src/main/resources/db/migration/H2/V1_5_0__target_filter_query___H2.sql rename to hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/H2/V1_5_0__target_filter_query___H2.sql diff --git a/hawkbit-repository/src/main/resources/db/migration/H2/V1_6_0__rollout_management___H2.sql b/hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/H2/V1_6_0__rollout_management___H2.sql similarity index 100% rename from hawkbit-repository/src/main/resources/db/migration/H2/V1_6_0__rollout_management___H2.sql rename to hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/H2/V1_6_0__rollout_management___H2.sql diff --git a/hawkbit-repository/src/main/resources/db/migration/MYSQL/V1_0_1__init___MYSQL.sql b/hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/MYSQL/V1_0_1__init___MYSQL.sql similarity index 100% rename from hawkbit-repository/src/main/resources/db/migration/MYSQL/V1_0_1__init___MYSQL.sql rename to hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/MYSQL/V1_0_1__init___MYSQL.sql diff --git a/hawkbit-repository/src/main/resources/db/migration/MYSQL/V1_2_0__update_target_info_for_message___MYSQL.sql b/hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/MYSQL/V1_2_0__update_target_info_for_message___MYSQL.sql similarity index 100% rename from hawkbit-repository/src/main/resources/db/migration/MYSQL/V1_2_0__update_target_info_for_message___MYSQL.sql rename to hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/MYSQL/V1_2_0__update_target_info_for_message___MYSQL.sql diff --git a/hawkbit-repository/src/main/resources/db/migration/MYSQL/V1_4_0__cascade_delete___MYSQL.sql b/hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/MYSQL/V1_4_0__cascade_delete___MYSQL.sql similarity index 100% rename from hawkbit-repository/src/main/resources/db/migration/MYSQL/V1_4_0__cascade_delete___MYSQL.sql rename to hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/MYSQL/V1_4_0__cascade_delete___MYSQL.sql diff --git a/hawkbit-repository/src/main/resources/db/migration/MYSQL/V1_4_1__cascade_delete___MYSQL.sql b/hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/MYSQL/V1_4_1__cascade_delete___MYSQL.sql similarity index 100% rename from hawkbit-repository/src/main/resources/db/migration/MYSQL/V1_4_1__cascade_delete___MYSQL.sql rename to hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/MYSQL/V1_4_1__cascade_delete___MYSQL.sql diff --git a/hawkbit-repository/src/main/resources/db/migration/MYSQL/V1_5_0__target_filter_query___MYSQL.sql b/hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/MYSQL/V1_5_0__target_filter_query___MYSQL.sql similarity index 100% rename from hawkbit-repository/src/main/resources/db/migration/MYSQL/V1_5_0__target_filter_query___MYSQL.sql rename to hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/MYSQL/V1_5_0__target_filter_query___MYSQL.sql diff --git a/hawkbit-repository/src/main/resources/db/migration/MYSQL/V1_6_0__rollout_management___MYSQL.sql b/hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/MYSQL/V1_6_0__rollout_management___MYSQL.sql similarity index 100% rename from hawkbit-repository/src/main/resources/db/migration/MYSQL/V1_6_0__rollout_management___MYSQL.sql rename to hawkbit-repository/hawkbit-repository-jpa/src/main/resources/db/migration/MYSQL/V1_6_0__rollout_management___MYSQL.sql diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/AbstractJpaIntegrationTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/AbstractJpaIntegrationTest.java new file mode 100644 index 000000000..b4b451ecd --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/AbstractJpaIntegrationTest.java @@ -0,0 +1,79 @@ +/** + * 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.jpa; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import org.eclipse.hawkbit.cache.TenantAwareCacheManager; +import org.eclipse.hawkbit.repository.util.AbstractIntegrationTest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.data.mongodb.gridfs.GridFsOperations; + +@SpringApplicationConfiguration(classes = { org.eclipse.hawkbit.RepositoryApplicationConfiguration.class }) +public abstract class AbstractJpaIntegrationTest extends AbstractIntegrationTest { + + @PersistenceContext + protected EntityManager entityManager; + + @Autowired + protected TargetRepository targetRepository; + + @Autowired + protected ActionRepository actionRepository; + + @Autowired + protected DistributionSetRepository distributionSetRepository; + + @Autowired + protected SoftwareModuleRepository softwareModuleRepository; + + @Autowired + protected TenantMetaDataRepository tenantMetaDataRepository; + + @Autowired + protected DistributionSetTypeRepository distributionSetTypeRepository; + + @Autowired + protected SoftwareModuleTypeRepository softwareModuleTypeRepository; + + @Autowired + protected TargetTagRepository targetTagRepository; + + @Autowired + protected DistributionSetTagRepository distributionSetTagRepository; + + @Autowired + protected SoftwareModuleMetadataRepository softwareModuleMetadataRepository; + + @Autowired + protected ActionStatusRepository actionStatusRepository; + + @Autowired + protected ExternalArtifactRepository externalArtifactRepository; + + @Autowired + protected LocalArtifactRepository artifactRepository; + + @Autowired + protected TargetInfoRepository targetInfoRepository; + + @Autowired + protected GridFsOperations operations; + + @Autowired + protected RolloutGroupRepository rolloutGroupRepository; + + @Autowired + protected RolloutRepository rolloutRepository; + + @Autowired + protected TenantAwareCacheManager cacheManager; +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/AbstractJpaIntegrationTestWithMongoDB.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/AbstractJpaIntegrationTestWithMongoDB.java new file mode 100644 index 000000000..d1c433cc4 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/AbstractJpaIntegrationTestWithMongoDB.java @@ -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.jpa; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import org.eclipse.hawkbit.cache.TenantAwareCacheManager; +import org.eclipse.hawkbit.repository.util.AbstractIntegrationTestWithMongoDB; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.SpringApplicationConfiguration; + +@SpringApplicationConfiguration(classes = { org.eclipse.hawkbit.RepositoryApplicationConfiguration.class }) +public abstract class AbstractJpaIntegrationTestWithMongoDB extends AbstractIntegrationTestWithMongoDB { + + @PersistenceContext + protected EntityManager entityManager; + + @Autowired + protected TargetRepository targetRepository; + + @Autowired + protected ActionRepository actionRepository; + + @Autowired + protected DistributionSetRepository distributionSetRepository; + + @Autowired + protected SoftwareModuleRepository softwareModuleRepository; + + @Autowired + protected TenantMetaDataRepository tenantMetaDataRepository; + + @Autowired + protected DistributionSetTypeRepository distributionSetTypeRepository; + + @Autowired + protected SoftwareModuleTypeRepository softwareModuleTypeRepository; + + @Autowired + protected TargetTagRepository targetTagRepository; + + @Autowired + protected DistributionSetTagRepository distributionSetTagRepository; + + @Autowired + protected SoftwareModuleMetadataRepository softwareModuleMetadataRepository; + + @Autowired + protected ActionStatusRepository actionStatusRepository; + + @Autowired + protected ExternalArtifactRepository externalArtifactRepository; + + @Autowired + protected LocalArtifactRepository artifactRepository; + + @Autowired + protected TargetInfoRepository targetInfoRepository; + + @Autowired + protected RolloutGroupRepository rolloutGroupRepository; + + @Autowired + protected RolloutRepository rolloutRepository; + + @Autowired + protected TenantAwareCacheManager cacheManager; + +} diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ActionTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ActionTest.java similarity index 87% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ActionTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ActionTest.java index 937a544a7..9104f28cf 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ActionTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ActionTest.java @@ -6,11 +6,11 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import static org.fest.assertions.api.Assertions.assertThat; -import org.eclipse.hawkbit.repository.model.Action; +import org.eclipse.hawkbit.repository.jpa.model.JpaAction; import org.eclipse.hawkbit.repository.model.Action.ActionType; import org.junit.Test; @@ -26,11 +26,11 @@ public class ActionTest { @Description("Ensures that timeforced moded switch from soft to forces after defined timeframe.") public void timeforcedHitNewHasCodeIsGenerated() throws InterruptedException { - final boolean active = true; + final boolean active; // current time + 1 seconds final long sleepTime = 1000; final long timeForceTimeAt = System.currentTimeMillis() + sleepTime; - final Action timeforcedAction = new Action(); + final JpaAction timeforcedAction = new JpaAction(); timeforcedAction.setActionType(ActionType.TIMEFORCED); timeforcedAction.setForcedTime(timeForceTimeAt); assertThat(timeforcedAction.isForce()).isFalse(); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ArtifactManagementNoMongoDbTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ArtifactManagementNoMongoDbTest.java similarity index 84% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ArtifactManagementNoMongoDbTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ArtifactManagementNoMongoDbTest.java index 30f4093c2..42b759b74 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ArtifactManagementNoMongoDbTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ArtifactManagementNoMongoDbTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import static org.junit.Assert.fail; @@ -14,9 +14,8 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import org.apache.commons.lang3.RandomStringUtils; -import org.eclipse.hawkbit.AbstractIntegrationTest; import org.eclipse.hawkbit.repository.exception.ArtifactUploadFailedException; -import org.eclipse.hawkbit.repository.model.SoftwareModule; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; import org.junit.BeforeClass; import org.junit.Test; @@ -30,7 +29,7 @@ import ru.yandex.qatools.allure.annotations.Stories; */ @Features("Component Tests - Repository") @Stories("Artifact Management") -public class ArtifactManagementNoMongoDbTest extends AbstractIntegrationTest { +public class ArtifactManagementNoMongoDbTest extends AbstractJpaIntegrationTest { @BeforeClass public static void initialize() { @@ -42,7 +41,7 @@ public class ArtifactManagementNoMongoDbTest extends AbstractIntegrationTest { @Test @Description("Checks if the expected ArtifactUploadFailedException is thrown in case of MongoDB down") public void createLocalArtifactWithMongoDbDown() throws IOException { - SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", + JpaSoftwareModule sm = new JpaSoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", "version 1", null, null); sm = softwareModuleRepository.save(sm); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ArtifactManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ArtifactManagementTest.java similarity index 73% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ArtifactManagementTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ArtifactManagementTest.java index 7c801a571..faf7649d0 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ArtifactManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ArtifactManagementTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import static org.fest.assertions.api.Assertions.assertThat; import static org.junit.Assert.assertNotNull; @@ -20,18 +20,20 @@ import java.security.NoSuchAlgorithmException; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.RandomStringUtils; -import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB; -import org.eclipse.hawkbit.HashGeneratorUtils; -import org.eclipse.hawkbit.RandomGeneratedInputStream; -import org.eclipse.hawkbit.WithUser; import org.eclipse.hawkbit.im.authentication.SpPermission; +import org.eclipse.hawkbit.repository.ArtifactManagement; import org.eclipse.hawkbit.repository.exception.ArtifactDeleteFailedException; import org.eclipse.hawkbit.repository.exception.InsufficientPermissionException; +import org.eclipse.hawkbit.repository.jpa.model.JpaExternalArtifact; +import org.eclipse.hawkbit.repository.jpa.model.JpaExternalArtifactProvider; +import org.eclipse.hawkbit.repository.jpa.model.JpaLocalArtifact; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; 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.eclipse.hawkbit.repository.util.HashGeneratorUtils; +import org.eclipse.hawkbit.repository.util.WithUser; import org.junit.Test; import org.slf4j.LoggerFactory; import org.springframework.data.mongodb.core.query.Criteria; @@ -50,7 +52,7 @@ import ru.yandex.qatools.allure.annotations.Stories; */ @Features("Component Tests - Repository") @Stories("Artifact Management") -public class ArtifactManagementTest extends AbstractIntegrationTestWithMongoDB { +public class ArtifactManagementTest extends AbstractJpaIntegrationTestWithMongoDB { public ArtifactManagementTest() { LOG = LoggerFactory.getLogger(ArtifactManagementTest.class); } @@ -70,15 +72,15 @@ public class ArtifactManagementTest extends AbstractIntegrationTestWithMongoDB { assertThat(softwareModuleRepository.findAll()).hasSize(0); assertThat(artifactRepository.findAll()).hasSize(0); - SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", + JpaSoftwareModule sm = new JpaSoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", "version 1", null, null); sm = softwareModuleRepository.save(sm); - SoftwareModule sm2 = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 2", + JpaSoftwareModule sm2 = new JpaSoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 2", "version 2", null, null); sm2 = softwareModuleRepository.save(sm2); - SoftwareModule sm3 = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 3", + JpaSoftwareModule sm3 = new JpaSoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 3", "version 3", null, null); sm3 = softwareModuleRepository.save(sm3); @@ -96,11 +98,11 @@ public class ArtifactManagementTest extends AbstractIntegrationTestWithMongoDB { assertThat(result).isInstanceOf(LocalArtifact.class); assertThat(result.getSoftwareModule().getId()).isEqualTo(sm.getId()); assertThat(result2.getSoftwareModule().getId()).isEqualTo(sm2.getId()); - assertThat(((LocalArtifact) result).getFilename()).isEqualTo("file1"); - assertThat(((LocalArtifact) result).getGridFsFileName()).isNotNull(); + assertThat(((JpaLocalArtifact) result).getFilename()).isEqualTo("file1"); + assertThat(((JpaLocalArtifact) result).getGridFsFileName()).isNotNull(); assertThat(result).isNotEqualTo(result2); - assertThat(((LocalArtifact) result).getGridFsFileName()) - .isEqualTo(((LocalArtifact) result2).getGridFsFileName()); + assertThat(((JpaLocalArtifact) result).getGridFsFileName()) + .isEqualTo(((JpaLocalArtifact) result2).getGridFsFileName()); assertThat(artifactManagement.findLocalArtifactByFilename("file1").get(0).getSha1Hash()) .isEqualTo(HashGeneratorUtils.generateSHA1(random)); @@ -116,7 +118,7 @@ public class ArtifactManagementTest extends AbstractIntegrationTestWithMongoDB { @Test @Description("Tests hard delete directly on repository.") public void hardDeleteSoftwareModule() throws NoSuchAlgorithmException, IOException { - SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", + JpaSoftwareModule sm = new JpaSoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", "version 1", null, null); sm = softwareModuleRepository.save(sm); @@ -137,18 +139,19 @@ public class ArtifactManagementTest extends AbstractIntegrationTestWithMongoDB { @Test @Description("Tests the creation of an external artifact metadata element.") public void createExternalArtifact() { - SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", + JpaSoftwareModule sm = new JpaSoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", "version 1", null, null); sm = softwareModuleRepository.save(sm); - SoftwareModule sm2 = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 2", + JpaSoftwareModule sm2 = new JpaSoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 2", "version 2", null, null); sm2 = softwareModuleRepository.save(sm2); final ExternalArtifactProvider provider = artifactManagement.createExternalArtifactProvider("provider X", null, "https://fhghdfjgh", "/{version}/"); - ExternalArtifact result = artifactManagement.createExternalArtifact(provider, null, sm.getId()); + JpaExternalArtifact result = (JpaExternalArtifact) artifactManagement.createExternalArtifact(provider, null, + sm.getId()); assertNotNull("The result of an external artifact should not be null", result); assertThat(externalArtifactRepository.findAll()).contains(result).hasSize(1); @@ -156,7 +159,7 @@ public class ArtifactManagementTest extends AbstractIntegrationTestWithMongoDB { assertThat(result.getUrl()).isEqualTo("https://fhghdfjgh/{version}/"); assertThat(result.getExternalArtifactProvider()).isEqualTo(provider); - result = artifactManagement.createExternalArtifact(provider, "/test", sm2.getId()); + result = (JpaExternalArtifact) artifactManagement.createExternalArtifact(provider, "/test", sm2.getId()); assertNotNull("The newly created external artifact should not be null", result); assertThat(externalArtifactRepository.findAll()).contains(result).hasSize(2); assertThat(result.getUrl()).isEqualTo("https://fhghdfjgh/test"); @@ -168,14 +171,15 @@ public class ArtifactManagementTest extends AbstractIntegrationTestWithMongoDB { public void deleteExternalArtifact() { assertThat(artifactRepository.findAll()).isEmpty(); - SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", + JpaSoftwareModule sm = new JpaSoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", "version 1", null, null); sm = softwareModuleRepository.save(sm); - final ExternalArtifactProvider provider = artifactManagement.createExternalArtifactProvider("provider X", null, - "https://fhghdfjgh", "/{version}/"); + final JpaExternalArtifactProvider provider = (JpaExternalArtifactProvider) artifactManagement + .createExternalArtifactProvider("provider X", null, "https://fhghdfjgh", "/{version}/"); - final ExternalArtifact result = artifactManagement.createExternalArtifact(provider, null, sm.getId()); + final JpaExternalArtifact result = (JpaExternalArtifact) artifactManagement.createExternalArtifact(provider, + null, sm.getId()); assertNotNull("The newly created external artifact should not be null", result); assertThat(externalArtifactRepository.findAll()).contains(result).hasSize(1); @@ -194,11 +198,11 @@ public class ArtifactManagementTest extends AbstractIntegrationTestWithMongoDB { @Test @Description("Tests the deletion of a local artifact including metadata.") public void deleteLocalArtifact() throws NoSuchAlgorithmException, IOException { - SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", + JpaSoftwareModule sm = new JpaSoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", "version 1", null, null); sm = softwareModuleRepository.save(sm); - SoftwareModule sm2 = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 2", + JpaSoftwareModule sm2 = new JpaSoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 2", "version 2", null, null); sm2 = softwareModuleRepository.save(sm2); @@ -213,26 +217,25 @@ public class ArtifactManagementTest extends AbstractIntegrationTestWithMongoDB { assertThat(result.getId()).isNotNull(); assertThat(result2.getId()).isNotNull(); - assertThat(((LocalArtifact) result).getGridFsFileName()) - .isNotEqualTo(((LocalArtifact) result2).getGridFsFileName()); - assertThat(operations.findOne( - new Query().addCriteria(Criteria.where("filename").is(((LocalArtifact) result).getGridFsFileName())))) + assertThat(((JpaLocalArtifact) result).getGridFsFileName()) + .isNotEqualTo(((JpaLocalArtifact) result2).getGridFsFileName()); + assertThat(operations.findOne(new Query() + .addCriteria(Criteria.where("filename").is(((JpaLocalArtifact) result).getGridFsFileName())))) .isNotNull(); - assertThat(operations.findOne( - new Query().addCriteria(Criteria.where("filename").is(((LocalArtifact) result2).getGridFsFileName())))) + assertThat(operations.findOne(new Query() + .addCriteria(Criteria.where("filename").is(((JpaLocalArtifact) result2).getGridFsFileName())))) .isNotNull(); artifactManagement.deleteLocalArtifact(result.getId()); - assertThat(operations.findOne( - new Query().addCriteria(Criteria.where("filename").is(((LocalArtifact) result).getGridFsFileName())))) - .isNull(); - assertThat(operations.findOne( - new Query().addCriteria(Criteria.where("filename").is(((LocalArtifact) result2).getGridFsFileName())))) + assertThat(operations.findOne(new Query() + .addCriteria(Criteria.where("filename").is(((JpaLocalArtifact) result).getGridFsFileName())))).isNull(); + assertThat(operations.findOne(new Query() + .addCriteria(Criteria.where("filename").is(((JpaLocalArtifact) result2).getGridFsFileName())))) .isNotNull(); artifactManagement.deleteLocalArtifact(result2.getId()); - assertThat(operations.findOne( - new Query().addCriteria(Criteria.where("filename").is(((LocalArtifact) result2).getGridFsFileName())))) + assertThat(operations.findOne(new Query() + .addCriteria(Criteria.where("filename").is(((JpaLocalArtifact) result2).getGridFsFileName())))) .isNull(); assertThat(artifactRepository.findAll()).hasSize(0); @@ -245,7 +248,7 @@ public class ArtifactManagementTest extends AbstractIntegrationTestWithMongoDB { assertThat(artifactRepository.findAll()).isEmpty(); // prepare test - SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", + JpaSoftwareModule sm = new JpaSoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", "version 1", null, null); sm = softwareModuleRepository.save(sm); @@ -272,11 +275,11 @@ public class ArtifactManagementTest extends AbstractIntegrationTestWithMongoDB { @Description("Test the deletion of an artifact metadata where the binary is still linked to another " + "metadata element. The expected result is that the metadata is deleted but the binary kept.") public void deleteDuplicateArtifacts() throws NoSuchAlgorithmException, IOException { - SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", + JpaSoftwareModule sm = new JpaSoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", "version 1", null, null); sm = softwareModuleRepository.save(sm); - SoftwareModule sm2 = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 2", + JpaSoftwareModule sm2 = new JpaSoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 2", "version 2", null, null); sm2 = softwareModuleRepository.save(sm2); @@ -290,21 +293,20 @@ public class ArtifactManagementTest extends AbstractIntegrationTestWithMongoDB { assertThat(artifactRepository.findAll()).hasSize(2); assertThat(result.getId()).isNotNull(); assertThat(result2.getId()).isNotNull(); - assertThat(((LocalArtifact) result).getGridFsFileName()) - .isEqualTo(((LocalArtifact) result2).getGridFsFileName()); + assertThat(((JpaLocalArtifact) result).getGridFsFileName()) + .isEqualTo(((JpaLocalArtifact) result2).getGridFsFileName()); - assertThat(operations.findOne( - new Query().addCriteria(Criteria.where("filename").is(((LocalArtifact) result).getGridFsFileName())))) + assertThat(operations.findOne(new Query() + .addCriteria(Criteria.where("filename").is(((JpaLocalArtifact) result).getGridFsFileName())))) .isNotNull(); artifactManagement.deleteLocalArtifact(result.getId()); - assertThat(operations.findOne( - new Query().addCriteria(Criteria.where("filename").is(((LocalArtifact) result).getGridFsFileName())))) + assertThat(operations.findOne(new Query() + .addCriteria(Criteria.where("filename").is(((JpaLocalArtifact) result).getGridFsFileName())))) .isNotNull(); artifactManagement.deleteLocalArtifact(result2.getId()); - assertThat(operations.findOne( - new Query().addCriteria(Criteria.where("filename").is(((LocalArtifact) result).getGridFsFileName())))) - .isNull(); + assertThat(operations.findOne(new Query() + .addCriteria(Criteria.where("filename").is(((JpaLocalArtifact) result).getGridFsFileName())))).isNull(); } /** @@ -318,7 +320,7 @@ public class ArtifactManagementTest extends AbstractIntegrationTestWithMongoDB { @Test @Description("Loads an artifact based on given ID.") public void findArtifact() throws NoSuchAlgorithmException, IOException { - SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", + SoftwareModule sm = new JpaSoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", "version 1", null, null); sm = softwareManagement.createSoftwareModule(sm); @@ -339,7 +341,7 @@ public class ArtifactManagementTest extends AbstractIntegrationTestWithMongoDB { @Test @Description("Loads an artifact binary based on given ID.") public void loadStreamOfLocalArtifact() throws NoSuchAlgorithmException, IOException { - SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", + SoftwareModule sm = new JpaSoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", "version 1", null, null); sm = softwareManagement.createSoftwareModule(sm); @@ -357,7 +359,7 @@ public class ArtifactManagementTest extends AbstractIntegrationTestWithMongoDB { @Description("Trys and fails to load an artifact without required permission. Checks if expected InsufficientPermissionException is thrown.") public void loadLocalArtifactBinaryWithoutDownloadArtifactThrowsPermissionDenied() { try { - artifactManagement.loadLocalArtifactBinary(new LocalArtifact()); + artifactManagement.loadLocalArtifactBinary(new JpaLocalArtifact()); fail("Should not have worked with missing permission."); } catch (final InsufficientPermissionException e) { @@ -367,10 +369,10 @@ public class ArtifactManagementTest extends AbstractIntegrationTestWithMongoDB { @Test @Description("Searches an artifact through the relations of a software module.") public void findLocalArtifactBySoftwareModule() { - SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null); + SoftwareModule sm = new JpaSoftwareModule(osType, "name 1", "version 1", null, null); sm = softwareManagement.createSoftwareModule(sm); - SoftwareModule sm2 = new SoftwareModule(osType, "name 2", "version 2", null, null); + SoftwareModule sm2 = new JpaSoftwareModule(osType, "name 2", "version 2", null, null); sm2 = softwareManagement.createSoftwareModule(sm2); assertThat(artifactManagement.findLocalArtifactBySoftwareModule(pageReq, sm.getId())).isEmpty(); @@ -384,7 +386,7 @@ public class ArtifactManagementTest extends AbstractIntegrationTestWithMongoDB { @Test @Description("Searches an artifact through the relations of a software module and the filename.") public void findByFilenameAndSoftwareModule() { - SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null); + SoftwareModule sm = new JpaSoftwareModule(osType, "name 1", "version 1", null, null); sm = softwareManagement.createSoftwareModule(sm); assertThat(artifactManagement.findByFilenameAndSoftwareModule("file1", sm.getId())).isEmpty(); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ControllerManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ControllerManagementTest.java similarity index 80% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ControllerManagementTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ControllerManagementTest.java index 279932ef7..f33c5c170 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ControllerManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ControllerManagementTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import static org.fest.assertions.api.Assertions.assertThat; import static org.junit.Assert.fail; @@ -17,8 +17,8 @@ import java.util.List; import javax.validation.ConstraintViolationException; import org.apache.commons.lang3.RandomStringUtils; -import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.TestDataUtil; +import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.ActionStatus; @@ -33,14 +33,13 @@ import ru.yandex.qatools.allure.annotations.Stories; @Features("Component Tests - Repository") @Stories("Controller Management") -public class ControllerManagementTest extends AbstractIntegrationTest { +public class ControllerManagementTest extends AbstractJpaIntegrationTest { @Test @Description("Controller adds a new action status.") public void controllerAddsActionStatus() { - final Target target = new Target("4712"); - final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement, - distributionSetManagement); + final Target target = new JpaTarget("4712"); + final DistributionSet ds = testdataFactory.createDistributionSet(""); Target savedTarget = targetManagement.createTarget(target); final List toAssign = new ArrayList<>(); @@ -54,23 +53,23 @@ public class ControllerManagementTest extends AbstractIntegrationTest { assertThat(targetManagement.findTargetByControllerID(savedTarget.getControllerId()).getTargetInfo() .getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); - ActionStatus actionStatusMessage = new ActionStatus(savedAction, Action.Status.RUNNING, + ActionStatus actionStatusMessage = new JpaActionStatus(savedAction, Action.Status.RUNNING, System.currentTimeMillis()); actionStatusMessage.addMessage("foobar"); savedAction.setStatus(Status.RUNNING); - controllerManagament.addUpdateActionStatus(actionStatusMessage, savedAction); + controllerManagament.addUpdateActionStatus(actionStatusMessage); assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) .isEqualTo(TargetUpdateStatus.PENDING); - actionStatusMessage = new ActionStatus(savedAction, Action.Status.FINISHED, System.currentTimeMillis()); + actionStatusMessage = new JpaActionStatus(savedAction, Action.Status.FINISHED, System.currentTimeMillis()); actionStatusMessage.addMessage(RandomStringUtils.randomAscii(512)); savedAction.setStatus(Status.FINISHED); - controllerManagament.addUpdateActionStatus(actionStatusMessage, savedAction); + controllerManagament.addUpdateActionStatus(actionStatusMessage); assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) .isEqualTo(TargetUpdateStatus.IN_SYNC); assertThat(actionStatusRepository.findAll(pageReq).getNumberOfElements()).isEqualTo(3); - assertThat(deploymentManagement.findActionStatusByAction(pageReq, savedAction, false).getNumberOfElements()) + assertThat(deploymentManagement.findActionStatusByAction(pageReq, savedAction).getNumberOfElements()) .isEqualTo(3); } @@ -98,9 +97,8 @@ public class ControllerManagementTest extends AbstractIntegrationTest { public void tryToFinishUpdateProcessMoreThenOnce() { // mock - final Target target = new Target("Rabbit"); - final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement, - distributionSetManagement); + final Target target = new JpaTarget("Rabbit"); + final DistributionSet ds = testdataFactory.createDistributionSet(""); Target savedTarget = targetManagement.createTarget(target); final List toAssign = new ArrayList<>(); toAssign.add(savedTarget); @@ -108,24 +106,24 @@ public class ControllerManagementTest extends AbstractIntegrationTest { Action savedAction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0); // test and verify - final ActionStatus actionStatusMessage = new ActionStatus(savedAction, Action.Status.RUNNING, + final ActionStatus actionStatusMessage = new JpaActionStatus(savedAction, Action.Status.RUNNING, System.currentTimeMillis()); actionStatusMessage.addMessage("running"); - savedAction = controllerManagament.addUpdateActionStatus(actionStatusMessage, savedAction); + savedAction = controllerManagament.addUpdateActionStatus(actionStatusMessage); assertThat(targetManagement.findTargetByControllerID("Rabbit").getTargetInfo().getUpdateStatus()) .isEqualTo(TargetUpdateStatus.PENDING); - final ActionStatus actionStatusMessage2 = new ActionStatus(savedAction, Action.Status.ERROR, + final ActionStatus actionStatusMessage2 = new JpaActionStatus(savedAction, Action.Status.ERROR, System.currentTimeMillis()); actionStatusMessage2.addMessage("error"); - savedAction = controllerManagament.addUpdateActionStatus(actionStatusMessage2, savedAction); + savedAction = controllerManagament.addUpdateActionStatus(actionStatusMessage2); assertThat(targetManagement.findTargetByControllerID("Rabbit").getTargetInfo().getUpdateStatus()) .isEqualTo(TargetUpdateStatus.ERROR); - final ActionStatus actionStatusMessage3 = new ActionStatus(savedAction, Action.Status.FINISHED, + final ActionStatus actionStatusMessage3 = new JpaActionStatus(savedAction, Action.Status.FINISHED, System.currentTimeMillis()); actionStatusMessage3.addMessage("finish"); - controllerManagament.addUpdateActionStatus(actionStatusMessage3, savedAction); + controllerManagament.addUpdateActionStatus(actionStatusMessage3); targetManagement.findTargetByControllerID("Rabbit").getTargetInfo().getUpdateStatus(); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/DeploymentManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DeploymentManagementTest.java similarity index 84% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/DeploymentManagementTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DeploymentManagementTest.java index a17054a3d..565513107 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/DeploymentManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DeploymentManagementTest.java @@ -6,13 +6,14 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import static org.fest.assertions.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; @@ -20,13 +21,20 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; -import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.Constants; -import org.eclipse.hawkbit.TestDataUtil; import org.eclipse.hawkbit.eventbus.event.CancelTargetAssignmentEvent; -import org.eclipse.hawkbit.eventbus.event.TargetAssignDistributionSetEvent; +import org.eclipse.hawkbit.repository.ActionStatusFields; +import org.eclipse.hawkbit.repository.DistributionSetAssignmentResult; +import org.eclipse.hawkbit.repository.eventbus.event.TargetAssignDistributionSetEvent; import org.eclipse.hawkbit.repository.exception.ForceQuitActionNotAllowedException; import org.eclipse.hawkbit.repository.exception.IncompleteDistributionSetException; +import org.eclipse.hawkbit.repository.jpa.configuration.Constants; +import org.eclipse.hawkbit.repository.jpa.model.JpaAction; +import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; +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; @@ -59,7 +67,7 @@ import ru.yandex.qatools.allure.annotations.Stories; */ @Features("Component Tests - Repository") @Stories("Deployment Management") -public class DeploymentManagementTest extends AbstractIntegrationTest { +public class DeploymentManagementTest extends AbstractJpaIntegrationTest { @Autowired private EventBus eventBus; @@ -67,9 +75,9 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { @Test @Description("Test verifies that the repistory retrieves the action including all defined (lazy) details.") public void findActionWithLazyDetails() { - final DistributionSet testDs = TestDataUtil.generateDistributionSet("TestDs", "1.0", softwareManagement, - distributionSetManagement, new ArrayList()); - final List testTarget = targetManagement.createTargets(TestDataUtil.generateTargets(1)); + final DistributionSet testDs = testdataFactory.createDistributionSet("TestDs", "1.0", + new ArrayList()); + final List testTarget = testdataFactory.createTargets(1); // one action with one action status is generated final Long actionId = deploymentManagement.assignDistributionSet(testDs, testTarget).getActions().get(0); final Action action = deploymentManagement.findActionWithDetails(actionId); @@ -83,15 +91,15 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { @Test @Description("Test verifies that the custom query to find all actions include the count of action status is working correctly") public void findActionsWithStatusCountByTarget() { - final DistributionSet testDs = TestDataUtil.generateDistributionSet("TestDs", "1.0", softwareManagement, - distributionSetManagement, new ArrayList()); - final List testTarget = targetManagement.createTargets(TestDataUtil.generateTargets(1)); + final DistributionSet testDs = testdataFactory.createDistributionSet("TestDs", "1.0", + new ArrayList()); + final List testTarget = testdataFactory.createTargets(1); // one action with one action status is generated final Action action = deploymentManagement.findActionWithDetails( deploymentManagement.assignDistributionSet(testDs, testTarget).getActions().get(0)); // save 2 action status - actionStatusRepository.save(new ActionStatus(action, Status.RETRIEVED, System.currentTimeMillis())); - actionStatusRepository.save(new ActionStatus(action, Status.RUNNING, System.currentTimeMillis())); + actionStatusRepository.save(new JpaActionStatus(action, Status.RETRIEVED, System.currentTimeMillis())); + actionStatusRepository.save(new JpaActionStatus(action, Status.RUNNING, System.currentTimeMillis())); final List findActionsWithStatusCountByTarget = deploymentManagement .findActionsWithStatusCountByTargetOrderByIdDesc(testTarget.get(0)); @@ -104,14 +112,14 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { @Test @Description("Ensures that distribution sets can assigned and unassigned to a distribution set tag. Not exists distribution set will be ignored for the assignment.") public void assignAndUnassignDistributionSetToTag() { - final List assignDS = new ArrayList(); + final List assignDS = new ArrayList<>(); for (int i = 0; i < 4; i++) { - assignDS.add(TestDataUtil.generateDistributionSet("DS" + i, "1.0", softwareManagement, - distributionSetManagement, new ArrayList()).getId()); + assignDS.add(testdataFactory.createDistributionSet("DS" + i, "1.0", new ArrayList()) + .getId()); } // not exists assignDS.add(Long.valueOf(100)); - final DistributionSetTag tag = tagManagement.createDistributionSetTag(new DistributionSetTag("Tag1")); + final DistributionSetTag tag = tagManagement.createDistributionSetTag(new JpaDistributionSetTag("Tag1")); final List assignedDS = distributionSetManagement.assignTag(assignDS, tag); assertThat(assignedDS.size()).as("assigned ds has wrong size").isEqualTo(4); @@ -146,14 +154,13 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { @Description("Test verifies that an assignment with automatic cancelation works correctly even if the update is split into multiple partitions on the database.") public void multiAssigmentHistoryOverMultiplePagesResultsInTwoActiveAction() { - final DistributionSet cancelDs = TestDataUtil.generateDistributionSet("Canceled DS", "1.0", softwareManagement, - distributionSetManagement, new ArrayList()); + final DistributionSet cancelDs = testdataFactory.createDistributionSet("Canceled DS", "1.0", + new ArrayList()); - final DistributionSet cancelDs2 = TestDataUtil.generateDistributionSet("Canceled DS", "1.2", softwareManagement, - distributionSetManagement, new ArrayList()); + final DistributionSet cancelDs2 = testdataFactory.createDistributionSet("Canceled DS", "1.2", + new ArrayList()); - List targets = targetManagement - .createTargets(TestDataUtil.generateTargets(Constants.MAX_ENTRIES_IN_STATEMENT + 10)); + List targets = testdataFactory.createTargets(Constants.MAX_ENTRIES_IN_STATEMENT + 10); targets = deploymentManagement.assignDistributionSet(cancelDs, targets).getAssignedEntity(); targets = deploymentManagement.assignDistributionSet(cancelDs2, targets).getAssignedEntity(); @@ -170,17 +177,14 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { + "actions after canceling the second active action the first one is still running as it is not touched by the cancelation. After canceling the first one " + "also the target goes back to IN_SYNC as no open action is left.") public void manualCancelWithMultipleAssignmentsCancelLastOneFirst() { - Target target = new Target("4712"); - final DistributionSet dsFirst = TestDataUtil.generateDistributionSet("", softwareManagement, - distributionSetManagement, true); + JpaTarget target = new JpaTarget("4712"); + final DistributionSet dsFirst = testdataFactory.createDistributionSet("", true); dsFirst.setRequiredMigrationStep(true); - final DistributionSet dsSecond = TestDataUtil.generateDistributionSet("2", softwareManagement, - distributionSetManagement, true); - final DistributionSet dsInstalled = TestDataUtil.generateDistributionSet("installed", softwareManagement, - distributionSetManagement, true); + final DistributionSet dsSecond = testdataFactory.createDistributionSet("2", true); + final DistributionSet dsInstalled = testdataFactory.createDistributionSet("installed", true); - target.getTargetInfo().setInstalledDistributionSet(dsInstalled); - target = targetManagement.createTarget(target); + ((JpaTargetInfo) target.getTargetInfo()).setInstalledDistributionSet((JpaDistributionSet) dsInstalled); + target = (JpaTarget) targetManagement.createTarget(target); // check initial status assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) @@ -199,8 +203,8 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { secondAction = deploymentManagement.findActionWithDetails(secondAction.getId()); // confirm cancellation secondAction.setStatus(Status.CANCELED); - controllerManagement.addCancelActionStatus( - new ActionStatus(secondAction, Status.CANCELED, System.currentTimeMillis()), secondAction); + controllerManagement + .addCancelActionStatus(new JpaActionStatus(secondAction, Status.CANCELED, System.currentTimeMillis())); assertThat(actionStatusRepository.findAll()).as("wrong size of actions status").hasSize(4); assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet()).as("wrong ds") .isEqualTo(dsFirst); @@ -213,8 +217,8 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { firstAction = deploymentManagement.findActionWithDetails(firstAction.getId()); // confirm cancellation firstAction.setStatus(Status.CANCELED); - controllerManagement.addCancelActionStatus( - new ActionStatus(firstAction, Status.CANCELED, System.currentTimeMillis()), firstAction); + controllerManagement + .addCancelActionStatus(new JpaActionStatus(firstAction, Status.CANCELED, System.currentTimeMillis())); assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(6); assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet()) .as("wrong assigned ds").isEqualTo(dsInstalled); @@ -227,17 +231,14 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { + "actions after canceling the first active action the system switched to second one. After canceling this one " + "also the target goes back to IN_SYNC as no open action is left.") public void manualCancelWithMultipleAssignmentsCancelMiddleOneFirst() { - Target target = new Target("4712"); - final DistributionSet dsFirst = TestDataUtil.generateDistributionSet("", softwareManagement, - distributionSetManagement, true); + JpaTarget target = new JpaTarget("4712"); + final DistributionSet dsFirst = testdataFactory.createDistributionSet("", true); dsFirst.setRequiredMigrationStep(true); - final DistributionSet dsSecond = TestDataUtil.generateDistributionSet("2", softwareManagement, - distributionSetManagement, true); - final DistributionSet dsInstalled = TestDataUtil.generateDistributionSet("installed", softwareManagement, - distributionSetManagement, true); + final DistributionSet dsSecond = testdataFactory.createDistributionSet("2", true); + final DistributionSet dsInstalled = testdataFactory.createDistributionSet("installed", true); - target.getTargetInfo().setInstalledDistributionSet(dsInstalled); - target = targetManagement.createTarget(target); + ((JpaTargetInfo) target.getTargetInfo()).setInstalledDistributionSet((JpaDistributionSet) dsInstalled); + target = (JpaTarget) targetManagement.createTarget(target); // check initial status assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) @@ -256,8 +257,8 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { // confirm cancellation firstAction = deploymentManagement.findActionWithDetails(firstAction.getId()); firstAction.setStatus(Status.CANCELED); - controllerManagement.addCancelActionStatus( - new ActionStatus(firstAction, Status.CANCELED, System.currentTimeMillis()), firstAction); + controllerManagement + .addCancelActionStatus(new JpaActionStatus(firstAction, Status.CANCELED, System.currentTimeMillis())); assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(4); assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet()) .as("wrong assigned ds").isEqualTo(dsSecond); @@ -273,8 +274,8 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { .as("wrong assigned ds").isEqualTo(dsSecond); // confirm cancellation secondAction.setStatus(Status.CANCELED); - controllerManagement.addCancelActionStatus( - new ActionStatus(secondAction, Status.CANCELED, System.currentTimeMillis()), secondAction); + controllerManagement + .addCancelActionStatus(new JpaActionStatus(secondAction, Status.CANCELED, System.currentTimeMillis())); // cancelled success -> back to dsInstalled assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet()) .as("wrong installed ds").isEqualTo(dsInstalled); @@ -286,15 +287,13 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { @Description("Force Quit an Assignment. Expected behaviour is that the action is canceled and is marked as deleted. The assigned Software module") public void forceQuitSetActionToInactive() throws InterruptedException { - Target target = new Target("4712"); - final DistributionSet dsInstalled = TestDataUtil.generateDistributionSet("installed", softwareManagement, - distributionSetManagement, true); - target.getTargetInfo().setInstalledDistributionSet(dsInstalled); - target = targetManagement.createTarget(target); + JpaTarget target = new JpaTarget("4712"); + final DistributionSet dsInstalled = testdataFactory.createDistributionSet("installed", true); + ((JpaTargetInfo) target.getTargetInfo()).setInstalledDistributionSet((JpaDistributionSet) dsInstalled); + target = (JpaTarget) targetManagement.createTarget(target); - final DistributionSet ds = TestDataUtil - .generateDistributionSet("newDS", softwareManagement, distributionSetManagement, true) - .setRequiredMigrationStep(true); + final DistributionSet ds = testdataFactory.createDistributionSet("newDS", true); + ds.setRequiredMigrationStep(true); // verify initial status assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) @@ -306,7 +305,7 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { assertThat(actionRepository.findAll()).as("wrong size of action").hasSize(1); assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(1); - target = targetManagement.findTargetByControllerID(target.getControllerId()); + target = (JpaTarget) targetManagement.findTargetByControllerID(target.getControllerId()); // force quit assignment deploymentManagement.cancelAction(assigningAction, target); @@ -328,15 +327,13 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { @Description("Force Quit an not canceled Assignment. Expected behaviour is that the action can not be force quit and there is thrown an exception.") public void forceQuitNotAllowedThrowsException() { - Target target = new Target("4712"); - final DistributionSet dsInstalled = TestDataUtil.generateDistributionSet("installed", softwareManagement, - distributionSetManagement, true); - target.getTargetInfo().setInstalledDistributionSet(dsInstalled); + Target target = new JpaTarget("4712"); + final DistributionSet dsInstalled = testdataFactory.createDistributionSet("installed", true); + ((JpaTargetInfo) target.getTargetInfo()).setInstalledDistributionSet((JpaDistributionSet) dsInstalled); target = targetManagement.createTarget(target); - final DistributionSet ds = TestDataUtil - .generateDistributionSet("newDS", softwareManagement, distributionSetManagement, true) - .setRequiredMigrationStep(true); + final DistributionSet ds = testdataFactory.createDistributionSet("newDS", true); + ds.setRequiredMigrationStep(true); // verify initial status assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) @@ -363,7 +360,9 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { .as("wrong update status").isEqualTo(TargetUpdateStatus.PENDING); assertThat(targetManagement.findTargetByControllerID(target.getControllerId()).getAssignedDistributionSet()) .as("wrong assigned ds").isEqualTo(ds); - final Action action = actionRepository.findByTargetAndDistributionSet(pageReq, target, ds).getContent().get(0); + final Action action = actionRepository + .findByTargetAndDistributionSet(pageReq, (JpaTarget) target, (JpaDistributionSet) ds).getContent() + .get(0); assertThat(action).as("action should not be null").isNotNull(); return action; } @@ -384,14 +383,13 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { final String myCtrlIDPref = "myCtrlID"; final Iterable savedNakedTargets = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(10, myCtrlIDPref, "first description")); + .createTargets(testdataFactory.generateTargets(10, myCtrlIDPref, "first description")); final String myDeployedCtrlIDPref = "myDeployedCtrlID"; List savedDeployedTargets = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(20, myDeployedCtrlIDPref, "first description")); + .createTargets(testdataFactory.generateTargets(20, myDeployedCtrlIDPref, "first description")); - final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement, - distributionSetManagement); + final DistributionSet ds = testdataFactory.createDistributionSet(""); deploymentManagement.assignDistributionSet(ds, savedDeployedTargets); @@ -438,17 +436,17 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { final EventHandlerMock eventHandlerMock = new EventHandlerMock(0); eventBus.register(eventHandlerMock); - final List targets = targetManagement.createTargets(TestDataUtil.generateTargets(10)); + final List targets = testdataFactory.createTargets(10); final SoftwareModule ah = softwareManagement - .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); final SoftwareModule jvm = softwareManagement - .createSoftwareModule(new SoftwareModule(runtimeType, "oracle-jre", "1.7.2", null, "")); + .createSoftwareModule(new JpaSoftwareModule(runtimeType, "oracle-jre", "1.7.2", null, "")); final SoftwareModule os = softwareManagement - .createSoftwareModule(new SoftwareModule(osType, "poky", "3.0.2", null, "")); + .createSoftwareModule(new JpaSoftwareModule(osType, "poky", "3.0.2", null, "")); final DistributionSet incomplete = distributionSetManagement.createDistributionSet( - new DistributionSet("incomplete", "v1", "", standardDsType, Lists.newArrayList(ah, jvm))); + new JpaDistributionSet("incomplete", "v1", "", standardDsType, Lists.newArrayList(ah, jvm))); try { deploymentManagement.assignDistributionSet(incomplete, targets); @@ -502,11 +500,11 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { final List deployedTargetIDs = deploymentResult.getDeployedTargetIDs(); final List undeployedTargetIDs = deploymentResult.getUndeployedTargetIDs(); - final List savedNakedTargets = deploymentResult.getUndeployedTargets(); - final List savedDeployedTargets = deploymentResult.getDeployedTargets(); + final Collection savedNakedTargets = (Collection) deploymentResult.getUndeployedTargets(); + final Collection savedDeployedTargets = (Collection) deploymentResult.getDeployedTargets(); // retrieving all Actions created by the assignDistributionSet call - final Page page = actionRepository.findAll(pageReq); + final Page page = actionRepository.findAll(pageReq); // and verify the number assertThat(page.getTotalElements()).as("wrong size of actions") .isEqualTo(noOfDeployedTargets * noOfDistributionSets); @@ -514,10 +512,10 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { // only records retrieved from the DB can be evaluated to be sure that // all fields are // populated; - final Iterable allFoundTargets = targetRepository.findAll(); + final Iterable allFoundTargets = targetRepository.findAll(); - final Iterable deployedTargetsFromDB = targetRepository.findAll(deployedTargetIDs); - final Iterable undeployedTargetsFromDB = targetRepository.findAll(undeployedTargetIDs); + final Iterable deployedTargetsFromDB = targetRepository.findAll(deployedTargetIDs); + final Iterable undeployedTargetsFromDB = targetRepository.findAll(undeployedTargetIDs); // test that number of Targets assertThat(allFoundTargets.spliterator().getExactSizeIfKnown()).as("number of target is wrong") @@ -532,9 +530,9 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { assertThat(allFoundTargets).as("content of founded target is wrong").containsAll(deployedTargetsFromDB) .containsAll(undeployedTargetsFromDB); assertThat(deployedTargetsFromDB).as("content of deployed target is wrong").containsAll(savedDeployedTargets) - .doesNotContain(Iterables.toArray(undeployedTargetsFromDB, Target.class)); + .doesNotContain(Iterables.toArray(undeployedTargetsFromDB, JpaTarget.class)); assertThat(undeployedTargetsFromDB).as("content of undeployed target is wrong").containsAll(savedNakedTargets) - .doesNotContain(Iterables.toArray(deployedTargetsFromDB, Target.class)); + .doesNotContain(Iterables.toArray(deployedTargetsFromDB, JpaTarget.class)); // For each of the 4 targets 1 distribution sets gets assigned eventHandlerMock.getEvents(10, TimeUnit.SECONDS); @@ -556,9 +554,9 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { final DeploymentResult deployResWithDsC = prepareComplexRepo("undep-C-T", 4, "dep-C-T", 6, 1, "dsC"); // keep a reference to the created DistributionSets - final DistributionSet dsA = deployResWithDsA.getDistributionSets().get(0); - final DistributionSet dsB = deployResWithDsB.getDistributionSets().get(0); - final DistributionSet dsC = deployResWithDsC.getDistributionSets().get(0); + final JpaDistributionSet dsA = (JpaDistributionSet) deployResWithDsA.getDistributionSets().get(0); + final JpaDistributionSet dsB = (JpaDistributionSet) deployResWithDsB.getDistributionSets().get(0); + final JpaDistributionSet dsC = (JpaDistributionSet) deployResWithDsC.getDistributionSets().get(0); // retrieving the UpdateActions created by the assignments actionRepository.findByDistributionSet(pageRequest, dsA).getContent().get(0); @@ -649,7 +647,7 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { final DeploymentResult deploymentResult = prepareComplexRepo(undeployedTargetPrefix, noOfUndeployedTargets, deployedTargetPrefix, noOfDeployedTargets, noOfDistributionSets, "myTestDS"); - DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement, distributionSetManagement); + DistributionSet dsA = testdataFactory.createDistributionSet(""); distributionSetManagement.deleteDistributionSet(dsA.getId()); dsA = distributionSetManagement.findDistributionSetById(dsA.getId()); @@ -664,10 +662,11 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { } // verify that deleted attribute is used correctly - List allFoundDS = distributionSetManagement.findDistributionSetsAll(pageReq, false, true) - .getContent(); + List allFoundDS = distributionSetManagement + .findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true).getContent(); assertThat(allFoundDS.size()).as("no ds should be founded").isEqualTo(0); - allFoundDS = distributionSetManagement.findDistributionSetsAll(pageRequest, true, true).getContent(); + allFoundDS = distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageRequest, true, true) + .getContent(); assertThat(allFoundDS).as("wrong size of founded ds").hasSize(noOfDistributionSets); for (final DistributionSet ds : deploymentResult.getDistributionSets()) { @@ -681,9 +680,11 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { // has been installed // successfully and no activeAction is referring to created distribution // sets - allFoundDS = distributionSetManagement.findDistributionSetsAll(pageRequest, false, true).getContent(); + allFoundDS = distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageRequest, false, true) + .getContent(); assertThat(allFoundDS.size()).as("no ds should be founded").isEqualTo(0); - allFoundDS = distributionSetManagement.findDistributionSetsAll(pageRequest, true, true).getContent(); + allFoundDS = distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageRequest, true, true) + .getContent(); assertThat(allFoundDS).as("size of founded ds is wrong").hasSize(noOfDistributionSets); } @@ -721,9 +722,9 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { private List sendUpdateActionStatusToTargets(final DistributionSet dsA, final Iterable targs, final Status status, final String... msgs) { - final List result = new ArrayList(); + final List result = new ArrayList<>(); for (final Target t : targs) { - final List findByTarget = actionRepository.findByTarget(t); + final List findByTarget = actionRepository.findByTarget((JpaTarget) t); for (final Action action : findByTarget) { result.add(sendUpdateActionStatusToTarget(status, action, t, msgs)); } @@ -735,14 +736,14 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { final String... msgs) { updActA.setStatus(status); - final ActionStatus statusMessages = new ActionStatus(); + final ActionStatus statusMessages = new JpaActionStatus(); statusMessages.setAction(updActA); statusMessages.setOccurredAt(System.currentTimeMillis()); statusMessages.setStatus(status); for (final String msg : msgs) { statusMessages.addMessage(msg); } - controllerManagament.addUpdateActionStatus(statusMessages, updActA); + controllerManagament.addUpdateActionStatus(statusMessages); return targetManagement.findTargetByControllerID(t.getControllerId()); } @@ -750,14 +751,11 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { @Description("Testing if changing target and the status without refreshing the entities from the DB (e.g. concurrent changes from UI and from controller) works") public void alternatingAssignmentAndAddUpdateActionStatus() { - final DistributionSet dsA = TestDataUtil.generateDistributionSet("a", softwareManagement, - distributionSetManagement); - final DistributionSet dsB = TestDataUtil.generateDistributionSet("b", softwareManagement, - distributionSetManagement); - Target targ = targetManagement - .createTarget(TestDataUtil.buildTargetFixture("target-id-A", "first description")); + final DistributionSet dsA = testdataFactory.createDistributionSet("a"); + final DistributionSet dsB = testdataFactory.createDistributionSet("b"); + Target targ = targetManagement.createTarget(testdataFactory.generateTarget("target-id-A", "first description")); - List targs = new ArrayList(); + List targs = new ArrayList<>(); targs.add(targ); // doing the assignment @@ -782,11 +780,12 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { assertThat(deploymentManagement.findActiveActionsByTarget(targ).get(0).getDistributionSet()) .as("Installed distribution set of action should be null").isNotNull(); - final Page updAct = actionRepository.findByDistributionSet(pageReq, dsA); + final Page updAct = actionRepository.findByDistributionSet(pageReq, (JpaDistributionSet) dsA); final Action action = updAct.getContent().get(0); action.setStatus(Status.FINISHED); - final ActionStatus statusMessage = new ActionStatus(action, Status.FINISHED, System.currentTimeMillis(), ""); - controllerManagament.addUpdateActionStatus(statusMessage, action); + final ActionStatus statusMessage = new JpaActionStatus((JpaAction) action, Status.FINISHED, + System.currentTimeMillis(), ""); + controllerManagament.addUpdateActionStatus(statusMessage); targ = targetManagement.findTargetByControllerID(targ.getControllerId()); @@ -819,11 +818,9 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { @Description("The test verfies that the DS itself is not changed because of an target assignment" + " which is a relationship but not a changed on the entity itself..") public void checkThatDsRevisionsIsNotChangedWithTargetAssignment() { - final DistributionSet dsA = TestDataUtil.generateDistributionSet("a", softwareManagement, - distributionSetManagement); - TestDataUtil.generateDistributionSet("b", softwareManagement, distributionSetManagement); - Target targ = targetManagement - .createTarget(TestDataUtil.buildTargetFixture("target-id-A", "first description")); + final DistributionSet dsA = testdataFactory.createDistributionSet("a"); + testdataFactory.createDistributionSet("b"); + Target targ = targetManagement.createTarget(testdataFactory.generateTarget("target-id-A", "first description")); assertThat(dsA.getOptLockRevision()).as("lock revision is wrong").isEqualTo( distributionSetManagement.findDistributionSetByIdWithDetails(dsA.getId()).getOptLockRevision()); @@ -841,12 +838,12 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { @Description("Tests the switch from a soft to hard update by API") public void forceSoftAction() { // prepare - final Target target = targetManagement.createTarget(new Target("knownControllerId")); - final DistributionSet ds = TestDataUtil.generateDistributionSet("a", softwareManagement, - distributionSetManagement); + final Target target = targetManagement.createTarget(new JpaTarget("knownControllerId")); + final DistributionSet ds = testdataFactory.createDistributionSet("a"); // assign ds to create an action - final DistributionSetAssignmentResult assignDistributionSet = deploymentManagement - .assignDistributionSet(ds.getId(), ActionType.SOFT, Action.NO_FORCE_TIME, target.getControllerId()); + final DistributionSetAssignmentResult assignDistributionSet = deploymentManagement.assignDistributionSet( + ds.getId(), ActionType.SOFT, org.eclipse.hawkbit.repository.model.RepositoryModelConstants.NO_FORCE_TIME, + target.getControllerId()); final Action action = deploymentManagement.findActionWithDetails(assignDistributionSet.getActions().get(0)); // verify preparation Action findAction = deploymentManagement.findAction(action.getId()); @@ -864,12 +861,12 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { @Description("Tests the switch from a hard to hard update by API, e.g. which in fact should not change anything.") public void forceAlreadyForcedActionNothingChanges() { // prepare - final Target target = targetManagement.createTarget(new Target("knownControllerId")); - final DistributionSet ds = TestDataUtil.generateDistributionSet("a", softwareManagement, - distributionSetManagement); + final Target target = targetManagement.createTarget(new JpaTarget("knownControllerId")); + final DistributionSet ds = testdataFactory.createDistributionSet("a"); // assign ds to create an action - final DistributionSetAssignmentResult assignDistributionSet = deploymentManagement - .assignDistributionSet(ds.getId(), ActionType.FORCED, Action.NO_FORCE_TIME, target.getControllerId()); + final DistributionSetAssignmentResult assignDistributionSet = deploymentManagement.assignDistributionSet( + ds.getId(), ActionType.FORCED, org.eclipse.hawkbit.repository.model.RepositoryModelConstants.NO_FORCE_TIME, + target.getControllerId()); final Action action = deploymentManagement.findActionWithDetails(assignDistributionSet.getActions().get(0)); // verify perparation Action findAction = deploymentManagement.findAction(action.getId()); @@ -912,14 +909,14 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { final String deployedTargetPrefix, final int noOfDeployedTargets, final int noOfDistributionSets, final String distributionSetPrefix) { final Iterable nakedTargets = targetManagement.createTargets( - TestDataUtil.buildTargetFixtures(noOfUndeployedTargets, undeployedTargetPrefix, "first description")); + testdataFactory.generateTargets(noOfUndeployedTargets, undeployedTargetPrefix, "first description")); List deployedTargets = targetManagement.createTargets( - TestDataUtil.buildTargetFixtures(noOfDeployedTargets, deployedTargetPrefix, "first description")); + testdataFactory.generateTargets(noOfDeployedTargets, deployedTargetPrefix, "first description")); // creating 10 DistributionSets - final List dsList = TestDataUtil.generateDistributionSets(distributionSetPrefix, - noOfDistributionSets, softwareManagement, distributionSetManagement); + final Collection dsList = testdataFactory.createDistributionSets(distributionSetPrefix, + noOfDistributionSets); String time = String.valueOf(System.currentTimeMillis()); time = time.substring(time.length() - 5); @@ -1048,8 +1045,7 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { public List getEvents(final long timeout, final TimeUnit unit) throws InterruptedException { latch.await(timeout, unit); - final List handledEvents = new LinkedList( - events); + final List handledEvents = new LinkedList<>(events); assertThat(handledEvents).as("Did not receive the expected amount of events (" + expectedNumberOfEvents + ") within timeout. Received events are " + handledEvents).hasSize(expectedNumberOfEvents); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/DistributionSetManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DistributionSetManagementTest.java similarity index 82% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/DistributionSetManagementTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DistributionSetManagementTest.java index db9618425..d26474bb4 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/DistributionSetManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DistributionSetManagementTest.java @@ -6,33 +6,40 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import static org.fest.assertions.api.Assertions.assertThat; import static org.junit.Assert.fail; import java.util.ArrayList; +import java.util.Collection; import java.util.Iterator; import java.util.List; -import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.TestDataUtil; -import org.eclipse.hawkbit.WithUser; -import org.eclipse.hawkbit.repository.DistributionSetFilter.DistributionSetFilterBuilder; +import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.exception.DistributionSetTypeUndefinedException; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; import org.eclipse.hawkbit.repository.exception.EntityLockedException; import org.eclipse.hawkbit.repository.exception.EntityReadOnlyException; import org.eclipse.hawkbit.repository.exception.UnsupportedSoftwareModuleForThisDistributionSetException; +import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetMetadata; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; 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.DistributionSetFilter.DistributionSetFilterBuilder; 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.SoftwareModule; import org.eclipse.hawkbit.repository.model.Target; +import org.eclipse.hawkbit.repository.util.WithUser; import org.fest.assertions.core.Condition; import org.junit.Test; import org.springframework.data.domain.Page; @@ -50,13 +57,13 @@ import ru.yandex.qatools.allure.annotations.Stories; */ @Features("Component Tests - Repository") @Stories("DistributionSet Management") -public class DistributionSetManagementTest extends AbstractIntegrationTest { +public class DistributionSetManagementTest extends AbstractJpaIntegrationTest { @Test @Description("Tests the successfull module update of unused distribution set type which is in fact allowed.") public void updateUnassignedDistributionSetTypeModules() { DistributionSetType updatableType = distributionSetManagement - .createDistributionSetType(new DistributionSetType("updatableType", "to be deleted", "")); + .createDistributionSetType(new JpaDistributionSetType("updatableType", "to be deleted", "")); assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes()) .isEmpty(); @@ -83,11 +90,11 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { @Description("Tests the successfull update of used distribution set type meta data hich is in fact allowed.") public void updateAssignedDistributionSetTypeMetaData() { final DistributionSetType nonUpdatableType = distributionSetManagement - .createDistributionSetType(new DistributionSetType("updatableType", "to be deletd", "")); + .createDistributionSetType(new JpaDistributionSetType("updatableType", "to be deletd", "")); assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes()) .isEmpty(); distributionSetManagement - .createDistributionSet(new DistributionSet("newtypesoft", "1", "", nonUpdatableType, null)); + .createDistributionSet(new JpaDistributionSet("newtypesoft", "1", "", nonUpdatableType, null)); nonUpdatableType.setDescription("a new description"); nonUpdatableType.setColour("test123"); @@ -104,11 +111,11 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { @Description("Tests the unsuccessfull update of used distribution set type (module addition).") public void addModuleToAssignedDistributionSetTypeFails() { final DistributionSetType nonUpdatableType = distributionSetManagement - .createDistributionSetType(new DistributionSetType("updatableType", "to be deletd", "")); + .createDistributionSetType(new JpaDistributionSetType("updatableType", "to be deletd", "")); assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes()) .isEmpty(); distributionSetManagement - .createDistributionSet(new DistributionSet("newtypesoft", "1", "", nonUpdatableType, null)); + .createDistributionSet(new JpaDistributionSet("newtypesoft", "1", "", nonUpdatableType, null)); nonUpdatableType.addMandatoryModuleType(osType); @@ -125,14 +132,14 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { @Description("Tests the unsuccessfull update of used distribution set type (module removal).") public void removeModuleToAssignedDistributionSetTypeFails() { DistributionSetType nonUpdatableType = distributionSetManagement - .createDistributionSetType(new DistributionSetType("updatableType", "to be deletd", "")); + .createDistributionSetType(new JpaDistributionSetType("updatableType", "to be deletd", "")); assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes()) .isEmpty(); nonUpdatableType.addMandatoryModuleType(osType); nonUpdatableType = distributionSetManagement.updateDistributionSetType(nonUpdatableType); distributionSetManagement - .createDistributionSet(new DistributionSet("newtypesoft", "1", "", nonUpdatableType, null)); + .createDistributionSet(new JpaDistributionSet("newtypesoft", "1", "", nonUpdatableType, null)); nonUpdatableType.removeModuleType(osType.getId()); try { @@ -146,8 +153,8 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { @Test @Description("Tests the successfull deletion of unused (hard delete) distribution set types.") public void deleteUnassignedDistributionSetType() { - final DistributionSetType hardDelete = distributionSetManagement - .createDistributionSetType(new DistributionSetType("deleted", "to be deleted", "")); + final JpaDistributionSetType hardDelete = (JpaDistributionSetType) distributionSetManagement + .createDistributionSetType(new JpaDistributionSetType("deleted", "to be deleted", "")); assertThat(distributionSetTypeRepository.findAll()).contains(hardDelete); distributionSetManagement.deleteDistributionSetType(hardDelete); @@ -158,11 +165,12 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { @Test @Description("Tests the successfull deletion of used (soft delete) distribution set types.") public void deleteAssignedDistributionSetType() { - final DistributionSetType softDelete = distributionSetManagement - .createDistributionSetType(new DistributionSetType("softdeleted", "to be deletd", "")); + final JpaDistributionSetType softDelete = (JpaDistributionSetType) distributionSetManagement + .createDistributionSetType(new JpaDistributionSetType("softdeleted", "to be deletd", "")); assertThat(distributionSetTypeRepository.findAll()).contains(softDelete); - distributionSetManagement.createDistributionSet(new DistributionSet("newtypesoft", "1", "", softDelete, null)); + distributionSetManagement + .createDistributionSet(new JpaDistributionSet("newtypesoft", "1", "", softDelete, null)); distributionSetManagement.deleteDistributionSetType(softDelete); assertThat(distributionSetManagement.findDistributionSetTypeByKey("softdeleted").isDeleted()).isEqualTo(true); @@ -171,10 +179,10 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { @Test @Description("Ensures that it is not possible to create a DS that already exists (unique constraint is on name,version for DS).") public void createDuplicateDistributionSetsFailsWithException() { - TestDataUtil.generateDistributionSet("a", softwareManagement, distributionSetManagement); + testdataFactory.createDistributionSet("a"); try { - TestDataUtil.generateDistributionSet("a", softwareManagement, distributionSetManagement); + testdataFactory.createDistributionSet("a"); fail("Should not have worked as DS with same UK already exists."); } catch (final EntityAlreadyExistsException e) { @@ -185,7 +193,7 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { @Description("Verfies that a DS is of default type if not specified explicitly at creation time.") public void createDistributionSetWithImplicitType() { final DistributionSet set = distributionSetManagement - .createDistributionSet(new DistributionSet("newtypesoft", "1", "", null, null)); + .createDistributionSet(new JpaDistributionSet("newtypesoft", "1", "", null, null)); assertThat(set.getType()).as("Type should be equal to default type of tenant") .isEqualTo(systemManagement.getTenantMetadata().getDefaultDsType()); @@ -198,7 +206,7 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { List sets = new ArrayList<>(); for (int i = 0; i < 10; i++) { - sets.add(new DistributionSet("another DS" + i, "X" + i, "", null, null)); + sets.add(new JpaDistributionSet("another DS" + i, "X" + i, "", null, null)); } sets = distributionSetManagement.createDistributionSets(sets); @@ -216,7 +224,7 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { @Description("Verfies that a DS entity cannot be used for creation.") public void createDistributionSetFailsOnExistingEntity() { final DistributionSet set = distributionSetManagement - .createDistributionSet(new DistributionSet("newtypesoft", "1", "", null, null)); + .createDistributionSet(new JpaDistributionSet("newtypesoft", "1", "", null, null)); try { distributionSetManagement.createDistributionSet(set); @@ -232,11 +240,10 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { final String knownKey = "dsMetaKnownKey"; final String knownValue = "dsMetaKnownValue"; - final DistributionSet ds = TestDataUtil.generateDistributionSet("testDs", softwareManagement, - distributionSetManagement); + final DistributionSet ds = testdataFactory.createDistributionSet("testDs"); - final DistributionSetMetadata metadata = new DistributionSetMetadata(knownKey, ds, knownValue); - final DistributionSetMetadata createdMetadata = distributionSetManagement + final DistributionSetMetadata metadata = new JpaDistributionSetMetadata(knownKey, ds, knownValue); + final JpaDistributionSetMetadata createdMetadata = (JpaDistributionSetMetadata) distributionSetManagement .createDistributionSetMetadata(metadata); assertThat(createdMetadata).isNotNull(); @@ -249,14 +256,13 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { @Description("Ensures that updates concerning the internal software structure of a DS are not possible if the DS is already assigned.") public void updateDistributionSetForbiddedWithIllegalUpdate() { // prepare data - Target target = new Target("4711"); + Target target = new JpaTarget("4711"); target = targetManagement.createTarget(target); - SoftwareModule ah2 = new SoftwareModule(appType, "agent-hub2", "1.0.5", null, ""); - SoftwareModule os2 = new SoftwareModule(osType, "poky2", "3.0.3", null, ""); + SoftwareModule ah2 = new JpaSoftwareModule(appType, "agent-hub2", "1.0.5", null, ""); + SoftwareModule os2 = new JpaSoftwareModule(osType, "poky2", "3.0.3", null, ""); - DistributionSet ds = TestDataUtil.generateDistributionSet("ds-1", softwareManagement, - distributionSetManagement); + DistributionSet ds = testdataFactory.createDistributionSet("ds-1"); ah2 = softwareManagement.createSoftwareModule(ah2); os2 = softwareManagement.createSoftwareModule(os2); @@ -303,8 +309,8 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { @Test @Description("Ensures that it is not possible to add a software module to a set that has no type defined.") public void updateDistributionSetModuleWithUndefinedTypeFails() { - final DistributionSet testSet = new DistributionSet(); - final SoftwareModule module = new SoftwareModule(appType, "agent-hub2", "1.0.5", null, ""); + final DistributionSet testSet = new JpaDistributionSet(); + final SoftwareModule module = new JpaSoftwareModule(appType, "agent-hub2", "1.0.5", null, ""); // update data try { @@ -318,9 +324,9 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { @Test @Description("Ensures that it is not possible to add a software module that is not defined of the DS's type.") public void updateDistributionSetUnsupportedModuleFails() { - final DistributionSet set = new DistributionSet("agent-hub2", "1.0.5", "desc", - new DistributionSetType("test", "test", "test").addMandatoryModuleType(osType), null); - final SoftwareModule module = new SoftwareModule(appType, "agent-hub2", "1.0.5", null, ""); + final DistributionSet set = new JpaDistributionSet("agent-hub2", "1.0.5", "desc", + new JpaDistributionSetType("test", "test", "test").addMandatoryModuleType(osType), null); + final SoftwareModule module = new JpaSoftwareModule(appType, "agent-hub2", "1.0.5", null, ""); // update data try { @@ -335,13 +341,13 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { @Description("Legal updates of a DS, e.g. name or description and module addition, removal while still unassigned.") public void updateDistributionSet() { // prepare data - Target target = new Target("4711"); + Target target = new JpaTarget("4711"); target = targetManagement.createTarget(target); - SoftwareModule os2 = new SoftwareModule(osType, "poky2", "3.0.3", null, ""); - final SoftwareModule app2 = new SoftwareModule(appType, "app2", "3.0.3", null, ""); + SoftwareModule os2 = new JpaSoftwareModule(osType, "poky2", "3.0.3", null, ""); + final SoftwareModule app2 = new JpaSoftwareModule(appType, "app2", "3.0.3", null, ""); - DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement, distributionSetManagement); + DistributionSet ds = testdataFactory.createDistributionSet(""); os2 = softwareManagement.createSoftwareModule(os2); @@ -380,14 +386,13 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { final String knownUpdateValue = "myNewUpdatedValue"; // create a DS - final DistributionSet ds = TestDataUtil.generateDistributionSet("testDs", softwareManagement, - distributionSetManagement); + final DistributionSet ds = testdataFactory.createDistributionSet("testDs"); // initial opt lock revision must be zero assertThat(ds.getOptLockRevision()).isEqualTo(1L); // create an DS meta data entry final DistributionSetMetadata dsMetadata = distributionSetManagement - .createDistributionSetMetadata(new DistributionSetMetadata(knownKey, ds, knownValue)); + .createDistributionSetMetadata(new JpaDistributionSetMetadata(knownKey, ds, knownValue)); DistributionSet changedLockRevisionDS = distributionSetManagement.findDistributionSetById(ds.getId()); assertThat(changedLockRevisionDS.getOptLockRevision()).isEqualTo(2L); @@ -395,12 +400,13 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { // modifying the meta data value dsMetadata.setValue(knownUpdateValue); dsMetadata.setKey(knownKey); - dsMetadata.setDistributionSet(changedLockRevisionDS); + ((JpaDistributionSetMetadata) dsMetadata).setDistributionSet(changedLockRevisionDS); Thread.sleep(100); // update the DS metadata - final DistributionSetMetadata updated = distributionSetManagement.updateDistributionSetMetadata(dsMetadata); + final JpaDistributionSetMetadata updated = (JpaDistributionSetMetadata) distributionSetManagement + .updateDistributionSetMetadata(dsMetadata); // we are updating the sw meta data so also modifying the base software // module so opt lock // revision must be three @@ -419,11 +425,10 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { @Description("Tests that a DS queue is possible where the result is ordered by the target assignment, i.e. assigned first in the list.") public void findDistributionSetsAllOrderedByLinkTarget() { - final List buildDistributionSets = TestDataUtil.generateDistributionSets("dsOrder", 10, - softwareManagement, distributionSetManagement); + final List buildDistributionSets = testdataFactory.createDistributionSets("dsOrder", 10); final List buildTargetFixtures = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(5, "tOrder", "someDesc")); + .createTargets(testdataFactory.generateTargets(5, "tOrder", "someDesc")); final Iterator dsIterator = buildDistributionSets.iterator(); final Iterator tIterator = buildTargetFixtures.iterator(); @@ -466,32 +471,28 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { @Description("searches for distribution sets based on the various filter options, e.g. name, version, desc., tags.") public void searchDistributionSetsOnFilters() { DistributionSetTag dsTagA = tagManagement - .createDistributionSetTag(new DistributionSetTag("DistributionSetTag-A")); + .createDistributionSetTag(new JpaDistributionSetTag("DistributionSetTag-A")); final DistributionSetTag dsTagB = tagManagement - .createDistributionSetTag(new DistributionSetTag("DistributionSetTag-B")); + .createDistributionSetTag(new JpaDistributionSetTag("DistributionSetTag-B")); final DistributionSetTag dsTagC = tagManagement - .createDistributionSetTag(new DistributionSetTag("DistributionSetTag-C")); + .createDistributionSetTag(new JpaDistributionSetTag("DistributionSetTag-C")); final DistributionSetTag dsTagD = tagManagement - .createDistributionSetTag(new DistributionSetTag("DistributionSetTag-D")); + .createDistributionSetTag(new JpaDistributionSetTag("DistributionSetTag-D")); - List ds100Group1 = TestDataUtil.generateDistributionSets("", 100, softwareManagement, - distributionSetManagement); - List ds100Group2 = TestDataUtil.generateDistributionSets("test2", 100, softwareManagement, - distributionSetManagement); - DistributionSet dsDeleted = TestDataUtil.generateDistributionSet("deleted", softwareManagement, - distributionSetManagement); + Collection ds100Group1 = testdataFactory.createDistributionSets("", 100); + Collection ds100Group2 = testdataFactory.createDistributionSets("test2", 100); + DistributionSet dsDeleted = testdataFactory.createDistributionSet("deleted"); final DistributionSet dsInComplete = distributionSetManagement - .createDistributionSet(new DistributionSet("notcomplete", "1", "", standardDsType, null)); + .createDistributionSet(new JpaDistributionSet("notcomplete", "1", "", standardDsType, null)); - final DistributionSetType newType = distributionSetManagement - .createDistributionSetType(new DistributionSetType("foo", "bar", "test").addMandatoryModuleType(osType) + final DistributionSetType newType = distributionSetManagement.createDistributionSetType( + new JpaDistributionSetType("foo", "bar", "test").addMandatoryModuleType(osType) .addOptionalModuleType(appType).addOptionalModuleType(runtimeType)); final DistributionSet dsNewType = distributionSetManagement - .createDistributionSet(new DistributionSet("newtype", "1", "", newType, dsDeleted.getModules())); + .createDistributionSet(new JpaDistributionSet("newtype", "1", "", newType, dsDeleted.getModules())); - deploymentManagement.assignDistributionSet(dsDeleted, - targetManagement.createTargets(Lists.newArrayList(TestDataUtil.generateTargets(5)))); + deploymentManagement.assignDistributionSet(dsDeleted, Lists.newArrayList(testdataFactory.createTargets(5))); distributionSetManagement.deleteDistributionSet(dsDeleted); dsDeleted = distributionSetManagement.findDistributionSetById(dsDeleted.getId()); @@ -705,7 +706,7 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { final Status status, final String... msgs) { final List result = new ArrayList<>(); for (final Target t : targs) { - final List findByTarget = actionRepository.findByTarget(t); + final List findByTarget = actionRepository.findByTarget((JpaTarget) t); for (final Action action : findByTarget) { result.add(sendUpdateActionStatusToTarget(status, action, t, msgs)); } @@ -716,18 +717,17 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { @Test @Description("Simple DS load without the related data that should be loaded lazy.") public void findDistributionSetsWithoutLazy() { - TestDataUtil.generateDistributionSets(20, softwareManagement, distributionSetManagement); + testdataFactory.createDistributionSets(20); - assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(20); + assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)) + .hasSize(20); } @Test @Description("Deltes a DS that is no in use. Expected behaviour is a hard delete on the database.") public void deleteUnassignedDistributionSet() { - DistributionSet ds1 = TestDataUtil.generateDistributionSet("ds-1", softwareManagement, - distributionSetManagement); - DistributionSet ds2 = TestDataUtil.generateDistributionSet("ds-2", softwareManagement, - distributionSetManagement); + DistributionSet ds1 = testdataFactory.createDistributionSet("ds-1"); + DistributionSet ds2 = testdataFactory.createDistributionSet("ds-2"); ds1 = distributionSetManagement.findDistributionSetByNameAndVersion(ds1.getName(), ds1.getVersion()); ds2 = distributionSetManagement.findDistributionSetByNameAndVersion(ds2.getName(), ds2.getVersion()); @@ -737,30 +737,29 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { distributionSetManagement.deleteDistributionSet(ds1.getId()); // not assigned so not marked as deleted but fully deleted assertThat(distributionSetRepository.findAll()).hasSize(1); - assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, Boolean.FALSE, Boolean.TRUE) - .getTotalElements()).isEqualTo(1); + assertThat(distributionSetManagement + .findDistributionSetsByDeletedAndOrCompleted(pageReq, Boolean.FALSE, Boolean.TRUE).getTotalElements()) + .isEqualTo(1); } @Test @Description("Queries and loads the metadata related to a given software module.") public void findAllDistributionSetMetadataByDsId() { // create a DS - DistributionSet ds1 = TestDataUtil.generateDistributionSet("testDs1", softwareManagement, - distributionSetManagement); - DistributionSet ds2 = TestDataUtil.generateDistributionSet("testDs2", softwareManagement, - distributionSetManagement); + DistributionSet ds1 = testdataFactory.createDistributionSet("testDs1"); + DistributionSet ds2 = testdataFactory.createDistributionSet("testDs2"); for (int index = 0; index < 10; index++) { ds1 = distributionSetManagement - .createDistributionSetMetadata(new DistributionSetMetadata("key" + index, ds1, "value" + index)) + .createDistributionSetMetadata(new JpaDistributionSetMetadata("key" + index, ds1, "value" + index)) .getDistributionSet(); } for (int index = 0; index < 20; index++) { ds2 = distributionSetManagement - .createDistributionSetMetadata(new DistributionSetMetadata("key" + index, ds2, "value" + index)) + .createDistributionSetMetadata(new JpaDistributionSetMetadata("key" + index, ds2, "value" + index)) .getDistributionSet(); } @@ -781,12 +780,9 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { @Description("Deltes a DS that is no in use. Expected behaviour is a soft delete on the database, i.e. only marked as " + "deleted, kept eas refernce and unavailable for future use..") public void deleteAssignedDistributionSet() { - DistributionSet ds1 = TestDataUtil.generateDistributionSet("ds-1", softwareManagement, - distributionSetManagement); - DistributionSet ds2 = TestDataUtil.generateDistributionSet("ds-2", softwareManagement, - distributionSetManagement); - DistributionSet dsAssigned = TestDataUtil.generateDistributionSet("ds-3", softwareManagement, - distributionSetManagement); + DistributionSet ds1 = testdataFactory.createDistributionSet("ds-1"); + DistributionSet ds2 = testdataFactory.createDistributionSet("ds-2"); + DistributionSet dsAssigned = testdataFactory.createDistributionSet("ds-3"); ds1 = distributionSetManagement.findDistributionSetByNameAndVersion(ds1.getName(), ds1.getVersion()); ds2 = distributionSetManagement.findDistributionSetByNameAndVersion(ds2.getName(), ds2.getVersion()); @@ -794,7 +790,7 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { // create assigned DS dsAssigned = distributionSetManagement.findDistributionSetByNameAndVersion(dsAssigned.getName(), dsAssigned.getVersion()); - final Target target = new Target("4712"); + final Target target = new JpaTarget("4712"); final Target savedTarget = targetManagement.createTarget(target); final List toAssign = new ArrayList<>(); toAssign.add(savedTarget); @@ -806,22 +802,23 @@ public class DistributionSetManagementTest extends AbstractIntegrationTest { // not assigned so not marked as deleted assertThat(distributionSetRepository.findAll()).hasSize(3); - assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, Boolean.FALSE, Boolean.TRUE) - .getTotalElements()).isEqualTo(2); + assertThat(distributionSetManagement + .findDistributionSetsByDeletedAndOrCompleted(pageReq, Boolean.FALSE, Boolean.TRUE).getTotalElements()) + .isEqualTo(2); } private Target sendUpdateActionStatusToTarget(final Status status, final Action updActA, final Target t, final String... msgs) { updActA.setStatus(status); - final ActionStatus statusMessages = new ActionStatus(); + final ActionStatus statusMessages = new JpaActionStatus(); statusMessages.setAction(updActA); statusMessages.setOccurredAt(System.currentTimeMillis()); statusMessages.setStatus(status); for (final String msg : msgs) { statusMessages.addMessage(msg); } - controllerManagament.addUpdateActionStatus(statusMessages, updActA); + controllerManagament.addUpdateActionStatus(statusMessages); return targetManagement.findTargetByControllerID(t.getControllerId()); } diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/MethodSecurityUtil.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/MethodSecurityUtil.java similarity index 98% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/MethodSecurityUtil.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/MethodSecurityUtil.java index 6633a27e5..032289e87 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/MethodSecurityUtil.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/MethodSecurityUtil.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit; +package org.eclipse.hawkbit.repository.jpa; import static org.fest.assertions.Assertions.assertThat; diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/RandomGeneratedInputStream.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/RandomGeneratedInputStream.java similarity index 96% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/RandomGeneratedInputStream.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/RandomGeneratedInputStream.java index bd5be54f5..a7a1c0956 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/RandomGeneratedInputStream.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/RandomGeneratedInputStream.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit; +package org.eclipse.hawkbit.repository.jpa; import java.io.IOException; import java.io.InputStream; diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ReportManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ReportManagementTest.java similarity index 87% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ReportManagementTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ReportManagementTest.java index 0184a9d26..4fba80616 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ReportManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ReportManagementTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import static org.fest.assertions.Assertions.assertThat; import static org.fest.assertions.api.Assertions.fail; @@ -20,23 +20,26 @@ import java.util.Calendar; import java.util.List; import java.util.stream.Collectors; -import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.TestDataUtil; -import org.eclipse.hawkbit.WithSpringAuthorityRule; -import org.eclipse.hawkbit.WithUser; -import org.eclipse.hawkbit.report.model.DataReportSeries; -import org.eclipse.hawkbit.report.model.DataReportSeriesItem; -import org.eclipse.hawkbit.report.model.InnerOuterDataReportSeries; -import org.eclipse.hawkbit.report.model.SeriesTime; +import org.eclipse.hawkbit.repository.DistributionSetAssignmentResult; +import org.eclipse.hawkbit.repository.ReportManagement; import org.eclipse.hawkbit.repository.ReportManagement.DateTypes; +import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus; +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.Status; 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.repository.model.TargetUpdateStatus; +import org.eclipse.hawkbit.repository.report.model.DataReportSeries; +import org.eclipse.hawkbit.repository.report.model.DataReportSeriesItem; +import org.eclipse.hawkbit.repository.report.model.InnerOuterDataReportSeries; +import org.eclipse.hawkbit.repository.report.model.SeriesTime; +import org.eclipse.hawkbit.repository.util.TestdataFactory; +import org.eclipse.hawkbit.repository.util.WithSpringAuthorityRule; +import org.eclipse.hawkbit.repository.util.WithUser; import org.junit.After; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -54,7 +57,7 @@ import ru.yandex.qatools.allure.annotations.Stories; @Features("Component Tests - Repository") @Stories("Report Management") -public class ReportManagementTest extends AbstractIntegrationTest { +public class ReportManagementTest extends AbstractJpaIntegrationTest { @Autowired private ReportManagement reportManagement; @@ -83,7 +86,7 @@ public class ReportManagementTest extends AbstractIntegrationTest { for (int month = 0; month < maxMonthBackAmountCreateTargets; month++) { dynamicDateTimeProvider.nowMinusMonths(month); - targetManagement.createTarget(new Target("t" + month)); + targetManagement.createTarget(new JpaTarget("t" + month)); } final LocalDateTime to = LocalDateTime.now(); @@ -105,7 +108,7 @@ public class ReportManagementTest extends AbstractIntegrationTest { // check cache evict for (int month = 0; month < maxMonthBackAmountCreateTargets; month++) { dynamicDateTimeProvider.nowMinusMonths(month); - targetManagement.createTarget(new Target("t2" + month)); + targetManagement.createTarget(new JpaTarget("t2" + month)); } targetsCreatedOverPeriod = reportManagement.targetsCreatedOverPeriod(DateTypes.perMonth(), from, to); for (final DataReportSeriesItem reportItem : targetsCreatedOverPeriod.getData()) { @@ -127,15 +130,14 @@ public class ReportManagementTest extends AbstractIntegrationTest { final LocalDateTime to = LocalDateTime.now(); final LocalDateTime from = to.minusMonths(maxMonthBackAmountReportTargets); - final DistributionSet distributionSet = TestDataUtil.generateDistributionSet("ds", softwareManagement, - distributionSetManagement); + final DistributionSet distributionSet = testdataFactory.createDistributionSet("ds"); final DynamicDateTimeProvider dynamicDateTimeProvider = new DynamicDateTimeProvider(); auditingHandler.setDateTimeProvider(dynamicDateTimeProvider); for (int month = 0; month < maxMonthBackAmountCreateTargets; month++) { dynamicDateTimeProvider.nowMinusMonths(month); - final Target createTarget = targetManagement.createTarget(new Target("t" + month)); + final Target createTarget = targetManagement.createTarget(new JpaTarget("t" + month)); final DistributionSetAssignmentResult result = deploymentManagement.assignDistributionSet(distributionSet, Lists.newArrayList(createTarget)); controllerManagament.registerRetrieved( @@ -157,7 +159,7 @@ public class ReportManagementTest extends AbstractIntegrationTest { // check cache evict for (int month = 0; month < maxMonthBackAmountCreateTargets; month++) { dynamicDateTimeProvider.nowMinusMonths(month); - final Target createTarget = targetManagement.createTarget(new Target("t2" + month)); + final Target createTarget = targetManagement.createTarget(new JpaTarget("t2" + month)); final DistributionSetAssignmentResult result = deploymentManagement.assignDistributionSet(distributionSet, Lists.newArrayList(createTarget)); controllerManagament.registerRetrieved( @@ -174,27 +176,24 @@ public class ReportManagementTest extends AbstractIntegrationTest { @Test @Description("Tests correct statistics calculation including a correct cache evict.") public void distributionUsageInstalled() { - final Target knownTarget1 = targetManagement.createTarget(new Target("t1")); - final Target knownTarget2 = targetManagement.createTarget(new Target("t2")); - final Target knownTarget3 = targetManagement.createTarget(new Target("t3")); - final Target knownTarget4 = targetManagement.createTarget(new Target("t4")); - final Target knownTarget5 = targetManagement.createTarget(new Target("t5")); + final Target knownTarget1 = targetManagement.createTarget(new JpaTarget("t1")); + final Target knownTarget2 = targetManagement.createTarget(new JpaTarget("t2")); + final Target knownTarget3 = targetManagement.createTarget(new JpaTarget("t3")); + final Target knownTarget4 = targetManagement.createTarget(new JpaTarget("t4")); + final Target knownTarget5 = targetManagement.createTarget(new JpaTarget("t5")); - 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); - final DistributionSet distributionSet1 = distributionSetManagement - .createDistributionSet(TestDataUtil.buildDistributionSet("ds1", "0.0.0", standardDsType, os, jvm, ah)); - final DistributionSet distributionSet11 = distributionSetManagement - .createDistributionSet(TestDataUtil.buildDistributionSet("ds1", "0.0.1", standardDsType, os, jvm, ah)); - final DistributionSet distributionSet2 = distributionSetManagement - .createDistributionSet(TestDataUtil.buildDistributionSet("ds2", "0.0.2", standardDsType, os, jvm, ah)); - final DistributionSet distributionSet3 = distributionSetManagement - .createDistributionSet(TestDataUtil.buildDistributionSet("ds3", "0.0.3", standardDsType, os, jvm, ah)); + final DistributionSet distributionSet1 = distributionSetManagement.createDistributionSet(testdataFactory + .generateDistributionSet("ds1", "0.0.0", standardDsType, Lists.newArrayList(os, jvm, ah))); + final DistributionSet distributionSet11 = distributionSetManagement.createDistributionSet(testdataFactory + .generateDistributionSet("ds1", "0.0.1", standardDsType, Lists.newArrayList(os, jvm, ah))); + final DistributionSet distributionSet2 = distributionSetManagement.createDistributionSet(testdataFactory + .generateDistributionSet("ds2", "0.0.2", standardDsType, Lists.newArrayList(os, jvm, ah))); + final DistributionSet distributionSet3 = distributionSetManagement.createDistributionSet(testdataFactory + .generateDistributionSet("ds3", "0.0.3", standardDsType, Lists.newArrayList(os, jvm, ah))); // ds1(0.0.0)=[target1,target2], ds1(0.0.1)=[target3] deploymentManagement.assignDistributionSet(distributionSet1.getId(), knownTarget1.getControllerId()); @@ -250,7 +249,7 @@ public class ReportManagementTest extends AbstractIntegrationTest { } // Test cache evict - final Target knownTarget6 = targetManagement.createTarget(new Target("t6")); + final Target knownTarget6 = targetManagement.createTarget(new JpaTarget("t6")); deploymentManagement.assignDistributionSet(distributionSet1.getId(), knownTarget6.getControllerId()); sendUpdateActionStatusToTargets(distributionSet1, Lists.newArrayList(knownTarget6), Status.FINISHED, "some message"); @@ -349,26 +348,23 @@ public class ReportManagementTest extends AbstractIntegrationTest { @Description("Tests correct statistics calculation including a correct cache evict.") public void topXDistributionUsage() { - final Target knownTarget1 = targetManagement.createTarget(new Target("t1")); - final Target knownTarget2 = targetManagement.createTarget(new Target("t2")); - final Target knownTarget3 = targetManagement.createTarget(new Target("t3")); - final Target knownTarget4 = targetManagement.createTarget(new Target("t4")); + final Target knownTarget1 = targetManagement.createTarget(new JpaTarget("t1")); + final Target knownTarget2 = targetManagement.createTarget(new JpaTarget("t2")); + final Target knownTarget3 = targetManagement.createTarget(new JpaTarget("t3")); + final Target knownTarget4 = targetManagement.createTarget(new JpaTarget("t4")); - 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); - final DistributionSet distributionSet1 = distributionSetManagement - .createDistributionSet(TestDataUtil.buildDistributionSet("ds1", "0.0.0", standardDsType, os, jvm, ah)); - final DistributionSet distributionSet11 = distributionSetManagement - .createDistributionSet(TestDataUtil.buildDistributionSet("ds1", "0.0.1", standardDsType, os, jvm, ah)); - final DistributionSet distributionSet2 = distributionSetManagement - .createDistributionSet(TestDataUtil.buildDistributionSet("ds2", "0.0.2", standardDsType, os, jvm, ah)); - final DistributionSet distributionSet3 = distributionSetManagement - .createDistributionSet(TestDataUtil.buildDistributionSet("ds3", "0.0.3", standardDsType, os, jvm, ah)); + final DistributionSet distributionSet1 = distributionSetManagement.createDistributionSet(testdataFactory + .generateDistributionSet("ds1", "0.0.0", standardDsType, Lists.newArrayList(os, jvm, ah))); + final DistributionSet distributionSet11 = distributionSetManagement.createDistributionSet(testdataFactory + .generateDistributionSet("ds1", "0.0.1", standardDsType, Lists.newArrayList(os, jvm, ah))); + final DistributionSet distributionSet2 = distributionSetManagement.createDistributionSet(testdataFactory + .generateDistributionSet("ds2", "0.0.2", standardDsType, Lists.newArrayList(os, jvm, ah))); + final DistributionSet distributionSet3 = distributionSetManagement.createDistributionSet(testdataFactory + .generateDistributionSet("ds3", "0.0.3", standardDsType, Lists.newArrayList(os, jvm, ah))); // ds1(0.0.0)=[target1,target2], ds1(0.0.1)=[target3] deploymentManagement.assignDistributionSet(distributionSet1.getId(), knownTarget1.getControllerId()); @@ -419,7 +415,7 @@ public class ReportManagementTest extends AbstractIntegrationTest { } // test cache evict - final Target knownTarget5 = targetManagement.createTarget(new Target("t5")); + final Target knownTarget5 = targetManagement.createTarget(new JpaTarget("t5")); deploymentManagement.assignDistributionSet(distributionSet1.getId(), knownTarget5.getControllerId()); distributionUsage = reportManagement.distributionUsageAssigned(100); for (final InnerOuterDataReportSeries innerOuterDataReportSeries : distributionUsage) { @@ -490,7 +486,7 @@ public class ReportManagementTest extends AbstractIntegrationTest { // create targets for another tenant securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", "anotherTenant"), () -> { for (int index = 0; index < targetCreateAmount; index++) { - targetManagement.createTarget(new Target("t" + index)); + targetManagement.createTarget(new JpaTarget("t" + index)); } return null; }); @@ -513,10 +509,10 @@ public class ReportManagementTest extends AbstractIntegrationTest { private void createTargets(final String prefix, final int amount, final LocalDateTime lastTargetQuery) { for (int index = 0; index < amount; index++) { - final Target target = new Target(prefix + index); - final Target createTarget = targetManagement.createTarget(target); + final Target target = new JpaTarget(prefix + index); + final JpaTarget createTarget = (JpaTarget) targetManagement.createTarget(target); if (lastTargetQuery != null) { - final TargetInfo targetInfo = createTarget.getTargetInfo(); + final JpaTargetInfo targetInfo = (JpaTargetInfo) createTarget.getTargetInfo(); targetInfo.setNew(false); targetInfo .setLastTargetQuery(lastTargetQuery.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); @@ -527,9 +523,9 @@ public class ReportManagementTest extends AbstractIntegrationTest { private void createTargetsWithStatus(final String prefix, final long amount, final TargetUpdateStatus status) { for (int index = 0; index < amount; index++) { - final Target target = new Target(prefix + index); + final JpaTarget target = new JpaTarget(prefix + index); final Target sTarget = targetRepository.save(target); - final TargetInfo targetInfo = sTarget.getTargetInfo(); + final JpaTargetInfo targetInfo = (JpaTargetInfo) sTarget.getTargetInfo(); targetInfo.setUpdateStatus(status); targetInfoRepository.save(targetInfo); } @@ -537,9 +533,9 @@ public class ReportManagementTest extends AbstractIntegrationTest { private List sendUpdateActionStatusToTargets(final DistributionSet dsA, final Iterable targs, final Status status, final String... msgs) { - final List result = new ArrayList(); + final List result = new ArrayList<>(); for (final Target t : targs) { - final List findByTarget = actionRepository.findByTarget(t); + final List findByTarget = actionRepository.findByTarget((JpaTarget) t); for (final Action action : findByTarget) { result.add(sendUpdateActionStatusToTarget(status, action, t, msgs)); } @@ -551,14 +547,14 @@ public class ReportManagementTest extends AbstractIntegrationTest { final String... msgs) { updActA.setStatus(status); - final ActionStatus statusMessages = new ActionStatus(); + final ActionStatus statusMessages = new JpaActionStatus(); statusMessages.setAction(updActA); statusMessages.setOccurredAt(System.currentTimeMillis()); statusMessages.setStatus(status); for (final String msg : msgs) { statusMessages.addMessage(msg); } - controllerManagament.addUpdateActionStatus(statusMessages, updActA); + controllerManagament.addUpdateActionStatus(statusMessages); return targetManagement.findTargetByControllerID(t.getControllerId()); } diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/RolloutManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/RolloutManagementTest.java similarity index 93% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/RolloutManagementTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/RolloutManagementTest.java index 22f9ee8b4..42e5de498 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/RolloutManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/RolloutManagementTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import static org.fest.assertions.api.Assertions.assertThat; @@ -16,27 +16,31 @@ import java.util.List; import java.util.Map; import java.util.concurrent.Callable; -import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.TestDataUtil; +import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; +import org.eclipse.hawkbit.repository.RolloutGroupManagement; +import org.eclipse.hawkbit.repository.RolloutManagement; +import org.eclipse.hawkbit.repository.jpa.model.JpaAction; +import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus; +import org.eclipse.hawkbit.repository.jpa.model.JpaRollout; +import org.eclipse.hawkbit.repository.jpa.utils.MultipleInvokeHelper; +import org.eclipse.hawkbit.repository.jpa.utils.SuccessCondition; 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.Rollout; import org.eclipse.hawkbit.repository.model.Rollout.RolloutStatus; 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.RolloutGroupStatus; 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.SoftwareModule; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.repository.model.TotalTargetCountStatus; -import org.eclipse.hawkbit.repository.rsql.RSQLUtility; -import org.eclipse.hawkbit.repository.utils.MultipleInvokeHelper; -import org.eclipse.hawkbit.repository.utils.SuccessCondition; +import org.eclipse.hawkbit.repository.util.TestdataFactory; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Description; @@ -44,7 +48,8 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.Slice; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; -import org.springframework.data.jpa.domain.Specification; + +import com.google.common.collect.Lists; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; @@ -57,7 +62,7 @@ import ru.yandex.qatools.allure.annotations.Stories; */ @Features("Component Tests - Repository") @Stories("Rollout Management") -public class RolloutManagementTest extends AbstractIntegrationTest { +public class RolloutManagementTest extends AbstractJpaIntegrationTest { @Autowired private RolloutManagement rolloutManagement; @@ -134,10 +139,10 @@ public class RolloutManagementTest extends AbstractIntegrationTest { Status.RUNNING); // finish one action should be sufficient due the finish condition is at // 50% - final Action action = runningActions.get(0); + final JpaAction action = (JpaAction) runningActions.get(0); action.setStatus(Status.FINISHED); - controllerManagament.addUpdateActionStatus( - new ActionStatus(action, Status.FINISHED, System.currentTimeMillis(), ""), action); + controllerManagament + .addUpdateActionStatus(new JpaActionStatus(action, Status.FINISHED, System.currentTimeMillis(), "")); // check running rollouts again, now the finish condition should be hit // and should start the next group @@ -179,7 +184,7 @@ public class RolloutManagementTest extends AbstractIntegrationTest { for (final Action action : runningActions) { action.setStatus(Status.ERROR); controllerManagament.addUpdateActionStatus( - new ActionStatus(action, Status.ERROR, System.currentTimeMillis(), ""), action); + new JpaActionStatus((JpaAction) action, Status.ERROR, System.currentTimeMillis(), "")); } // check running rollouts again, now the error condition should be hit @@ -221,7 +226,7 @@ public class RolloutManagementTest extends AbstractIntegrationTest { for (final Action action : runningActions) { action.setStatus(Status.ERROR); controllerManagament.addUpdateActionStatus( - new ActionStatus(action, Status.ERROR, System.currentTimeMillis(), ""), action); + new JpaActionStatus((JpaAction) action, Status.ERROR, System.currentTimeMillis(), "")); } // check running rollouts again, now the error condition should be hit @@ -452,8 +457,7 @@ public class RolloutManagementTest extends AbstractIntegrationTest { targetToCancel.add(targetList.get(0)); targetToCancel.add(targetList.get(1)); targetToCancel.add(targetList.get(2)); - final DistributionSet dsForCancelTest = TestDataUtil.generateDistributionSet("dsForTest", softwareManagement, - distributionSetManagement); + final DistributionSet dsForCancelTest = testdataFactory.createDistributionSet("dsForTest"); deploymentManagement.assignDistributionSet(dsForCancelTest, targetToCancel); // 5 targets are canceling but still have the status running and 5 are // still in SCHEDULED @@ -477,8 +481,7 @@ public class RolloutManagementTest extends AbstractIntegrationTest { rolloutManagement.startRollout(rolloutOne); rolloutOne = rolloutManagement.findRolloutById(rolloutOne.getId()); - final DistributionSet dsForRolloutTwo = TestDataUtil.generateDistributionSet("dsForRolloutTwo", - softwareManagement, distributionSetManagement); + final DistributionSet dsForRolloutTwo = testdataFactory.createDistributionSet("dsForRolloutTwo"); final Rollout rolloutTwo = createRolloutByVariables("rolloutTwo", "This is the description for rollout two", 1, "controllerId==rollout-*", dsForRolloutTwo, "50", "80"); @@ -831,28 +834,27 @@ public class RolloutManagementTest extends AbstractIntegrationTest { Rollout myRollout = createTestRolloutWithTargetsAndDistributionSet(amountTargetsForRollout, amountGroups, successCondition, errorCondition, rolloutName, rolloutName); - targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountOtherTargets, "others-", "rollout")); + targetManagement.createTargets(testdataFactory.generateTargets(amountOtherTargets, "others-", "rollout")); final String rsqlParam = "controllerId==*MyRoll*"; - final Specification rsqlSpecification = RSQLUtility.parse(rsqlParam, TargetFields.class); rolloutManagement.startRollout(myRollout); myRollout = rolloutManagement.findRolloutById(myRollout.getId()); final List rolloutGroups = myRollout.getRolloutGroups(); - Page targetPage = rolloutGroupManagement.findRolloutGroupTargets(rolloutGroups.get(0), - rsqlSpecification, new OffsetBasedPageRequest(0, 100, new Sort(Direction.ASC, "controllerId"))); + Page targetPage = rolloutGroupManagement.findRolloutGroupTargets(rolloutGroups.get(0), rsqlParam, + new OffsetBasedPageRequest(0, 100, new Sort(Direction.ASC, "controllerId"))); final List targetlistGroup1 = targetPage.getContent(); assertThat(targetlistGroup1.size()).isEqualTo(5); assertThat(targetlistGroup1.get(0).getControllerId()).isEqualTo("MyRollout--00000"); - targetPage = rolloutGroupManagement.findRolloutGroupTargets(rolloutGroups.get(1), rsqlSpecification, + targetPage = rolloutGroupManagement.findRolloutGroupTargets(rolloutGroups.get(1), rsqlParam, new OffsetBasedPageRequest(0, 100, new Sort(Direction.DESC, "controllerId"))); final List targetlistGroup2 = targetPage.getContent(); assertThat(targetlistGroup2.size()).isEqualTo(5); assertThat(targetlistGroup2.get(0).getControllerId()).isEqualTo("MyRollout--00009"); - targetPage = rolloutGroupManagement.findRolloutGroupTargets(rolloutGroups.get(2), rsqlSpecification, + targetPage = rolloutGroupManagement.findRolloutGroupTargets(rolloutGroups.get(2), rsqlParam, new OffsetBasedPageRequest(0, 100, new Sort(Direction.ASC, "controllerId"))); final List targetlistGroup3 = targetPage.getContent(); assertThat(targetlistGroup3.size()).isEqualTo(5); @@ -870,15 +872,14 @@ public class RolloutManagementTest extends AbstractIntegrationTest { final String errorCondition = "80"; final String rolloutName = "rolloutTest"; final String targetPrefixName = rolloutName; - final DistributionSet distributionSet = TestDataUtil.generateDistributionSet("dsFor" + rolloutName, - softwareManagement, distributionSetManagement); + final DistributionSet distributionSet = testdataFactory.createDistributionSet("dsFor" + rolloutName); targetManagement.createTargets( - TestDataUtil.buildTargetFixtures(amountTargetsForRollout, targetPrefixName + "-", targetPrefixName)); - final RolloutGroupConditions conditions = new RolloutGroup.RolloutGroupConditionBuilder() + testdataFactory.generateTargets(amountTargetsForRollout, targetPrefixName + "-", targetPrefixName)); + final RolloutGroupConditions conditions = new RolloutGroupConditionBuilder() .successCondition(RolloutGroupSuccessCondition.THRESHOLD, successCondition) .errorCondition(RolloutGroupErrorCondition.THRESHOLD, errorCondition) .errorAction(RolloutGroupErrorAction.PAUSE, null).build(); - Rollout myRollout = new Rollout(); + Rollout myRollout = new JpaRollout(); myRollout.setName(rolloutName); myRollout.setDescription("This is a test description for the rollout"); myRollout.setTargetFilterQuery("controllerId==" + targetPrefixName + "-*"); @@ -931,17 +932,14 @@ public class RolloutManagementTest extends AbstractIntegrationTest { private Rollout createSimpleTestRolloutWithTargetsAndDistributionSet(final int amountTargetsForRollout, final int amountOtherTargets, final int groupSize, final String successCondition, final String errorCondition) { - 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 DistributionSet rolloutDS = distributionSetManagement.createDistributionSet( - TestDataUtil.buildDistributionSet("rolloutDS", "0.0.0", standardDsType, os, jvm, ah)); - targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(amountTargetsForRollout, "rollout-", "rollout")); - targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountOtherTargets, "others-", "rollout")); + 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); + + final DistributionSet rolloutDS = distributionSetManagement.createDistributionSet(testdataFactory + .generateDistributionSet("rolloutDS", "0.0.0", standardDsType, Lists.newArrayList(os, jvm, ah))); + targetManagement.createTargets(testdataFactory.generateTargets(amountTargetsForRollout, "rollout-", "rollout")); + targetManagement.createTargets(testdataFactory.generateTargets(amountOtherTargets, "others-", "rollout")); final String filterQuery = "controllerId==rollout-*"; return createRolloutByVariables("test-rollout-name-1", "test-rollout-description-1", groupSize, filterQuery, rolloutDS, successCondition, errorCondition); @@ -950,10 +948,9 @@ public class RolloutManagementTest extends AbstractIntegrationTest { private Rollout createTestRolloutWithTargetsAndDistributionSet(final int amountTargetsForRollout, final int groupSize, final String successCondition, final String errorCondition, final String rolloutName, final String targetPrefixName) { - final DistributionSet dsForRolloutTwo = TestDataUtil.generateDistributionSet("dsFor" + rolloutName, - softwareManagement, distributionSetManagement); + final DistributionSet dsForRolloutTwo = testdataFactory.createDistributionSet("dsFor" + rolloutName); targetManagement.createTargets( - TestDataUtil.buildTargetFixtures(amountTargetsForRollout, targetPrefixName + "-", targetPrefixName)); + testdataFactory.generateTargets(amountTargetsForRollout, targetPrefixName + "-", targetPrefixName)); return createRolloutByVariables(rolloutName, rolloutName + "description", groupSize, "controllerId==" + targetPrefixName + "-*", dsForRolloutTwo, successCondition, errorCondition); } @@ -961,11 +958,11 @@ public class RolloutManagementTest extends AbstractIntegrationTest { private Rollout createRolloutByVariables(final String rolloutName, final String rolloutDescription, final int groupSize, final String filterQuery, final DistributionSet distributionSet, final String successCondition, final String errorCondition) { - final RolloutGroupConditions conditions = new RolloutGroup.RolloutGroupConditionBuilder() + final RolloutGroupConditions conditions = new RolloutGroupConditionBuilder() .successCondition(RolloutGroupSuccessCondition.THRESHOLD, successCondition) .errorCondition(RolloutGroupErrorCondition.THRESHOLD, errorCondition) .errorAction(RolloutGroupErrorAction.PAUSE, null).build(); - final Rollout rolloutToCreate = new Rollout(); + final Rollout rolloutToCreate = new JpaRollout(); rolloutToCreate.setName(rolloutName); rolloutToCreate.setDescription(rolloutDescription); rolloutToCreate.setTargetFilterQuery(filterQuery); @@ -977,8 +974,8 @@ public class RolloutManagementTest extends AbstractIntegrationTest { final List runningActions = deploymentManagement.findActionsByRolloutAndStatus(rollout, Status.RUNNING); for (final Action action : runningActions) { action.setStatus(status); - controllerManagament.addUpdateActionStatus(new ActionStatus(action, status, System.currentTimeMillis(), ""), - action); + controllerManagament.addUpdateActionStatus( + new JpaActionStatus((JpaAction) action, status, System.currentTimeMillis(), "")); } return runningActions.size(); } @@ -989,14 +986,13 @@ public class RolloutManagementTest extends AbstractIntegrationTest { assertThat(runningActions.size()).isGreaterThanOrEqualTo(amountOfTargetsToGetChanged); for (int i = 0; i < amountOfTargetsToGetChanged; i++) { controllerManagament.addUpdateActionStatus( - new ActionStatus(runningActions.get(i), status, System.currentTimeMillis(), ""), - runningActions.get(i)); + new JpaActionStatus((JpaAction) runningActions.get(i), status, System.currentTimeMillis(), "")); } return runningActions.size(); } - private Map createInitStatusMap() { - final Map map = new HashMap(); + private static Map createInitStatusMap() { + final Map map = new HashMap<>(); for (final TotalTargetCountStatus.Status status : TotalTargetCountStatus.Status.values()) { map.put(status, 0L); } diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/SoftwareManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SoftwareManagementTest.java similarity index 75% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/SoftwareManagementTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SoftwareManagementTest.java index 849cf8e30..366dd6ec7 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/SoftwareManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SoftwareManagementTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import static org.fest.assertions.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; @@ -20,24 +20,26 @@ import java.util.Iterator; import java.util.List; import org.apache.commons.lang3.RandomUtils; -import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB; -import org.eclipse.hawkbit.RandomGeneratedInputStream; -import org.eclipse.hawkbit.TestDataUtil; -import org.eclipse.hawkbit.WithUser; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType; +import org.eclipse.hawkbit.repository.jpa.model.JpaLocalArtifact; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleMetadata; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Artifact; -import org.eclipse.hawkbit.repository.model.CustomSoftwareModule; +import org.eclipse.hawkbit.repository.model.AssignedSoftwareModule; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetType; -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.SoftwareModuleType; -import org.eclipse.hawkbit.repository.model.SwMetadataCompositeKey; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; +import org.eclipse.hawkbit.repository.util.WithUser; import org.junit.Test; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; @@ -53,13 +55,13 @@ import ru.yandex.qatools.allure.annotations.Stories; @Features("Component Tests - Repository") @Stories("Software Management") -public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { +public class SoftwareManagementTest extends AbstractJpaIntegrationTestWithMongoDB { @Test @Description("Try to update non updatable fields results in repository doing nothing.") public void updateTypeNonUpdateableFieldsFails() { final SoftwareModuleType created = softwareManagement - .createSoftwareModuleType(new SoftwareModuleType("test-key", "test-name", "test-desc", 1)); + .createSoftwareModuleType(new JpaSoftwareModuleType("test-key", "test-name", "test-desc", 1)); created.setName("a new name"); final SoftwareModuleType updated = softwareManagement.updateSoftwareModuleType(created); @@ -73,7 +75,7 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { @Description("Calling update without changing fields results in no recorded change in the repository including unchanged audit fields.") public void updateNothingResultsInUnchangedRepositoryForType() { final SoftwareModuleType created = softwareManagement - .createSoftwareModuleType(new SoftwareModuleType("test-key", "test-name", "test-desc", 1)); + .createSoftwareModuleType(new JpaSoftwareModuleType("test-key", "test-name", "test-desc", 1)); final SoftwareModuleType updated = softwareManagement.updateSoftwareModuleType(created); @@ -86,7 +88,7 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { @Description("Calling update for changed fields results in change in the repository.") public void updateSoftareModuleTypeFieldsToNewValue() { final SoftwareModuleType created = softwareManagement - .createSoftwareModuleType(new SoftwareModuleType("test-key", "test-name", "test-desc", 1)); + .createSoftwareModuleType(new JpaSoftwareModuleType("test-key", "test-name", "test-desc", 1)); created.setDescription("changed"); created.setColour("changed"); @@ -103,7 +105,7 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { @Description("Try to update non updatable fields results in repository doing nothing.") public void updateNonUpdateableFieldsFails() { final SoftwareModule ah = softwareManagement - .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); ah.setName("a new name"); final SoftwareModule updated = softwareManagement.updateSoftwareModule(ah); @@ -117,7 +119,7 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { @Description("Calling update without changing fields results in no recorded change in the repository including unchanged audit fields.") public void updateNothingResultsInUnchangedRepository() { final SoftwareModule ah = softwareManagement - .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); final SoftwareModule updated = softwareManagement.updateSoftwareModule(ah); @@ -130,7 +132,7 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { @Description("Calling update for changed fields results in change in the repository.") public void updateSoftareModuleFieldsToNewValue() { final SoftwareModule ah = softwareManagement - .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", "test desc", "test vendor")); + .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", "test desc", "test vendor")); ah.setDescription("changed"); ah.setVendor("changed"); @@ -146,7 +148,7 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { @Description("Create Software Module call fails when called for existing entity.") public void createModuleCallFailsForExistingModule() { final SoftwareModule ah = softwareManagement - .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", "test desc", "test vendor")); + .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", "test desc", "test vendor")); try { softwareManagement.createSoftwareModule(ah); fail("Should not have worked as module already exists."); @@ -159,8 +161,8 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { @Description("Create Software Modules call fails when called for existing entities.") public void createModulesCallFailsForExistingModule() { final List modules = softwareManagement.createSoftwareModule( - Lists.newArrayList(new SoftwareModule(appType, "agent-hub", "1.0.1", "test desc", "test vendor"), - new SoftwareModule(appType, "agent-hub", "1.0.2", "test desc", "test vendor"))); + Lists.newArrayList(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", "test desc", "test vendor"), + new JpaSoftwareModule(appType, "agent-hub", "1.0.2", "test desc", "test vendor"))); try { softwareManagement.createSoftwareModule(modules); fail("Should not have worked as module already exists."); @@ -173,7 +175,7 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { @Description("Create Software Module Type call fails when called for existing entity.") public void createModuleTypeCallFailsForExistingType() { final SoftwareModuleType created = softwareManagement - .createSoftwareModuleType(new SoftwareModuleType("test-key", "test-name", "test-desc", 1)); + .createSoftwareModuleType(new JpaSoftwareModuleType("test-key", "test-name", "test-desc", 1)); try { softwareManagement.createSoftwareModuleType(created); @@ -187,8 +189,8 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { @Description("Create Software Module Types call fails when called for existing entities.") public void createModuleTypesCallFailsForExistingTypes() { final List created = softwareManagement.createSoftwareModuleType( - Lists.newArrayList(new SoftwareModuleType("test-key-bumlux", "test-name", "test-desc", 1), - new SoftwareModuleType("test-key-bumlux2", "test-name2", "test-desc", 1))); + Lists.newArrayList(new JpaSoftwareModuleType("test-key-bumlux", "test-name", "test-desc", 1), + new JpaSoftwareModuleType("test-key-bumlux2", "test-name2", "test-desc", 1))); try { softwareManagement.createSoftwareModuleType(created); @@ -202,7 +204,7 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { @Description("Calling update for changing fields to null results in change in the repository.") public void eraseSoftareModuleFields() { final SoftwareModule ah = softwareManagement - .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", "test desc", "test vendor")); + .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", "test desc", "test vendor")); ah.setDescription(null); ah.setVendor(null); @@ -218,19 +220,19 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { @Description("searched for software modules based on the various filter options, e.g. name,desc,type, version.") public void findSoftwareModuleByFilters() { final SoftwareModule ah = softwareManagement - .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); final SoftwareModule jvm = softwareManagement - .createSoftwareModule(new SoftwareModule(runtimeType, "oracle-jre", "1.7.2", null, "")); + .createSoftwareModule(new JpaSoftwareModule(runtimeType, "oracle-jre", "1.7.2", null, "")); final SoftwareModule os = softwareManagement - .createSoftwareModule(new SoftwareModule(osType, "poky", "3.0.2", null, "")); + .createSoftwareModule(new JpaSoftwareModule(osType, "poky", "3.0.2", null, "")); final SoftwareModule ah2 = softwareManagement - .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.2", null, "")); - DistributionSet ds = distributionSetManagement.createDistributionSet( - TestDataUtil.buildDistributionSet("ds-1", "1.0.1", standardDsType, os, jvm, ah2)); + .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.2", null, "")); + JpaDistributionSet ds = (JpaDistributionSet) distributionSetManagement.createDistributionSet(testdataFactory + .generateDistributionSet("ds-1", "1.0.1", standardDsType, Lists.newArrayList(os, jvm, ah2))); - final Target target = targetManagement.createTarget(new Target("test123")); - ds = assignSet(target, ds).getDistributionSet(); + final JpaTarget target = (JpaTarget) targetManagement.createTarget(new JpaTarget("test123")); + ds = (JpaDistributionSet) assignSet(target, ds).getDistributionSet(); // standard searches assertThat(softwareManagement.findSoftwareModuleByFilters(pageReq, "poky", osType).getContent()).hasSize(1); @@ -254,7 +256,7 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { .isEqualTo(ah); } - private Action assignSet(final Target target, final DistributionSet ds) { + private Action assignSet(final JpaTarget target, final JpaDistributionSet ds) { deploymentManagement.assignDistributionSet(ds.getId(), new String[] { target.getControllerId() }); assertThat( targetManagement.findTargetByControllerID(target.getControllerId()).getTargetInfo().getUpdateStatus()) @@ -270,12 +272,12 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { @Description("Searches for software modules based on a list of IDs.") public void findSoftwareModulesById() { - final List modules = new ArrayList(); + final List modules = new ArrayList<>(); - modules.add(softwareManagement.createSoftwareModule(new SoftwareModule(osType, "poky-una", "3.0.2", null, "")) - .getId()); - modules.add(softwareManagement.createSoftwareModule(new SoftwareModule(osType, "poky-u2na", "3.0.3", null, "")) - .getId()); + modules.add(softwareManagement + .createSoftwareModule(new JpaSoftwareModule(osType, "poky-una", "3.0.2", null, "")).getId()); + modules.add(softwareManagement + .createSoftwareModule(new JpaSoftwareModule(osType, "poky-u2na", "3.0.3", null, "")).getId()); modules.add(624355263L); assertThat(softwareManagement.findSoftwareModulesById(modules)).hasSize(2); @@ -286,13 +288,13 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { public void findSoftwareModulesByType() { // found in test final SoftwareModule one = softwareManagement - .createSoftwareModule(new SoftwareModule(osType, "one", "one", null, "")); + .createSoftwareModule(new JpaSoftwareModule(osType, "one", "one", null, "")); final SoftwareModule two = softwareManagement - .createSoftwareModule(new SoftwareModule(osType, "two", "two", null, "")); + .createSoftwareModule(new JpaSoftwareModule(osType, "two", "two", null, "")); // ignored softwareManagement.deleteSoftwareModule( - softwareManagement.createSoftwareModule(new SoftwareModule(osType, "deleted", "deleted", null, ""))); - softwareManagement.createSoftwareModule(new SoftwareModule(appType, "three", "3.0.2", null, "")); + softwareManagement.createSoftwareModule(new JpaSoftwareModule(osType, "deleted", "deleted", null, ""))); + softwareManagement.createSoftwareModule(new JpaSoftwareModule(appType, "three", "3.0.2", null, "")); assertThat(softwareManagement.findSoftwareModulesByType(pageReq, osType).getContent()) .as("Expected to find the following number of modules:").hasSize(2).as("with the following elements") @@ -303,11 +305,11 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { @Description("Counts all software modules in the repsitory that are not marked as deleted.") public void countSoftwareModulesAll() { // found in test - softwareManagement.createSoftwareModule(new SoftwareModule(osType, "one", "one", null, "")); - softwareManagement.createSoftwareModule(new SoftwareModule(appType, "two", "two", null, "")); + softwareManagement.createSoftwareModule(new JpaSoftwareModule(osType, "one", "one", null, "")); + softwareManagement.createSoftwareModule(new JpaSoftwareModule(appType, "two", "two", null, "")); // ignored softwareManagement.deleteSoftwareModule( - softwareManagement.createSoftwareModule(new SoftwareModule(osType, "deleted", "deleted", null, ""))); + softwareManagement.createSoftwareModule(new JpaSoftwareModule(osType, "deleted", "deleted", null, ""))); assertThat(softwareManagement.countSoftwareModulesAll()).as("Expected to find the following number of modules:") .isEqualTo(2); @@ -317,13 +319,13 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { @Description("Counts for software modules by type.") public void countSoftwareModulesByType() { // found in test - softwareManagement.createSoftwareModule(new SoftwareModule(osType, "one", "one", null, "")); - softwareManagement.createSoftwareModule(new SoftwareModule(osType, "two", "two", null, "")); + softwareManagement.createSoftwareModule(new JpaSoftwareModule(osType, "one", "one", null, "")); + softwareManagement.createSoftwareModule(new JpaSoftwareModule(osType, "two", "two", null, "")); // ignored softwareManagement.deleteSoftwareModule( - softwareManagement.createSoftwareModule(new SoftwareModule(osType, "deleted", "deleted", null, ""))); - softwareManagement.createSoftwareModule(new SoftwareModule(appType, "three", "3.0.2", null, "")); + softwareManagement.createSoftwareModule(new JpaSoftwareModule(osType, "deleted", "deleted", null, ""))); + softwareManagement.createSoftwareModule(new JpaSoftwareModule(appType, "three", "3.0.2", null, "")); assertThat(softwareManagement.countSoftwareModulesByType(osType)) .as("Expected to find the following number of modules:").isEqualTo(2); @@ -336,7 +338,7 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { appType); SoftwareModuleType type = softwareManagement.createSoftwareModuleType( - new SoftwareModuleType("bundle", "OSGi Bundle", "fancy stuff", Integer.MAX_VALUE)); + new JpaSoftwareModuleType("bundle", "OSGi Bundle", "fancy stuff", Integer.MAX_VALUE)); assertThat(softwareManagement.findSoftwareModuleTypesAll(pageReq)).hasSize(4).contains(osType, runtimeType, appType, type); @@ -345,23 +347,25 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { softwareManagement.deleteSoftwareModuleType(type); assertThat(softwareManagement.findSoftwareModuleTypesAll(pageReq)).hasSize(3).contains(osType, runtimeType, appType); - assertThat(softwareModuleTypeRepository.findAll()).hasSize(3).contains(osType, runtimeType, appType); + assertThat(softwareModuleTypeRepository.findAll()).hasSize(3).contains((JpaSoftwareModuleType) osType, + (JpaSoftwareModuleType) runtimeType, (JpaSoftwareModuleType) appType); type = softwareManagement.createSoftwareModuleType( - new SoftwareModuleType("bundle2", "OSGi Bundle2", "fancy stuff", Integer.MAX_VALUE)); + new JpaSoftwareModuleType("bundle2", "OSGi Bundle2", "fancy stuff", Integer.MAX_VALUE)); assertThat(softwareManagement.findSoftwareModuleTypesAll(pageReq)).hasSize(4).contains(osType, runtimeType, appType, type); softwareManagement - .createSoftwareModule(new SoftwareModule(type, "Test SM", "1.0", "cool module", "from meeee")); + .createSoftwareModule(new JpaSoftwareModule(type, "Test SM", "1.0", "cool module", "from meeee")); // delete assigned softwareManagement.deleteSoftwareModuleType(type); assertThat(softwareManagement.findSoftwareModuleTypesAll(pageReq)).hasSize(3).contains(osType, runtimeType, appType); - assertThat(softwareModuleTypeRepository.findAll()).hasSize(4).contains(osType, runtimeType, appType, + assertThat(softwareModuleTypeRepository.findAll()).hasSize(4).contains((JpaSoftwareModuleType) osType, + (JpaSoftwareModuleType) runtimeType, (JpaSoftwareModuleType) appType, softwareModuleTypeRepository.findOne(type.getId())); } @@ -397,7 +401,7 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { // Init DistributionSet final DistributionSet disSet = distributionSetManagement - .createDistributionSet(new DistributionSet("ds1", "v1.0", "test ds", standardDsType, null)); + .createDistributionSet(new JpaDistributionSet("ds1", "v1.0", "test ds", standardDsType, null)); // [STEP1]: Create SoftwareModuleX with ArtifactX SoftwareModule assignedModule = createSoftwareModuleWithArtifacts(osType, "moduleX", "3.0.2", 2); @@ -431,9 +435,9 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { public void softDeleteOfHistoricalAssignedArtifact() { // Init target and DistributionSet - final Target target = targetManagement.createTarget(new Target("test123")); + final Target target = targetManagement.createTarget(new JpaTarget("test123")); final DistributionSet disSet = distributionSetManagement - .createDistributionSet(new DistributionSet("ds1", "v1.0", "test ds", standardDsType, null)); + .createDistributionSet(new JpaDistributionSet("ds1", "v1.0", "test ds", standardDsType, null)); // [STEP1]: Create SoftwareModuleX and include the new ArtifactX SoftwareModule assignedModule = createSoftwareModuleWithArtifacts(osType, "moduleX", "3.0.2", 2); @@ -525,11 +529,11 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { // Init artifact binary data, target and DistributionSets final byte[] source = RandomUtils.nextBytes(1024); - final Target target = targetManagement.createTarget(new Target("test123")); + final Target target = targetManagement.createTarget(new JpaTarget("test123")); final DistributionSet disSetX = distributionSetManagement - .createDistributionSet(new DistributionSet("dsX", "v1.0", "test dsX", standardDsType, null)); + .createDistributionSet(new JpaDistributionSet("dsX", "v1.0", "test dsX", standardDsType, null)); final DistributionSet disSetY = distributionSetManagement - .createDistributionSet(new DistributionSet("dsY", "v1.0", "test dsY", standardDsType, null)); + .createDistributionSet(new JpaDistributionSet("dsY", "v1.0", "test dsY", standardDsType, null)); // [STEP1]: Create SoftwareModuleX and add a new ArtifactX SoftwareModule moduleX = createSoftwareModuleWithArtifacts(osType, "modulex", "v1.0", 0); @@ -587,8 +591,8 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { final long countSoftwareModule = softwareModuleRepository.count(); // create SoftwareModule - SoftwareModule softwareModule = softwareManagement - .createSoftwareModule(new SoftwareModule(type, name, version, "description of artifact " + name, "")); + SoftwareModule softwareModule = softwareManagement.createSoftwareModule( + new JpaSoftwareModule(type, name, version, "description of artifact " + name, "")); for (int i = 0; i < numberArtifacts; i++) { artifactManagement.createLocalArtifact(new RandomGeneratedInputStream(5 * 1024), softwareModule.getId(), @@ -617,7 +621,7 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { for (final Artifact result : results) { assertThat(result.getId()).isNotNull(); assertThat(operations.findOne(new Query() - .addCriteria(Criteria.where("filename").is(((LocalArtifact) result).getGridFsFileName())))) + .addCriteria(Criteria.where("filename").is(((JpaLocalArtifact) result).getGridFsFileName())))) .isNotNull(); } } @@ -625,7 +629,7 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { private void assertArtfiactNull(final Artifact... results) { for (final Artifact result : results) { assertThat(operations.findOne(new Query() - .addCriteria(Criteria.where("filename").is(((LocalArtifact) result).getGridFsFileName())))) + .addCriteria(Criteria.where("filename").is(((JpaLocalArtifact) result).getGridFsFileName())))) .isNull(); } } @@ -635,28 +639,28 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { public void findSoftwareModuleOrderByDistributionModuleNameAscModuleVersionAsc() { // test meta data final SoftwareModuleType testType = softwareManagement - .createSoftwareModuleType(new SoftwareModuleType("thetype", "thename", "desc", 100)); + .createSoftwareModuleType(new JpaSoftwareModuleType("thetype", "thename", "desc", 100)); final DistributionSetType testDsType = distributionSetManagement - .createDistributionSetType(new DistributionSetType("key", "name", "desc").addMandatoryModuleType(osType) - .addOptionalModuleType(testType)); + .createDistributionSetType(new JpaDistributionSetType("key", "name", "desc") + .addMandatoryModuleType(osType).addOptionalModuleType(testType)); // found in test final SoftwareModule unassigned = softwareManagement - .createSoftwareModule(new SoftwareModule(testType, "asis", "found", null, "")); + .createSoftwareModule(new JpaSoftwareModule(testType, "asis", "found", null, "")); final SoftwareModule one = softwareManagement - .createSoftwareModule(new SoftwareModule(testType, "found", "b", null, "")); + .createSoftwareModule(new JpaSoftwareModule(testType, "found", "b", null, "")); final SoftwareModule two = softwareManagement - .createSoftwareModule(new SoftwareModule(testType, "found", "c", null, "")); + .createSoftwareModule(new JpaSoftwareModule(testType, "found", "c", null, "")); final SoftwareModule differentName = softwareManagement - .createSoftwareModule(new SoftwareModule(testType, "differentname", "d", null, "")); + .createSoftwareModule(new JpaSoftwareModule(testType, "differentname", "d", null, "")); // ignored final SoftwareModule deleted = softwareManagement - .createSoftwareModule(new SoftwareModule(testType, "deleted", "deleted", null, "")); + .createSoftwareModule(new JpaSoftwareModule(testType, "deleted", "deleted", null, "")); final SoftwareModule four = softwareManagement - .createSoftwareModule(new SoftwareModule(osType, "sdfjhsdj", "e", null, "")); + .createSoftwareModule(new JpaSoftwareModule(osType, "sdfjhsdj", "e", null, "")); - final DistributionSet set = distributionSetManagement.createDistributionSet(new DistributionSet("set", "1", + final DistributionSet set = distributionSetManagement.createDistributionSet(new JpaDistributionSet("set", "1", "desc", testDsType, Lists.newArrayList(one, two, deleted, four, differentName))); softwareManagement.deleteSoftwareModule(deleted); @@ -664,22 +668,22 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { assertThat(softwareManagement.findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(pageReq, set.getId(), "found", testType).getContent()) .as("Found modules with given name, given module type and the assigned ones first") - .containsExactly(new CustomSoftwareModule(one, true), new CustomSoftwareModule(two, true), - new CustomSoftwareModule(unassigned, false)); + .containsExactly(new AssignedSoftwareModule(one, true), new AssignedSoftwareModule(two, true), + new AssignedSoftwareModule(unassigned, false)); // with filter on module type only assertThat(softwareManagement.findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(pageReq, set.getId(), null, testType).getContent()) .as("Found modules with given module type and the assigned ones first").containsExactly( - new CustomSoftwareModule(differentName, true), new CustomSoftwareModule(one, true), - new CustomSoftwareModule(two, true), new CustomSoftwareModule(unassigned, false)); + new AssignedSoftwareModule(differentName, true), new AssignedSoftwareModule(one, true), + new AssignedSoftwareModule(two, true), new AssignedSoftwareModule(unassigned, false)); // without any filter assertThat(softwareManagement.findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(pageReq, set.getId(), null, null).getContent()).as("Found modules with the assigned ones first").containsExactly( - new CustomSoftwareModule(differentName, true), new CustomSoftwareModule(one, true), - new CustomSoftwareModule(two, true), new CustomSoftwareModule(four, true), - new CustomSoftwareModule(unassigned, false)); + new AssignedSoftwareModule(differentName, true), new AssignedSoftwareModule(one, true), + new AssignedSoftwareModule(two, true), new AssignedSoftwareModule(four, true), + new AssignedSoftwareModule(unassigned, false)); } @Test @@ -688,26 +692,26 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { // test meta data final SoftwareModuleType testType = softwareManagement - .createSoftwareModuleType(new SoftwareModuleType("thetype", "thename", "desc", 100)); + .createSoftwareModuleType(new JpaSoftwareModuleType("thetype", "thename", "desc", 100)); final DistributionSetType testDsType = distributionSetManagement - .createDistributionSetType(new DistributionSetType("key", "name", "desc").addMandatoryModuleType(osType) - .addOptionalModuleType(testType)); + .createDistributionSetType(new JpaDistributionSetType("key", "name", "desc") + .addMandatoryModuleType(osType).addOptionalModuleType(testType)); // test modules - softwareManagement.createSoftwareModule(new SoftwareModule(testType, "asis", "found", null, "")); + softwareManagement.createSoftwareModule(new JpaSoftwareModule(testType, "asis", "found", null, "")); final SoftwareModule one = softwareManagement - .createSoftwareModule(new SoftwareModule(testType, "found", "b", null, "")); + .createSoftwareModule(new JpaSoftwareModule(testType, "found", "b", null, "")); final SoftwareModule two = softwareManagement - .createSoftwareModule(new SoftwareModule(testType, "found", "c", null, "")); + .createSoftwareModule(new JpaSoftwareModule(testType, "found", "c", null, "")); final SoftwareModule differentName = softwareManagement - .createSoftwareModule(new SoftwareModule(testType, "differentname", "d", null, "")); + .createSoftwareModule(new JpaSoftwareModule(testType, "differentname", "d", null, "")); final SoftwareModule four = softwareManagement - .createSoftwareModule(new SoftwareModule(osType, "found", "3.0.2", null, "")); + .createSoftwareModule(new JpaSoftwareModule(osType, "found", "3.0.2", null, "")); // one soft deleted final SoftwareModule deleted = softwareManagement - .createSoftwareModule(new SoftwareModule(testType, "deleted", "deleted", null, "")); - distributionSetManagement.createDistributionSet(new DistributionSet("set", "1", "desc", testDsType, + .createSoftwareModule(new JpaSoftwareModule(testType, "deleted", "deleted", null, "")); + distributionSetManagement.createDistributionSet(new JpaDistributionSet("set", "1", "desc", testDsType, Lists.newArrayList(one, two, deleted, four, differentName))); softwareManagement.deleteSoftwareModule(deleted); @@ -724,18 +728,18 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { @Description("Verfies that all undeleted software modules are found in the repository.") public void countSoftwareModuleTypesAll() { final SoftwareModuleType testType = softwareManagement - .createSoftwareModuleType(new SoftwareModuleType("thetype", "thename", "desc", 100)); + .createSoftwareModuleType(new JpaSoftwareModuleType("thetype", "thename", "desc", 100)); final DistributionSetType testDsType = distributionSetManagement - .createDistributionSetType(new DistributionSetType("key", "name", "desc").addMandatoryModuleType(osType) - .addOptionalModuleType(testType)); + .createDistributionSetType(new JpaDistributionSetType("key", "name", "desc") + .addMandatoryModuleType(osType).addOptionalModuleType(testType)); final SoftwareModule four = softwareManagement - .createSoftwareModule(new SoftwareModule(osType, "found", "3.0.2", null, "")); + .createSoftwareModule(new JpaSoftwareModule(osType, "found", "3.0.2", null, "")); // one soft deleted final SoftwareModule deleted = softwareManagement - .createSoftwareModule(new SoftwareModule(testType, "deleted", "deleted", null, "")); + .createSoftwareModule(new JpaSoftwareModule(testType, "deleted", "deleted", null, "")); distributionSetManagement.createDistributionSet( - new DistributionSet("set", "1", "desc", testDsType, Lists.newArrayList(deleted, four))); + new JpaDistributionSet("set", "1", "desc", testDsType, Lists.newArrayList(deleted, four))); softwareManagement.deleteSoftwareModule(deleted); assertThat(softwareManagement.countSoftwareModulesAll()).as("Number of undeleted modules").isEqualTo(1); @@ -746,8 +750,8 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { @Description("Checks that software module typeis found based on given name.") public void findSoftwareModuleTypeByName() { final SoftwareModuleType found = softwareManagement - .createSoftwareModuleType(new SoftwareModuleType("thetype", "thename", "desc", 100)); - softwareManagement.createSoftwareModuleType(new SoftwareModuleType("thetype2", "anothername", "desc", 100)); + .createSoftwareModuleType(new JpaSoftwareModuleType("thetype", "thename", "desc", 100)); + softwareManagement.createSoftwareModuleType(new JpaSoftwareModuleType("thetype2", "anothername", "desc", 100)); assertThat(softwareManagement.findSoftwareModuleTypeByName("thename")).as("Type with given name") .isEqualTo(found); @@ -757,7 +761,7 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { @Description("Verfies that it is not possible to create a type that alrady exists.") public void createSoftwareModuleTypeFailsWithExistingEntity() { final SoftwareModuleType created = softwareManagement - .createSoftwareModuleType(new SoftwareModuleType("thetype", "thename", "desc", 100)); + .createSoftwareModuleType(new JpaSoftwareModuleType("thetype", "thename", "desc", 100)); try { softwareManagement.createSoftwareModuleType(created); fail("should not have worked as module type already exists"); @@ -771,10 +775,10 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { @Description("Verfies that it is not possible to create a list of types where one already exists.") public void createSoftwareModuleTypesFailsWithExistingEntity() { final SoftwareModuleType created = softwareManagement - .createSoftwareModuleType(new SoftwareModuleType("thetype", "thename", "desc", 100)); + .createSoftwareModuleType(new JpaSoftwareModuleType("thetype", "thename", "desc", 100)); try { softwareManagement.createSoftwareModuleType( - Lists.newArrayList(created, new SoftwareModuleType("anothertype", "anothername", "desc", 100))); + Lists.newArrayList(created, new JpaSoftwareModuleType("anothertype", "anothername", "desc", 100))); fail("should not have worked as module type already exists"); } catch (final EntityAlreadyExistsException e) { @@ -784,9 +788,9 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { @Test @Description("Verfies that multiple types are created as requested.") public void createMultipleoftwareModuleTypes() { - final List created = softwareManagement - .createSoftwareModuleType(Lists.newArrayList(new SoftwareModuleType("thetype", "thename", "desc", 100), - new SoftwareModuleType("thetype2", "thename2", "desc2", 100))); + final List created = softwareManagement.createSoftwareModuleType( + Lists.newArrayList(new JpaSoftwareModuleType("thetype", "thename", "desc", 100), + new JpaSoftwareModuleType("thetype2", "thename2", "desc2", 100))); assertThat(created.size()).as("Number of created types").isEqualTo(2); assertThat(softwareManagement.countSoftwareModuleTypesAll()).as("Number of types in repository").isEqualTo(5); @@ -797,23 +801,23 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { public void findSoftwareModuleByAssignedTo() { // test meta data final SoftwareModuleType testType = softwareManagement - .createSoftwareModuleType(new SoftwareModuleType("thetype", "thename", "desc", 100)); + .createSoftwareModuleType(new JpaSoftwareModuleType("thetype", "thename", "desc", 100)); final DistributionSetType testDsType = distributionSetManagement - .createDistributionSetType(new DistributionSetType("key", "name", "desc").addMandatoryModuleType(osType) - .addOptionalModuleType(testType)); + .createDistributionSetType(new JpaDistributionSetType("key", "name", "desc") + .addMandatoryModuleType(osType).addOptionalModuleType(testType)); // test modules - softwareManagement.createSoftwareModule(new SoftwareModule(testType, "asis", "found", null, "")); + softwareManagement.createSoftwareModule(new JpaSoftwareModule(testType, "asis", "found", null, "")); final SoftwareModule one = softwareManagement - .createSoftwareModule(new SoftwareModule(testType, "found", "b", null, "")); + .createSoftwareModule(new JpaSoftwareModule(testType, "found", "b", null, "")); final SoftwareModule two = softwareManagement - .createSoftwareModule(new SoftwareModule(testType, "found", "c", null, "")); + .createSoftwareModule(new JpaSoftwareModule(testType, "found", "c", null, "")); // one soft deleted final SoftwareModule deleted = softwareManagement - .createSoftwareModule(new SoftwareModule(testType, "deleted", "deleted", null, "")); + .createSoftwareModule(new JpaSoftwareModule(testType, "deleted", "deleted", null, "")); final DistributionSet set = distributionSetManagement.createDistributionSet( - new DistributionSet("set", "1", "desc", testDsType, Lists.newArrayList(one, deleted))); + new JpaDistributionSet("set", "1", "desc", testDsType, Lists.newArrayList(one, deleted))); softwareManagement.deleteSoftwareModule(deleted); assertThat(softwareManagement.findSoftwareModuleByAssignedTo(pageReq, set).getContent()) @@ -831,13 +835,13 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { final String knownValue2 = "myKnownValue2"; final SoftwareModule ah = softwareManagement - .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); assertThat(ah.getOptLockRevision()).isEqualTo(1L); - final SoftwareModuleMetadata swMetadata1 = new SoftwareModuleMetadata(knownKey1, ah, knownValue1); + final SoftwareModuleMetadata swMetadata1 = new JpaSoftwareModuleMetadata(knownKey1, ah, knownValue1); - final SoftwareModuleMetadata swMetadata2 = new SoftwareModuleMetadata(knownKey2, ah, knownValue2); + final SoftwareModuleMetadata swMetadata2 = new JpaSoftwareModuleMetadata(knownKey2, ah, knownValue2); final List softwareModuleMetadata = softwareManagement .createSoftwareModuleMetadata(Lists.newArrayList(swMetadata1, swMetadata2)); @@ -848,7 +852,7 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { assertThat(softwareModuleMetadata).hasSize(2); assertThat(softwareModuleMetadata.get(0)).isNotNull(); assertThat(softwareModuleMetadata.get(0).getValue()).isEqualTo(knownValue1); - assertThat(softwareModuleMetadata.get(0).getId().getKey()).isEqualTo(knownKey1); + assertThat(((JpaSoftwareModuleMetadata) softwareModuleMetadata.get(0)).getId().getKey()).isEqualTo(knownKey1); assertThat(softwareModuleMetadata.get(0).getSoftwareModule().getId()).isEqualTo(ah.getId()); } @@ -861,12 +865,12 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { final String knownValue2 = "myKnownValue2"; final SoftwareModule ah = softwareManagement - .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); - softwareManagement.createSoftwareModuleMetadata(new SoftwareModuleMetadata(knownKey1, ah, knownValue1)); + softwareManagement.createSoftwareModuleMetadata(new JpaSoftwareModuleMetadata(knownKey1, ah, knownValue1)); try { - softwareManagement.createSoftwareModuleMetadata(new SoftwareModuleMetadata(knownKey1, ah, knownValue2)); + softwareManagement.createSoftwareModuleMetadata(new JpaSoftwareModuleMetadata(knownKey1, ah, knownValue2)); fail("should not have worked as module metadata already exists"); } catch (final EntityAlreadyExistsException e) { @@ -883,13 +887,13 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { // create a base software module final SoftwareModule ah = softwareManagement - .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); // initial opt lock revision must be 1 assertThat(ah.getOptLockRevision()).isEqualTo(1L); // create an software module meta data entry final List softwareModuleMetadata = softwareManagement.createSoftwareModuleMetadata( - Collections.singleton(new SoftwareModuleMetadata(knownKey, ah, knownValue))); + Collections.singleton(new JpaSoftwareModuleMetadata(knownKey, ah, knownValue))); assertThat(softwareModuleMetadata).hasSize(1); // base software module should have now the opt lock revision one // because we are modifying the @@ -915,7 +919,7 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { // verify updated meta data contains the updated value assertThat(updated).isNotNull(); assertThat(updated.getValue()).isEqualTo(knownUpdateValue); - assertThat(updated.getId().getKey()).isEqualTo(knownKey); + assertThat(((JpaSoftwareModuleMetadata) updated).getId().getKey()).isEqualTo(knownKey); assertThat(updated.getSoftwareModule().getId()).isEqualTo(ah.getId()); } @@ -926,16 +930,16 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { final String knownValue1 = "myKnownValue1"; SoftwareModule ah = softwareManagement - .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); - ah = softwareManagement.createSoftwareModuleMetadata(new SoftwareModuleMetadata(knownKey1, ah, knownValue1)) + ah = softwareManagement.createSoftwareModuleMetadata(new JpaSoftwareModuleMetadata(knownKey1, ah, knownValue1)) .getSoftwareModule(); assertThat(softwareManagement.findSoftwareModuleById(ah.getId()).getMetadata()) .as("Contains the created metadata element") - .containsExactly(new SoftwareModuleMetadata(knownKey1, ah, knownValue1)); + .containsExactly(new JpaSoftwareModuleMetadata(knownKey1, ah, knownValue1)); - softwareManagement.deleteSoftwareModuleMetadata(new SwMetadataCompositeKey(ah, knownKey1)); + softwareManagement.deleteSoftwareModuleMetadata(ah, knownKey1); assertThat(softwareManagement.findSoftwareModuleById(ah.getId()).getMetadata()).as("Metadata elemenets are") .isEmpty(); } @@ -947,13 +951,13 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { final String knownValue1 = "myKnownValue1"; SoftwareModule ah = softwareManagement - .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); - ah = softwareManagement.createSoftwareModuleMetadata(new SoftwareModuleMetadata(knownKey1, ah, knownValue1)) + ah = softwareManagement.createSoftwareModuleMetadata(new JpaSoftwareModuleMetadata(knownKey1, ah, knownValue1)) .getSoftwareModule(); try { - softwareManagement.findSoftwareModuleMetadata(new SwMetadataCompositeKey(ah, "doesnotexist")); + softwareManagement.findSoftwareModuleMetadata(ah, "doesnotexist"); fail("should not have worked as module metadata with that key does not exist"); } catch (final EntityNotFoundException e) { @@ -965,20 +969,20 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { public void findAllSoftwareModuleMetadataBySwId() { SoftwareModule sw1 = softwareManagement - .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); SoftwareModule sw2 = softwareManagement - .createSoftwareModule(new SoftwareModule(osType, "os", "1.0.1", null, "")); + .createSoftwareModule(new JpaSoftwareModule(osType, "os", "1.0.1", null, "")); for (int index = 0; index < 10; index++) { sw1 = softwareManagement - .createSoftwareModuleMetadata(new SoftwareModuleMetadata("key" + index, sw1, "value" + index)) + .createSoftwareModuleMetadata(new JpaSoftwareModuleMetadata("key" + index, sw1, "value" + index)) .getSoftwareModule(); } for (int index = 0; index < 20; index++) { sw2 = softwareManagement - .createSoftwareModuleMetadata(new SoftwareModuleMetadata("key" + index, sw2, "value" + index)) + .createSoftwareModuleMetadata(new JpaSoftwareModuleMetadata("key" + index, sw2, "value" + index)) .getSoftwareModule(); } diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/SystemManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SystemManagementTest.java similarity index 85% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/SystemManagementTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SystemManagementTest.java index 1a1632d32..e697f65d8 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/SystemManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SystemManagementTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import static org.fest.assertions.api.Assertions.assertThat; @@ -14,13 +14,11 @@ import java.io.ByteArrayInputStream; import java.util.List; import java.util.Random; -import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB; -import org.eclipse.hawkbit.TestDataUtil; -import org.eclipse.hawkbit.WithSpringAuthorityRule; -import org.eclipse.hawkbit.report.model.TenantUsage; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; 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.report.model.TenantUsage; +import org.eclipse.hawkbit.repository.util.WithSpringAuthorityRule; import org.junit.Test; import ru.yandex.qatools.allure.annotations.Description; @@ -29,7 +27,7 @@ import ru.yandex.qatools.allure.annotations.Stories; @Features("Component Tests - Repository") @Stories("System Management") -public class SystemManagementTest extends AbstractIntegrationTestWithMongoDB { +public class SystemManagementTest extends AbstractJpaIntegrationTestWithMongoDB { @Test @Description("Ensures that findTenants returns all tenants and not only restricted to the tenant which currently is logged in") @@ -111,8 +109,8 @@ public class SystemManagementTest extends AbstractIntegrationTestWithMongoDB { final List createdTargets = createTestTargets(targets); if (updates > 0) { for (int x = 0; x < updates; x++) { - final DistributionSet ds = TestDataUtil.generateDistributionSet("to be deployed" + x, - softwareManagement, distributionSetManagement, true); + final DistributionSet ds = testdataFactory.createDistributionSet("to be deployed" + x, + true); deploymentManagement.assignDistributionSet(ds, createdTargets); } @@ -128,11 +126,11 @@ public class SystemManagementTest extends AbstractIntegrationTestWithMongoDB { private List createTestTargets(final int targets) { return targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(targets, "testTargetOfTenant", "testTargetOfTenant")); + .createTargets(testdataFactory.generateTargets(targets, "testTargetOfTenant", "testTargetOfTenant")); } private void createTestArtifact(final byte[] random) { - SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", + JpaSoftwareModule sm = new JpaSoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", "version 1", null, null); sm = softwareModuleRepository.save(sm); @@ -140,8 +138,7 @@ public class SystemManagementTest extends AbstractIntegrationTestWithMongoDB { } private void createDeletedTestArtifact(final byte[] random) { - final DistributionSet ds = TestDataUtil.generateDistributionSet("deleted garbage", softwareManagement, - distributionSetManagement, true); + final DistributionSet ds = testdataFactory.createDistributionSet("deleted garbage", true); ds.getModules().stream().forEach(module -> { artifactManagement.createLocalArtifact(new ByteArrayInputStream(random), module.getId(), "file1", false); softwareManagement.deleteSoftwareModule(module); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TagManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TagManagementTest.java similarity index 82% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TagManagementTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TagManagementTest.java index 4c6af0d83..5f2fe3fbd 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TagManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TagManagementTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import static org.fest.assertions.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; @@ -14,14 +14,16 @@ import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.List; import java.util.stream.Collectors; -import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.TestDataUtil; -import org.eclipse.hawkbit.repository.DistributionSetFilter.DistributionSetFilterBuilder; +import org.eclipse.hawkbit.repository.TagManagement; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag; import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.repository.model.DistributionSetFilter.DistributionSetFilterBuilder; import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult; import org.eclipse.hawkbit.repository.model.Tag; @@ -44,7 +46,7 @@ import ru.yandex.qatools.allure.annotations.Stories; */ @Features("Component Tests - Repository") @Stories("Tag Management") -public class TagManagementTest extends AbstractIntegrationTest { +public class TagManagementTest extends AbstractJpaIntegrationTest { public TagManagementTest() { LOG = LoggerFactory.getLogger(TagManagementTest.class); } @@ -57,26 +59,19 @@ public class TagManagementTest extends AbstractIntegrationTest { @Test @Description("Full DS tag lifecycle tested. Create tags, assign them to sets and delete the tags.") public void createAndAssignAndDeleteDistributionSetTags() { - final List dsAs = TestDataUtil.generateDistributionSets("DS-A", 20, softwareManagement, - distributionSetManagement); - final List dsBs = TestDataUtil.generateDistributionSets("DS-B", 10, softwareManagement, - distributionSetManagement); - final List dsCs = TestDataUtil.generateDistributionSets("DS-C", 25, softwareManagement, - distributionSetManagement); - final List dsABs = TestDataUtil.generateDistributionSets("DS-AB", 5, softwareManagement, - distributionSetManagement); - final List dsACs = TestDataUtil.generateDistributionSets("DS-AC", 11, softwareManagement, - distributionSetManagement); - final List dsBCs = TestDataUtil.generateDistributionSets("DS-BC", 13, softwareManagement, - distributionSetManagement); - final List dsABCs = TestDataUtil.generateDistributionSets("DS-ABC", 9, softwareManagement, - distributionSetManagement); + final Collection dsAs = testdataFactory.createDistributionSets("DS-A", 20); + final Collection dsBs = testdataFactory.createDistributionSets("DS-B", 10); + final Collection dsCs = testdataFactory.createDistributionSets("DS-C", 25); + final Collection dsABs = testdataFactory.createDistributionSets("DS-AB", 5); + final Collection dsACs = testdataFactory.createDistributionSets("DS-AC", 11); + final Collection dsBCs = testdataFactory.createDistributionSets("DS-BC", 13); + final Collection dsABCs = testdataFactory.createDistributionSets("DS-ABC", 9); - final DistributionSetTag tagA = tagManagement.createDistributionSetTag(new DistributionSetTag("A")); - final DistributionSetTag tagB = tagManagement.createDistributionSetTag(new DistributionSetTag("B")); - final DistributionSetTag tagC = tagManagement.createDistributionSetTag(new DistributionSetTag("C")); - final DistributionSetTag tagX = tagManagement.createDistributionSetTag(new DistributionSetTag("X")); - final DistributionSetTag tagY = tagManagement.createDistributionSetTag(new DistributionSetTag("Y")); + final DistributionSetTag tagA = tagManagement.createDistributionSetTag(new JpaDistributionSetTag("A")); + final DistributionSetTag tagB = tagManagement.createDistributionSetTag(new JpaDistributionSetTag("B")); + final DistributionSetTag tagC = tagManagement.createDistributionSetTag(new JpaDistributionSetTag("C")); + final DistributionSetTag tagX = tagManagement.createDistributionSetTag(new JpaDistributionSetTag("X")); + final DistributionSetTag tagY = tagManagement.createDistributionSetTag(new JpaDistributionSetTag("Y")); distributionSetManagement.toggleTagAssignment(dsAs, tagA); distributionSetManagement.toggleTagAssignment(dsBs, tagB); @@ -167,20 +162,18 @@ public class TagManagementTest extends AbstractIntegrationTest { @Description("Verifies the toogle mechanism by means on assigning tag if at least on DS in the list does not have" + "the tag yet. Unassign if all of them have the tag already.") public void assignAndUnassignDistributionSetTags() { - final List groupA = TestDataUtil.generateDistributionSets(20, softwareManagement, - distributionSetManagement); - final List groupB = TestDataUtil.generateDistributionSets("unassigned", 20, softwareManagement, - distributionSetManagement); + final Collection groupA = testdataFactory.createDistributionSets(20); + final Collection groupB = testdataFactory.createDistributionSets("unassigned", 20); final DistributionSetTag tag = tagManagement - .createDistributionSetTag(new DistributionSetTag("tag1", "tagdesc1", "")); + .createDistributionSetTag(new JpaDistributionSetTag("tag1", "tagdesc1", "")); // toggle A only -> A is now assigned DistributionSetTagAssignmentResult result = distributionSetManagement.toggleTagAssignment(groupA, tag); assertThat(result.getAlreadyAssigned()).isEqualTo(0); assertThat(result.getAssigned()).isEqualTo(20); - assertThat(result.getAssignedEntity()).containsAll(distributionSetManagement.findDistributionSetListWithDetails( - groupA.stream().map(set -> set.getId()).collect(Collectors.toList()))); + assertThat(result.getAssignedEntity()).containsAll(distributionSetManagement + .findDistributionSetsAll(groupA.stream().map(set -> set.getId()).collect(Collectors.toList()))); assertThat(result.getUnassigned()).isEqualTo(0); assertThat(result.getUnassignedEntity()).isEmpty(); assertThat(result.getDistributionSetTag()).isEqualTo(tag); @@ -189,8 +182,8 @@ public class TagManagementTest extends AbstractIntegrationTest { result = distributionSetManagement.toggleTagAssignment(concat(groupA, groupB), tag); assertThat(result.getAlreadyAssigned()).isEqualTo(20); assertThat(result.getAssigned()).isEqualTo(20); - assertThat(result.getAssignedEntity()).containsAll(distributionSetManagement.findDistributionSetListWithDetails( - groupB.stream().map(set -> set.getId()).collect(Collectors.toList()))); + assertThat(result.getAssignedEntity()).containsAll(distributionSetManagement + .findDistributionSetsAll(groupB.stream().map(set -> set.getId()).collect(Collectors.toList()))); assertThat(result.getUnassigned()).isEqualTo(0); assertThat(result.getUnassignedEntity()).isEmpty(); assertThat(result.getDistributionSetTag()).isEqualTo(tag); @@ -201,7 +194,7 @@ public class TagManagementTest extends AbstractIntegrationTest { assertThat(result.getAssigned()).isEqualTo(0); assertThat(result.getAssignedEntity()).isEmpty(); assertThat(result.getUnassigned()).isEqualTo(40); - assertThat(result.getUnassignedEntity()).containsAll(distributionSetManagement.findDistributionSetListWithDetails( + assertThat(result.getUnassignedEntity()).containsAll(distributionSetManagement.findDistributionSetsAll( concat(groupB, groupA).stream().map(set -> set.getId()).collect(Collectors.toList()))); assertThat(result.getDistributionSetTag()).isEqualTo(tag); @@ -211,10 +204,10 @@ public class TagManagementTest extends AbstractIntegrationTest { @Description("Verifies the toogle mechanism by means on assigning tag if at least on target in the list does not have" + "the tag yet. Unassign if all of them have the tag already.") public void assignAndUnassignTargetTags() { - final List groupA = targetManagement.createTargets(TestDataUtil.generateTargets(20, "")); - final List groupB = targetManagement.createTargets(TestDataUtil.generateTargets(20, "groupb")); + final List groupA = targetManagement.createTargets(testdataFactory.generateTargets(20, "")); + final List groupB = targetManagement.createTargets(testdataFactory.generateTargets(20, "groupb")); - final TargetTag tag = tagManagement.createTargetTag(new TargetTag("tag1", "tagdesc1", "")); + final TargetTag tag = tagManagement.createTargetTag(new JpaTargetTag("tag1", "tagdesc1", "")); // toggle A only -> A is now assigned TargetTagAssignmentResult result = targetManagement.toggleTagAssignment(groupA, tag); @@ -249,7 +242,7 @@ public class TagManagementTest extends AbstractIntegrationTest { } @SafeVarargs - private final List concat(final List... targets) { + private final Collection concat(final Collection... targets) { final List result = new ArrayList<>(); Arrays.asList(targets).forEach(result::addAll); return result; @@ -258,16 +251,16 @@ public class TagManagementTest extends AbstractIntegrationTest { @Test @Description("Ensures that all tags are retrieved through repository.") public void findAllTargetTags() { - final List tags = createTargetsWithTags(); + final List tags = createTargetsWithTags(); - assertThat(targetTagRepository.findAll()).isEqualTo(tagManagement.findAllTargetTags()).isEqualTo(tags) + assertThat(targetTagRepository.findAll()).isEqualTo(targetTagRepository.findAll()).isEqualTo(tags) .as("Wrong tag size").hasSize(20); } @Test @Description("Ensures that a created tag is persisted in the repository as defined.") public void createTargetTag() { - final Tag tag = tagManagement.createTargetTag(new TargetTag("kai1", "kai2", "colour")); + final Tag tag = tagManagement.createTargetTag(new JpaTargetTag("kai1", "kai2", "colour")); assertThat(targetTagRepository.findByNameEquals("kai1").getDescription()).as("wrong tag ed").isEqualTo("kai2"); assertThat(tagManagement.findTargetTag("kai1").getColour()).as("wrong tag found").isEqualTo("colour"); @@ -279,7 +272,7 @@ public class TagManagementTest extends AbstractIntegrationTest { public void deleteTargetTas() { // create test data - final Iterable tags = createTargetsWithTags(); + final Iterable tags = createTargetsWithTags(); final TargetTag toDelete = tags.iterator().next(); for (final Target target : targetRepository.findAll()) { @@ -296,13 +289,13 @@ public class TagManagementTest extends AbstractIntegrationTest { .doesNotContain(toDelete); } assertThat(targetTagRepository.findOne(toDelete.getId())).as("No tag should be found").isNull(); - assertThat(tagManagement.findAllTargetTags()).as("Wrong target tag size").hasSize(19); + assertThat(targetTagRepository.findAll()).as("Wrong target tag size").hasSize(19); } @Test @Description("Tests the name update of a target tag.") public void updateTargetTag() { - final List tags = createTargetsWithTags(); + final List tags = createTargetsWithTags(); // change data final TargetTag savedAssigned = tags.iterator().next(); @@ -312,7 +305,7 @@ public class TagManagementTest extends AbstractIntegrationTest { tagManagement.updateTargetTag(savedAssigned); // check data - assertThat(tagManagement.findAllTargetTags()).as("Wrong target tag size").hasSize(tags.size()); + assertThat(targetTagRepository.findAll()).as("Wrong target tag size").hasSize(tags.size()); assertThat(targetTagRepository.findOne(savedAssigned.getId()).getName()).as("wrong target tag is saved") .isEqualTo("test123"); assertThat(targetTagRepository.findOne(savedAssigned.getId()).getOptLockRevision()) @@ -322,7 +315,7 @@ public class TagManagementTest extends AbstractIntegrationTest { @Test @Description("Ensures that a created tag is persisted in the repository as defined.") public void createDistributionSetTag() { - final Tag tag = tagManagement.createDistributionSetTag(new DistributionSetTag("kai1", "kai2", "colour")); + final Tag tag = tagManagement.createDistributionSetTag(new JpaDistributionSetTag("kai1", "kai2", "colour")); assertThat(distributionSetTagRepository.findByNameEquals("kai1").getDescription()).as("wrong tag found") .isEqualTo("kai2"); @@ -366,10 +359,10 @@ public class TagManagementTest extends AbstractIntegrationTest { @Test @Description("Ensures that a tag cannot be created if one exists already with that name (ecpects EntityAlreadyExistsException).") public void failedDuplicateTargetTagNameException() { - tagManagement.createTargetTag(new TargetTag("A")); + tagManagement.createTargetTag(new JpaTargetTag("A")); try { - tagManagement.createTargetTag(new TargetTag("A")); + tagManagement.createTargetTag(new JpaTargetTag("A")); fail("should not have worked as tag already exists"); } catch (final EntityAlreadyExistsException e) { @@ -379,8 +372,8 @@ public class TagManagementTest extends AbstractIntegrationTest { @Test @Description("Ensures that a tag cannot be updated to a name that already exists on another tag (ecpects EntityAlreadyExistsException).") public void failedDuplicateTargetTagNameExceptionAfterUpdate() { - tagManagement.createTargetTag(new TargetTag("A")); - final TargetTag tag = tagManagement.createTargetTag(new TargetTag("B")); + tagManagement.createTargetTag(new JpaTargetTag("A")); + final TargetTag tag = tagManagement.createTargetTag(new JpaTargetTag("B")); tag.setName("A"); try { @@ -394,9 +387,9 @@ public class TagManagementTest extends AbstractIntegrationTest { @Test @Description("Ensures that a tag cannot be created if one exists already with that name (ecpects EntityAlreadyExistsException).") public void failedDuplicateDsTagNameException() { - tagManagement.createDistributionSetTag(new DistributionSetTag("A")); + tagManagement.createDistributionSetTag(new JpaDistributionSetTag("A")); try { - tagManagement.createDistributionSetTag(new DistributionSetTag("A")); + tagManagement.createDistributionSetTag(new JpaDistributionSetTag("A")); fail("should not have worked as tag already exists"); } catch (final EntityAlreadyExistsException e) { @@ -406,8 +399,8 @@ public class TagManagementTest extends AbstractIntegrationTest { @Test @Description("Ensures that a tag cannot be updated to a name that already exists on another tag (ecpects EntityAlreadyExistsException).") public void failedDuplicateDsTagNameExceptionAfterUpdate() { - tagManagement.createDistributionSetTag(new DistributionSetTag("A")); - final DistributionSetTag tag = tagManagement.createDistributionSetTag(new DistributionSetTag("B")); + tagManagement.createDistributionSetTag(new JpaDistributionSetTag("A")); + final DistributionSetTag tag = tagManagement.createDistributionSetTag(new JpaDistributionSetTag("B")); tag.setName("A"); try { @@ -448,21 +441,19 @@ public class TagManagementTest extends AbstractIntegrationTest { assertThat(distributionSetTagRepository.findAll()).as("Wrong size of tags").hasSize(20); } - private List createTargetsWithTags() { - targetManagement.createTargets(TestDataUtil.generateTargets(20)); - final Iterable tags = tagManagement.createTargetTags(TestDataUtil.generateTargetTags(20)); + private List createTargetsWithTags() { + final List targets = testdataFactory.createTargets(20); + final Iterable tags = tagManagement.createTargetTags(testdataFactory.generateTargetTags(20)); - tags.forEach(tag -> targetManagement.toggleTagAssignment(targetRepository.findAll(), tag)); + tags.forEach(tag -> targetManagement.toggleTagAssignment(targets, tag)); - return tagManagement.findAllTargetTags(); + return targetTagRepository.findAll(); } private List createDsSetsWithTags() { - final List sets = TestDataUtil.generateDistributionSets(20, softwareManagement, - distributionSetManagement); - final Iterable tags = tagManagement - .createDistributionSetTags(TestDataUtil.generateDistributionSetTags(20)); + final Collection sets = testdataFactory.createDistributionSets(20); + final Iterable tags = testdataFactory.createDistributionSetTags(20); tags.forEach(tag -> distributionSetManagement.toggleTagAssignment(sets, tag)); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagenmentTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryManagenmentTest.java similarity index 78% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagenmentTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryManagenmentTest.java index 99e08f331..07b92ebeb 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagenmentTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryManagenmentTest.java @@ -6,13 +6,14 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; -import org.eclipse.hawkbit.AbstractIntegrationTest; +import org.eclipse.hawkbit.repository.TargetFilterQueryManagement; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetFilterQuery; import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.junit.Test; @@ -26,14 +27,14 @@ import ru.yandex.qatools.allure.annotations.Stories; */ @Features("Component Tests - Repository") @Stories("Target Filter Query Management") -public class TargetFilterQueryManagenmentTest extends AbstractIntegrationTest { +public class TargetFilterQueryManagenmentTest extends AbstractJpaIntegrationTest { @Test @Description("Test creation of target filter query.") public void createTargetFilterQuery() { final String filterName = "new target filter"; final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement - .createTargetFilterQuery(new TargetFilterQuery(filterName, "name==PendingTargets001")); + .createTargetFilterQuery(new JpaTargetFilterQuery(filterName, "name==PendingTargets001")); assertEquals("Retrieved newly created custom target filter", targetFilterQuery, targetFilterQueryManagement.findTargetFilterQueryByName(filterName)); } @@ -43,11 +44,11 @@ public class TargetFilterQueryManagenmentTest extends AbstractIntegrationTest { public void createDuplicateTargetFilterQuery() { final String filterName = "new target filter duplicate"; targetFilterQueryManagement - .createTargetFilterQuery(new TargetFilterQuery(filterName, "name==PendingTargets001")); + .createTargetFilterQuery(new JpaTargetFilterQuery(filterName, "name==PendingTargets001")); try { targetFilterQueryManagement - .createTargetFilterQuery(new TargetFilterQuery(filterName, "name==PendingTargets001")); + .createTargetFilterQuery(new JpaTargetFilterQuery(filterName, "name==PendingTargets001")); fail("should not have worked as query already exists"); } catch (final EntityAlreadyExistsException e) { @@ -59,7 +60,7 @@ public class TargetFilterQueryManagenmentTest extends AbstractIntegrationTest { public void deleteTargetFilterQuery() { final String filterName = "delete_target_filter_query"; final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement - .createTargetFilterQuery(new TargetFilterQuery(filterName, "name==PendingTargets001")); + .createTargetFilterQuery(new JpaTargetFilterQuery(filterName, "name==PendingTargets001")); targetFilterQueryManagement.deleteTargetFilterQuery(targetFilterQuery.getId()); assertEquals("Returns null as the target filter is deleted", null, targetFilterQueryManagement.findTargetFilterQueryById(targetFilterQuery.getId())); @@ -71,7 +72,7 @@ public class TargetFilterQueryManagenmentTest extends AbstractIntegrationTest { public void updateTargetFilterQuery() { final String filterName = "target_filter_01"; final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement - .createTargetFilterQuery(new TargetFilterQuery(filterName, "name==PendingTargets001")); + .createTargetFilterQuery(new JpaTargetFilterQuery(filterName, "name==PendingTargets001")); final String newQuery = "status==UNKNOWN"; targetFilterQuery.setQuery(newQuery); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementSearchTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementSearchTest.java similarity index 82% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementSearchTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementSearchTest.java index 73d549eb7..1e8f102c7 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementSearchTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementSearchTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import static org.fest.assertions.api.Assertions.assertThat; @@ -17,19 +17,20 @@ import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; -import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.TestDataUtil; +import org.eclipse.hawkbit.repository.jpa.model.JpaAction; +import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetFilterQuery; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag; 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.Target; -import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.eclipse.hawkbit.repository.model.TargetIdName; import org.eclipse.hawkbit.repository.model.TargetTag; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity; -import org.eclipse.hawkbit.repository.specifications.TargetSpecifications; import org.junit.Test; import org.springframework.data.domain.Slice; @@ -43,44 +44,42 @@ import ru.yandex.qatools.allure.annotations.Stories; @Features("Component Tests - Repository") @Stories("Target Management Searches") -public class TargetManagementSearchTest extends AbstractIntegrationTest { +public class TargetManagementSearchTest extends AbstractJpaIntegrationTest { @Test @Description("Tests different parameter combinations for target search operations. " + "That includes both the test itself, as a count operation with the same filters " + "and query definitions by RSQL (named and un-named).") public void targetSearchWithVariousFilterCombinations() { - final TargetTag targTagX = tagManagement.createTargetTag(new TargetTag("TargTag-X")); - final TargetTag targTagY = tagManagement.createTargetTag(new TargetTag("TargTag-Y")); - final TargetTag targTagZ = tagManagement.createTargetTag(new TargetTag("TargTag-Z")); - final TargetTag targTagW = tagManagement.createTargetTag(new TargetTag("TargTag-W")); + final TargetTag targTagX = tagManagement.createTargetTag(new JpaTargetTag("TargTag-X")); + final TargetTag targTagY = tagManagement.createTargetTag(new JpaTargetTag("TargTag-Y")); + final TargetTag targTagZ = tagManagement.createTargetTag(new JpaTargetTag("TargTag-Z")); + final TargetTag targTagW = tagManagement.createTargetTag(new JpaTargetTag("TargTag-W")); - final DistributionSet setA = TestDataUtil.generateDistributionSet("", softwareManagement, - distributionSetManagement); + final DistributionSet setA = testdataFactory.createDistributionSet(""); - final DistributionSet installedSet = TestDataUtil.generateDistributionSet("another", softwareManagement, - distributionSetManagement); + final DistributionSet installedSet = testdataFactory.createDistributionSet("another"); final String targetDsAIdPref = "targ-A"; List targAs = targetManagement.createTargets( - TestDataUtil.buildTargetFixtures(100, targetDsAIdPref, targetDsAIdPref.concat(" description"))); + testdataFactory.generateTargets(100, targetDsAIdPref, targetDsAIdPref.concat(" description"))); targAs = targetManagement.toggleTagAssignment(targAs, targTagX).getAssignedEntity(); final String targetDsBIdPref = "targ-B"; List targBs = targetManagement.createTargets( - TestDataUtil.buildTargetFixtures(100, targetDsBIdPref, targetDsBIdPref.concat(" description"))); + testdataFactory.generateTargets(100, targetDsBIdPref, targetDsBIdPref.concat(" description"))); targBs = targetManagement.toggleTagAssignment(targBs, targTagY).getAssignedEntity(); targBs = targetManagement.toggleTagAssignment(targBs, targTagW).getAssignedEntity(); final String targetDsCIdPref = "targ-C"; List targCs = targetManagement.createTargets( - TestDataUtil.buildTargetFixtures(100, targetDsCIdPref, targetDsCIdPref.concat(" description"))); + testdataFactory.generateTargets(100, targetDsCIdPref, targetDsCIdPref.concat(" description"))); targCs = targetManagement.toggleTagAssignment(targCs, targTagZ).getAssignedEntity(); targCs = targetManagement.toggleTagAssignment(targCs, targTagW).getAssignedEntity(); final String targetDsDIdPref = "targ-D"; final List targDs = targetManagement.createTargets( - TestDataUtil.buildTargetFixtures(100, targetDsDIdPref, targetDsDIdPref.concat(" description"))); + testdataFactory.generateTargets(100, targetDsDIdPref, targetDsDIdPref.concat(" description"))); final String assignedC = targCs.iterator().next().getControllerId(); deploymentManagement.assignDistributionSet(setA.getId(), assignedC); @@ -96,7 +95,7 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { final Action action = deploymentManagement.findActionWithDetails(actionId); action.setStatus(Status.FINISHED); controllerManagament.addUpdateActionStatus( - new ActionStatus(action, Status.FINISHED, System.currentTimeMillis(), "message"), action); + new JpaActionStatus((JpaAction) action, Status.FINISHED, System.currentTimeMillis(), "message")); deploymentManagement.assignDistributionSet(setA.getId(), installedC); final List unknown = new ArrayList<>(); @@ -174,13 +173,13 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { .as("and filter query returns the same result") .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + .findTargetsAll(new JpaTargetFilterQuery("test", query), pageReq).getContent()); assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, pending, null, installedSet.getId(), Boolean.FALSE, new String[0])).as("has number of elements").hasSize(1) .as("and contains the following elements").containsExactly(expectedIdName) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findAllTargetIdsByTargetFilterQuery(pageReq, new TargetFilterQuery("test", query))); + .findAllTargetIdsByTargetFilterQuery(pageReq, new JpaTargetFilterQuery("test", query))); } @@ -200,13 +199,13 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { .as("and filter query returns the same result") .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + .findTargetsAll(new JpaTargetFilterQuery("test", query), pageReq).getContent()); assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, both, null, null, Boolean.FALSE, targTagW.getName())).as("has number of elements").hasSize(200).as("and contains the following elements") .containsAll(expectedIdNames).as("and NAMED filter query returns the same result") .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, - new TargetFilterQuery("test", query))); + new JpaTargetFilterQuery("test", query))); } private static List convertToIdNames(final List expected) { @@ -234,13 +233,13 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { .as("and filter query returns the same result") .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + .findTargetsAll(new JpaTargetFilterQuery("test", query), pageReq).getContent()); assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, pending, null, null, Boolean.FALSE, targTagW.getName())).as("has number of elements").hasSize(2).as("and contains the following elements") .containsAll(expectedIdNames).as("and NAMED filter query returns the same result") .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, - new TargetFilterQuery("test", query))); + new JpaTargetFilterQuery("test", query))); } @Step @@ -260,13 +259,13 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { .as("and filter query returns the same result") .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + .findTargetsAll(new JpaTargetFilterQuery("test", query), pageReq).getContent()); assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, pending, null, null, Boolean.FALSE, targTagW.getName())).as("has number of elements").hasSize(2).as("and contains the following elements") .containsAll(expectedIdNames).as("and NAMED filter query returns the same result") .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, - new TargetFilterQuery("test", query))); + new JpaTargetFilterQuery("test", query))); } @Step @@ -286,13 +285,13 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { .as("and filter query returns the same result") .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + .findTargetsAll(new JpaTargetFilterQuery("test", query), pageReq).getContent()); assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, pending, "%targ-B%", setA.getId(), Boolean.FALSE, targTagW.getName())).as("has number of elements").hasSize(1).as("and contains the following elements") .containsExactly(expectedIdName).as("and NAMED filter query returns the same result") .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, - new TargetFilterQuery("test", query))); + new JpaTargetFilterQuery("test", query))); } @Step @@ -312,13 +311,13 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { .as("and filter query returns the same result") .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + .findTargetsAll(new JpaTargetFilterQuery("test", query), pageReq).getContent()); assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, pending, "%targ-A%", setA.getId(), Boolean.FALSE, new String[0])).as("has number of elements").hasSize(1).as("and contains the following elements") .containsExactly(expectedIdName).as("and NAMED filter query returns the same result") .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, - new TargetFilterQuery("test", query))); + new JpaTargetFilterQuery("test", query))); } @Step @@ -337,13 +336,13 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { .as("and filter query returns the same result") .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + .findTargetsAll(new JpaTargetFilterQuery("test", query), pageReq).getContent()); assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, pending, null, setA.getId(), Boolean.FALSE, new String[0])).as("has number of elements").hasSize(3).as("and contains the following elements") .containsAll(expectedIdNames).as("and NAMED filter query returns the same result") .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, - new TargetFilterQuery("test", query))); + new JpaTargetFilterQuery("test", query))); } @Step @@ -361,14 +360,14 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { .as("and filter query returns the same result") .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + .findTargetsAll(new JpaTargetFilterQuery("test", query), pageReq).getContent()); assertThat( targetManagement.findAllTargetIdsByFilters(pageReq, pending, null, null, Boolean.FALSE, new String[0])) .as("has number of elements").hasSize(3).as("and contains the following elements") .containsAll(expectedIdNames).as("and NAMED filter query returns the same result") .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, - new TargetFilterQuery("test", query))); + new JpaTargetFilterQuery("test", query))); } @Step @@ -388,13 +387,13 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { .as("and filter query returns the same result") .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + .findTargetsAll(new JpaTargetFilterQuery("test", query), pageReq).getContent()); assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, unknown, "%targ-B%", null, Boolean.FALSE, targTagW.getName())).as("has number of elements").hasSize(99).as("and contains the following elements") .containsAll(expectedIdNames).as("and NAMED filter query returns the same result") .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, - new TargetFilterQuery("test", query))); + new JpaTargetFilterQuery("test", query))); } @Step @@ -412,13 +411,13 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { .as("and filter query returns the same result") .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + .findTargetsAll(new JpaTargetFilterQuery("test", query), pageReq).getContent()); assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, unknown, "%targ-A%", null, Boolean.FALSE, new String[0])).as("has number of elements").hasSize(99).as("and contains the following elements") .containsAll(expectedIdNames).as("and NAMED filter query returns the same result") .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, - new TargetFilterQuery("test", query))); + new JpaTargetFilterQuery("test", query))); } @Step @@ -435,12 +434,12 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { .as("and filter query returns the same result") .hasSize(targetManagement.findTargetsAll(query, pageReq).getContent().size()) .as("and NAMED filter query returns the same result").hasSize(targetManagement - .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent().size()); + .findTargetsAll(new JpaTargetFilterQuery("test", query), pageReq).getContent().size()); assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, unknown, null, setA.getId(), Boolean.FALSE, new String[0])).as("has number of elements").hasSize(0) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findAllTargetIdsByTargetFilterQuery(pageReq, new TargetFilterQuery("test", query))); + .findAllTargetIdsByTargetFilterQuery(pageReq, new JpaTargetFilterQuery("test", query))); } @Step @@ -459,13 +458,13 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { .as("and filter query returns the same result") .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + .findTargetsAll(new JpaTargetFilterQuery("test", query), pageReq).getContent()); assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, unknown, null, null, Boolean.FALSE, targTagY.getName(), targTagW.getName())).as("has number of elements").hasSize(198) .as("and contains the following elements").containsAll(expectedIdNames) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findAllTargetIdsByTargetFilterQuery(pageReq, new TargetFilterQuery("test", query))); + .findAllTargetIdsByTargetFilterQuery(pageReq, new JpaTargetFilterQuery("test", query))); } @Step @@ -483,14 +482,14 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { .as("and filter query returns the same result") .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + .findTargetsAll(new JpaTargetFilterQuery("test", query), pageReq).getContent()); assertThat( targetManagement.findAllTargetIdsByFilters(pageReq, unknown, null, null, Boolean.FALSE, new String[0])) .as("has number of elements").hasSize(397).as("and contains the following elements") .containsAll(expectedIdNames).as("and NAMED filter query returns the same result") .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, - new TargetFilterQuery("test", query))); + new JpaTargetFilterQuery("test", query))); } @Step @@ -509,13 +508,13 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { .as("and filter query returns the same result") .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + .findTargetsAll(new JpaTargetFilterQuery("test", query), pageReq).getContent()); assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, null, "%targ-A%", setA.getId(), Boolean.FALSE, new String[0])).as("has number of elements").hasSize(1).as("and contains the following elements") .containsExactly(expectedIdName).as("and NAMED filter query returns the same result") .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, - new TargetFilterQuery("test", query))); + new JpaTargetFilterQuery("test", query))); } @Step @@ -532,13 +531,13 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { .as("and filter query returns the same result") .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + .findTargetsAll(new JpaTargetFilterQuery("test", query), pageReq).getContent()); assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, null, null, setA.getId(), Boolean.FALSE, new String[0])).as("has number of elements").hasSize(3).as("and contains the following elements") .containsAll(expectedIdNames).as("and NAMED filter query returns the same result") .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, - new TargetFilterQuery("test", query))); + new JpaTargetFilterQuery("test", query))); } @Step @@ -554,12 +553,12 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { .as("and filter query returns the same result") .hasSize(targetManagement.findTargetsAll(query, pageReq).getContent().size()) .as("and NAMED filter query returns the same result").hasSize(targetManagement - .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent().size()); + .findTargetsAll(new JpaTargetFilterQuery("test", query), pageReq).getContent().size()); assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, null, "%targ-C%", setA.getId(), Boolean.FALSE, targTagX.getName())).as("has number of elements").hasSize(0) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findAllTargetIdsByTargetFilterQuery(pageReq, new TargetFilterQuery("test", query))); + .findAllTargetIdsByTargetFilterQuery(pageReq, new JpaTargetFilterQuery("test", query))); } @Step @@ -575,12 +574,12 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { .as("and filter query returns the same result") .hasSize(targetManagement.findTargetsAll(query, pageReq).getContent().size()) .as("and NAMED filter query returns the same result").hasSize(targetManagement - .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent().size()); + .findTargetsAll(new JpaTargetFilterQuery("test", query), pageReq).getContent().size()); assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, null, "%targ-A%", setA.getId(), Boolean.FALSE, targTagW.getName())).as("has number of elements").hasSize(0) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findAllTargetIdsByTargetFilterQuery(pageReq, new TargetFilterQuery("test", query))); + .findAllTargetIdsByTargetFilterQuery(pageReq, new JpaTargetFilterQuery("test", query))); } @Step @@ -599,13 +598,13 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { .as("and filter query returns the same result") .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + .findTargetsAll(new JpaTargetFilterQuery("test", query), pageReq).getContent()); assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, null, "%targ-C%", setA.getId(), Boolean.FALSE, targTagW.getName())).as("has number of elements").hasSize(1).as("and contains the following elements") .containsExactly(expectedIdName).as("and NAMED filter query returns the same result") .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, - new TargetFilterQuery("test", query))); + new JpaTargetFilterQuery("test", query))); } @Step @@ -623,13 +622,13 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { .as("and filter query returns the same result") .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + .findTargetsAll(new JpaTargetFilterQuery("test", query), pageReq).getContent()); assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, null, "%targ-B%", null, Boolean.FALSE, targTagY.getName(), targTagW.getName())).as("has number of elements").hasSize(100) .as("and contains the following elements").containsAll(expectedIdNames) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findAllTargetIdsByTargetFilterQuery(pageReq, new TargetFilterQuery("test", query))); + .findAllTargetIdsByTargetFilterQuery(pageReq, new JpaTargetFilterQuery("test", query))); } @@ -653,13 +652,13 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { .as("and filter query returns the same result") .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) .as("and NAMED filter query returns the same result").containsAll(targetManagement - .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + .findTargetsAll(new JpaTargetFilterQuery("test", query), pageReq).getContent()); assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, null, null, null, Boolean.FALSE, targTagD.getName())).as("has number of elements").hasSize(200).as("and contains the following elements") .containsAll(expectedIdNames).as("and NAMED filter query returns the same result") .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, - new TargetFilterQuery("test", query))); + new JpaTargetFilterQuery("test", query))); } @@ -679,14 +678,13 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { public void targetSearchWithVariousFilterCombinationsAndOrderByDistributionSet() { final List notAssigned = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(3, "not", "first description")); + .createTargets(testdataFactory.generateTargets(3, "not", "first description")); List targAssigned = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(3, "assigned", "first description")); + .createTargets(testdataFactory.generateTargets(3, "assigned", "first description")); List targInstalled = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(3, "installed", "first description")); + .createTargets(testdataFactory.generateTargets(3, "installed", "first description")); - final DistributionSet ds = TestDataUtil.generateDistributionSet("a", softwareManagement, - distributionSetManagement); + final DistributionSet ds = testdataFactory.createDistributionSet("a"); targAssigned = deploymentManagement.assignDistributionSet(ds, targAssigned).getAssignedEntity(); targInstalled = deploymentManagement.assignDistributionSet(ds, targInstalled).getAssignedEntity(); @@ -698,7 +696,7 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { final Comparator byId = (e1, e2) -> Long.compare(e2.getId(), e1.getId()); assertThat(result.getNumberOfElements()).isEqualTo(9); - final List expected = new ArrayList(); + final List expected = new ArrayList<>(); Collections.sort(targInstalled, byId); Collections.sort(targAssigned, byId); Collections.sort(notAssigned, byId); @@ -713,10 +711,9 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { @Test @Description("Verfies that targets with given assigned DS are returned from repository.") public void findTargetByAssignedDistributionSet() { - final DistributionSet assignedSet = TestDataUtil.generateDistributionSet("", softwareManagement, - distributionSetManagement); - targetManagement.createTargets(TestDataUtil.generateTargets(10, "unassigned")); - List assignedtargets = targetManagement.createTargets(TestDataUtil.generateTargets(10, "assigned")); + final DistributionSet assignedSet = testdataFactory.createDistributionSet(""); + targetManagement.createTargets(testdataFactory.generateTargets(10, "unassigned")); + List assignedtargets = targetManagement.createTargets(testdataFactory.generateTargets(10, "assigned")); deploymentManagement.assignDistributionSet(assignedSet, assignedtargets); @@ -730,50 +727,20 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { } - @Test - @Description("Verfies that targets with given assigned DS and additonal specification are returned from repository.") - public void findTargetByAssignedDistributionSetWithAdditonalSpecification() { - final DistributionSet assignedSet = TestDataUtil.generateDistributionSet("", softwareManagement, - distributionSetManagement); - final DistributionSet installedSet = TestDataUtil.generateDistributionSet("another", softwareManagement, - distributionSetManagement); - targetManagement.createTargets(TestDataUtil.generateTargets(10, "unassigned")); - List assignedtargets = targetManagement.createTargets(TestDataUtil.generateTargets(10, "assigned")); - - // set on installed and assign another one - deploymentManagement.assignDistributionSet(installedSet, assignedtargets).getActions().forEach(actionId -> { - final Action action = deploymentManagement.findActionWithDetails(actionId); - action.setStatus(Status.FINISHED); - controllerManagament.addUpdateActionStatus( - new ActionStatus(action, Status.FINISHED, System.currentTimeMillis(), "message"), action); - }); - deploymentManagement.assignDistributionSet(assignedSet, assignedtargets); - - assignedtargets = targetManagement.findTargetByControllerID( - assignedtargets.stream().map(target -> target.getControllerId()).collect(Collectors.toList())); - - assertThat(targetManagement.findTargetByAssignedDistributionSet(assignedSet.getId(), - TargetSpecifications.hasInstalledDistributionSet(installedSet.getId()), pageReq)) - .as("Contains the assigned targets").containsAll(assignedtargets) - .as("and that means the following expected amount").hasSize(10); - } - @Test @Description("Verfies that targets with given installed DS are returned from repository.") public void findTargetByInstalledDistributionSet() { - final DistributionSet assignedSet = TestDataUtil.generateDistributionSet("", softwareManagement, - distributionSetManagement); - final DistributionSet installedSet = TestDataUtil.generateDistributionSet("another", softwareManagement, - distributionSetManagement); - targetManagement.createTargets(TestDataUtil.generateTargets(10, "unassigned")); - List installedtargets = targetManagement.createTargets(TestDataUtil.generateTargets(10, "assigned")); + final DistributionSet assignedSet = testdataFactory.createDistributionSet(""); + final DistributionSet installedSet = testdataFactory.createDistributionSet("another"); + targetManagement.createTargets(testdataFactory.generateTargets(10, "unassigned")); + List installedtargets = targetManagement.createTargets(testdataFactory.generateTargets(10, "assigned")); // set on installed and assign another one deploymentManagement.assignDistributionSet(installedSet, installedtargets).getActions().forEach(actionId -> { final Action action = deploymentManagement.findActionWithDetails(actionId); action.setStatus(Status.FINISHED); controllerManagament.addUpdateActionStatus( - new ActionStatus(action, Status.FINISHED, System.currentTimeMillis(), "message"), action); + new JpaActionStatus((JpaAction) action, Status.FINISHED, System.currentTimeMillis(), "message")); }); deploymentManagement.assignDistributionSet(assignedSet, installedtargets); @@ -787,41 +754,11 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { } - @Test - @Description("Verfies that targets with given installed DS and additonal specification are returned from repository.") - public void findTargetByInstalledDistributionSetWithAdditonalSpecification() { - final DistributionSet assignedSet = TestDataUtil.generateDistributionSet("", softwareManagement, - distributionSetManagement); - final DistributionSet installedSet = TestDataUtil.generateDistributionSet("another", softwareManagement, - distributionSetManagement); - targetManagement.createTargets(TestDataUtil.generateTargets(10, "unassigned")); - List installedtargets = targetManagement.createTargets(TestDataUtil.generateTargets(10, "assigned")); - - // set on installed and assign another one - deploymentManagement.assignDistributionSet(installedSet, installedtargets).getActions().forEach(actionId -> { - final Action action = deploymentManagement.findActionWithDetails(actionId); - action.setStatus(Status.FINISHED); - controllerManagament.addUpdateActionStatus( - new ActionStatus(action, Status.FINISHED, System.currentTimeMillis(), "message"), action); - }); - deploymentManagement.assignDistributionSet(assignedSet, installedtargets); - - // get final updated version of targets - installedtargets = targetManagement.findTargetByControllerID( - installedtargets.stream().map(target -> target.getControllerId()).collect(Collectors.toList())); - - assertThat(targetManagement.findTargetByInstalledDistributionSet(installedSet.getId(), - TargetSpecifications.hasAssignedDistributionSet(assignedSet.getId()), pageReq)) - .as("Contains the assigned targets").containsAll(installedtargets) - .as("and that means the following expected amount").hasSize(10); - - } - private List sendUpdateActionStatusToTargets(final DistributionSet dsA, final Iterable targs, final Status status, final String... msgs) { final List result = new ArrayList(); for (final Target t : targs) { - final List findByTarget = actionRepository.findByTarget(t); + final List findByTarget = actionRepository.findByTarget((JpaTarget) t); for (final Action action : findByTarget) { result.add(sendUpdateActionStatusToTarget(status, action, t, msgs)); } @@ -833,14 +770,14 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { final String... msgs) { updActA.setStatus(status); - final ActionStatus statusMessages = new ActionStatus(); + final ActionStatus statusMessages = new JpaActionStatus(); statusMessages.setAction(updActA); statusMessages.setOccurredAt(System.currentTimeMillis()); statusMessages.setStatus(status); for (final String msg : msgs) { statusMessages.addMessage(msg); } - controllerManagament.addUpdateActionStatus(statusMessages, updActA); + controllerManagament.addUpdateActionStatus(statusMessages); return targetManagement.findTargetByControllerID(t.getControllerId()); } diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementTest.java similarity index 85% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementTest.java index 1c039c8c8..79a7ad89f 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import static org.fest.assertions.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; @@ -28,22 +28,23 @@ import java.util.stream.Collectors; import javax.persistence.Query; import javax.validation.ConstraintViolationException; -import org.eclipse.hawkbit.AbstractIntegrationTest; -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.repository.DistributionSetAssignmentResult; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; import org.eclipse.hawkbit.repository.exception.TenantNotExistException; -import org.eclipse.hawkbit.repository.model.Action; +import org.eclipse.hawkbit.repository.jpa.model.JpaAction; +import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetInfo; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag; 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.Tag; import org.eclipse.hawkbit.repository.model.Target; 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.util.WithSpringAuthorityRule; +import org.eclipse.hawkbit.repository.util.WithUser; import org.junit.Test; import org.springframework.data.domain.PageRequest; @@ -55,12 +56,12 @@ import ru.yandex.qatools.allure.annotations.Stories; @Features("Component Tests - Repository") @Stories("Target Management") -public class TargetManagementTest extends AbstractIntegrationTest { +public class TargetManagementTest extends AbstractJpaIntegrationTest { @Test @Description("Ensures that retrieving the target security is only permitted with the necessary permissions.") public void getTargetSecurityTokenOnlyWithCorrectPermission() throws Exception { - final Target createdTarget = targetManagement.createTarget(new Target("targetWithSecurityToken")); + final Target createdTarget = targetManagement.createTarget(new JpaTarget("targetWithSecurityToken")); // retrieve security token only with READ_TARGET_SEC_TOKEN permission final String securityTokenWithReadPermission = securityRule.runAs(WithSpringAuthorityRule @@ -92,7 +93,7 @@ public class TargetManagementTest extends AbstractIntegrationTest { @WithUser(tenantId = "tenantWhichDoesNotExists", allSpPermissions = true, autoCreateTenant = false) public void createTargetForTenantWhichDoesNotExistThrowsTenantNotExistException() { try { - targetManagement.createTarget(new Target("targetId123")); + targetManagement.createTarget(new JpaTarget("targetId123")); fail("should not be possible as the tenant does not exist"); } catch (final TenantNotExistException e) { // ok @@ -103,14 +104,14 @@ public class TargetManagementTest extends AbstractIntegrationTest { @Description("Verify that a target with empty controller id cannot be created") public void createTargetWithNoControllerId() { try { - targetManagement.createTarget(new Target("")); + targetManagement.createTarget(new JpaTarget("")); fail("target with empty controller id should not be created"); } catch (final ConstraintViolationException e) { // ok } try { - targetManagement.createTarget(new Target(null)); + targetManagement.createTarget(new JpaTarget(null)); fail("target with empty controller id should not be created"); } catch (final ConstraintViolationException e) { // ok @@ -121,13 +122,13 @@ public class TargetManagementTest extends AbstractIntegrationTest { @Description("Ensures that targets can assigned and unassigned to a target tag. Not exists target will be ignored for the assignment.") public void assignAndUnassignTargetsToTag() { final List assignTarget = new ArrayList(); - assignTarget.add(targetManagement.createTarget(new Target("targetId123")).getControllerId()); - assignTarget.add(targetManagement.createTarget(new Target("targetId1234")).getControllerId()); - assignTarget.add(targetManagement.createTarget(new Target("targetId1235")).getControllerId()); - assignTarget.add(targetManagement.createTarget(new Target("targetId1236")).getControllerId()); + assignTarget.add(targetManagement.createTarget(new JpaTarget("targetId123")).getControllerId()); + assignTarget.add(targetManagement.createTarget(new JpaTarget("targetId1234")).getControllerId()); + assignTarget.add(targetManagement.createTarget(new JpaTarget("targetId1235")).getControllerId()); + assignTarget.add(targetManagement.createTarget(new JpaTarget("targetId1236")).getControllerId()); assignTarget.add("NotExist"); - final TargetTag targetTag = tagManagement.createTargetTag(new TargetTag("Tag1")); + final TargetTag targetTag = tagManagement.createTargetTag(new JpaTargetTag("Tag1")); final List assignedTargets = targetManagement.assignTag(assignTarget, targetTag); assertThat(assignedTargets.size()).as("Assigned targets are wrong").isEqualTo(4); @@ -156,7 +157,7 @@ public class TargetManagementTest extends AbstractIntegrationTest { @Test @Description("Ensures that targets can deleted e.g. test all cascades") public void deleteAndCreateTargets() { - Target target = targetManagement.createTarget(new Target("targetId123")); + Target target = targetManagement.createTarget(new JpaTarget("targetId123")); assertThat(targetManagement.countTargetsAll()).as("target count is wrong").isEqualTo(1); targetManagement.deleteTargets(target.getId()); assertThat(targetManagement.countTargetsAll()).as("target count is wrong").isEqualTo(0); @@ -168,7 +169,7 @@ public class TargetManagementTest extends AbstractIntegrationTest { final List targets = new ArrayList(); for (int i = 0; i < 5; i++) { - target = targetManagement.createTarget(new Target("" + i)); + target = targetManagement.createTarget(new JpaTarget("" + i)); targets.add(target.getId()); targets.add(createTargetWithAttributes("" + (i * i + 1000)).getId()); } @@ -178,7 +179,7 @@ public class TargetManagementTest extends AbstractIntegrationTest { } private Target createTargetWithAttributes(final String controllerId) { - Target target = new Target(controllerId); + Target target = new JpaTarget(controllerId); final Map testData = new HashMap<>(); testData.put("test1", "testdata1"); @@ -194,10 +195,8 @@ public class TargetManagementTest extends AbstractIntegrationTest { @Test @Description("Finds a target by given ID and checks if all data is in the reponse (including the data defined as lazy).") public void findTargetByControllerIDWithDetails() { - final DistributionSet set = TestDataUtil.generateDistributionSet("test", softwareManagement, - distributionSetManagement); - final DistributionSet set2 = TestDataUtil.generateDistributionSet("test2", softwareManagement, - distributionSetManagement); + final DistributionSet set = testdataFactory.createDistributionSet("test"); + final DistributionSet set2 = testdataFactory.createDistributionSet("test2"); assertThat(targetManagement.countTargetByAssignedDistributionSet(set.getId())).as("Target count is wrong") .isEqualTo(0); @@ -215,10 +214,10 @@ public class TargetManagementTest extends AbstractIntegrationTest { final DistributionSetAssignmentResult result = deploymentManagement.assignDistributionSet(set.getId(), "4711"); - final Action action = deploymentManagement.findActionWithDetails(result.getActions().get(0)); + final JpaAction action = (JpaAction) deploymentManagement.findActionWithDetails(result.getActions().get(0)); action.setStatus(Status.FINISHED); controllerManagament.addUpdateActionStatus( - new ActionStatus(action, Status.FINISHED, System.currentTimeMillis(), "message"), action); + new JpaActionStatus(action, Status.FINISHED, System.currentTimeMillis(), "message")); deploymentManagement.assignDistributionSet(set2.getId(), "4711"); target = targetManagement.findTargetByControllerIDWithDetails("4711"); @@ -249,7 +248,7 @@ public class TargetManagementTest extends AbstractIntegrationTest { @Test @Description("Checks if the EntityAlreadyExistsException is thrown if the targets with the same controller ID are created twice.") public void createMultipleTargetsDuplicate() { - final List targets = TestDataUtil.buildTargetFixtures(5, "mySimpleTargs", "my simple targets"); + final List targets = testdataFactory.generateTargets(5, "mySimpleTargs", "my simple targets"); targetManagement.createTargets(targets); try { targetManagement.createTargets(targets); @@ -262,9 +261,9 @@ public class TargetManagementTest extends AbstractIntegrationTest { @Test @Description("Checks if the EntityAlreadyExistsException is thrown if a single target with the same controller ID are created twice.") public void createTargetDuplicate() { - targetManagement.createTarget(new Target("4711")); + targetManagement.createTarget(new JpaTarget("4711")); try { - targetManagement.createTarget(new Target("4711")); + targetManagement.createTarget(new JpaTarget("4711")); fail("Target already exists"); } catch (final EntityAlreadyExistsException e) { } @@ -324,7 +323,7 @@ public class TargetManagementTest extends AbstractIntegrationTest { public void singleTargetIsInsertedIntoRepo() throws Exception { final String myCtrlID = "myCtrlID"; - final Target target = TestDataUtil.buildTargetFixture(myCtrlID, "the description!"); + final Target target = testdataFactory.generateTarget(myCtrlID, "the description!"); Target savedTarget = targetManagement.createTarget(target); assertNotNull("The target should not be null", savedTarget); @@ -361,15 +360,15 @@ public class TargetManagementTest extends AbstractIntegrationTest { @Description("Create multiple tragets as bulk operation and delete them in bulk.") public void bulkTargetCreationAndDelete() throws Exception { final String myCtrlID = "myCtrlID"; - final List firstList = TestDataUtil.buildTargetFixtures(100, myCtrlID, "first description"); + final List firstList = testdataFactory.generateTargets(100, myCtrlID, "first description"); - final Target extra = TestDataUtil.buildTargetFixture("myCtrlID-00081XX", "first description"); + final Target extra = testdataFactory.generateTarget("myCtrlID-00081XX", "first description"); List firstSaved = targetManagement.createTargets(firstList); final Target savedExtra = targetManagement.createTarget(extra); - Iterable allFound = targetRepository.findAll(); + final Iterable allFound = targetRepository.findAll(); assertThat(Long.valueOf(firstList.size())).as("List size of targets") .isEqualTo(firstSaved.spliterator().getExactSizeIfKnown()); @@ -422,31 +421,31 @@ public class TargetManagementTest extends AbstractIntegrationTest { targetManagement.deleteTargets(deletedTargetIDs); - allFound = targetManagement.findTargetsAll(new PageRequest(0, 200)).getContent(); + final List found = targetManagement.findTargetsAll(new PageRequest(0, 200)).getContent(); assertThat(firstSaved.spliterator().getExactSizeIfKnown() - nr2Del).as("Size of splited list") - .isEqualTo(allFound.spliterator().getExactSizeIfKnown()); + .isEqualTo(found.spliterator().getExactSizeIfKnown()); - assertThat(allFound).as("Not all undeleted found").doesNotContain(deletedTargets); + assertThat(found).as("Not all undeleted found").doesNotContain(deletedTargets); } @Test @Description("Stores target attributes and verfies existence in the repository.") public void savingTargetControllerAttributes() { Iterable ts = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(100, "myCtrlID", "first description")); + .createTargets(testdataFactory.generateTargets(100, "myCtrlID", "first description")); - final Map attribs = new HashMap(); + final Map attribs = new HashMap<>(); attribs.put("a.b.c", "abc"); attribs.put("x.y.z", ""); attribs.put("1.2.3", "123"); attribs.put("1.2.3.4", "1234"); attribs.put("1.2.3.4.5", "12345"); - final Set attribs2Del = new HashSet(); + final Set attribs2Del = new HashSet<>(); attribs2Del.add("x.y.z"); attribs2Del.add("1.2.3"); for (final Target t : ts) { - TargetInfo targetInfo = t.getTargetInfo(); + JpaTargetInfo targetInfo = (JpaTargetInfo) t.getTargetInfo(); targetInfo.setNew(false); for (final Entry attrib : attribs.entrySet()) { final String key = attrib.getKey(); @@ -491,7 +490,7 @@ public class TargetManagementTest extends AbstractIntegrationTest { for (final Target ta : ts2DelAllAttribs) { final Target t = targetManagement.findTargetByControllerIDWithDetails(ta.getControllerId()); - final TargetInfo targetStatus = t.getTargetInfo(); + final JpaTargetInfo targetStatus = (JpaTargetInfo) t.getTargetInfo(); targetStatus.getControllerAttributes().clear(); targetInfoRepository.save(targetStatus); } @@ -499,7 +498,7 @@ public class TargetManagementTest extends AbstractIntegrationTest { for (final Target ta : ts2DelAttribs) { final Target t = targetManagement.findTargetByControllerIDWithDetails(ta.getControllerId()); - final TargetInfo targetStatus = t.getTargetInfo(); + final JpaTargetInfo targetStatus = (JpaTargetInfo) t.getTargetInfo(); for (final String attribKey : attribs2Del) { targetStatus.getControllerAttributes().remove(attribKey); } @@ -508,7 +507,7 @@ public class TargetManagementTest extends AbstractIntegrationTest { // only the number of the remaining targets and controller attributes // are checked - final Iterable restTS = targetRepository.findAll(); + final Iterable restTS = targetRepository.findAll(); restTarget_: for (final Target targetl : restTS) { final Target target = targetManagement.findTargetByControllerIDWithDetails(targetl.getControllerId()); @@ -542,17 +541,17 @@ public class TargetManagementTest extends AbstractIntegrationTest { @Test @Description("Tests the assigment of tags to the a single target.") public void targetTagAssignment() { - Target t1 = TestDataUtil.buildTargetFixture("id-1", "blablub"); + Target t1 = testdataFactory.generateTarget("id-1", "blablub"); final int noT2Tags = 4; final int noT1Tags = 3; final List t1Tags = tagManagement - .createTargetTags(TestDataUtil.buildTargetTagFixtures(noT1Tags, "tag1")); + .createTargetTags(testdataFactory.generateTargetTags(noT1Tags, "tag1")); t1.getTags().addAll(t1Tags); t1 = targetManagement.createTarget(t1); - Target t2 = TestDataUtil.buildTargetFixture("id-2", "blablub"); + Target t2 = testdataFactory.generateTarget("id-2", "blablub"); final List t2Tags = tagManagement - .createTargetTags(TestDataUtil.buildTargetTagFixtures(noT2Tags, "tag2")); + .createTargetTags(testdataFactory.generateTargetTags(noT2Tags, "tag2")); t2.getTags().addAll(t2Tags); t2 = targetManagement.createTarget(t2); @@ -571,22 +570,22 @@ public class TargetManagementTest extends AbstractIntegrationTest { @Description("Tests the assigment of tags to multiple targets.") public void targetTagBulkAssignments() { final List tagATargets = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(10, "tagATargets", "first description")); + .createTargets(testdataFactory.generateTargets(10, "tagATargets", "first description")); final List tagBTargets = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(10, "tagBTargets", "first description")); + .createTargets(testdataFactory.generateTargets(10, "tagBTargets", "first description")); final List tagCTargets = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(10, "tagCTargets", "first description")); + .createTargets(testdataFactory.generateTargets(10, "tagCTargets", "first description")); final List tagABTargets = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(10, "tagABTargets", "first description")); + .createTargets(testdataFactory.generateTargets(10, "tagABTargets", "first description")); final List tagABCTargets = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(10, "tagABCTargets", "first description")); + .createTargets(testdataFactory.generateTargets(10, "tagABCTargets", "first description")); - final TargetTag tagA = tagManagement.createTargetTag(new TargetTag("A")); - final TargetTag tagB = tagManagement.createTargetTag(new TargetTag("B")); - final TargetTag tagC = tagManagement.createTargetTag(new TargetTag("C")); - tagManagement.createTargetTag(new TargetTag("X")); + final TargetTag tagA = tagManagement.createTargetTag(new JpaTargetTag("A")); + final TargetTag tagB = tagManagement.createTargetTag(new JpaTargetTag("B")); + final TargetTag tagC = tagManagement.createTargetTag(new JpaTargetTag("C")); + tagManagement.createTargetTag(new JpaTargetTag("X")); // doing different assignments targetManagement.toggleTagAssignment(tagATargets, tagA); @@ -641,25 +640,25 @@ public class TargetManagementTest extends AbstractIntegrationTest { @Test @Description("Tests the unassigment of tags to multiple targets.") public void targetTagBulkUnassignments() { - final TargetTag targTagA = tagManagement.createTargetTag(new TargetTag("Targ-A-Tag")); - final TargetTag targTagB = tagManagement.createTargetTag(new TargetTag("Targ-B-Tag")); - final TargetTag targTagC = tagManagement.createTargetTag(new TargetTag("Targ-C-Tag")); + final TargetTag targTagA = tagManagement.createTargetTag(new JpaTargetTag("Targ-A-Tag")); + final TargetTag targTagB = tagManagement.createTargetTag(new JpaTargetTag("Targ-B-Tag")); + final TargetTag targTagC = tagManagement.createTargetTag(new JpaTargetTag("Targ-C-Tag")); final List targAs = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(25, "target-id-A", "first description")); + .createTargets(testdataFactory.generateTargets(25, "target-id-A", "first description")); final List targBs = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(20, "target-id-B", "first description")); + .createTargets(testdataFactory.generateTargets(20, "target-id-B", "first description")); final List targCs = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(15, "target-id-C", "first description")); + .createTargets(testdataFactory.generateTargets(15, "target-id-C", "first description")); final List targABs = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(12, "target-id-AB", "first description")); + .createTargets(testdataFactory.generateTargets(12, "target-id-AB", "first description")); final List targACs = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(13, "target-id-AC", "first description")); + .createTargets(testdataFactory.generateTargets(13, "target-id-AC", "first description")); final List targBCs = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(7, "target-id-BC", "first description")); + .createTargets(testdataFactory.generateTargets(7, "target-id-BC", "first description")); final List targABCs = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(17, "target-id-ABC", "first description")); + .createTargets(testdataFactory.generateTargets(17, "target-id-ABC", "first description")); targetManagement.toggleTagAssignment(targAs, targTagA); targetManagement.toggleTagAssignment(targABs, targTagA); @@ -704,10 +703,10 @@ public class TargetManagementTest extends AbstractIntegrationTest { @Test @Description("Retrieves targets by ID with lazy loading of the tags. Checks the successfull load.") public void findTargetsByControllerIDsWithTags() { - final TargetTag targTagA = tagManagement.createTargetTag(new TargetTag("Targ-A-Tag")); + final TargetTag targTagA = tagManagement.createTargetTag(new JpaTargetTag("Targ-A-Tag")); final List targAs = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(25, "target-id-A", "first description")); + .createTargets(testdataFactory.generateTargets(25, "target-id-A", "first description")); targetManagement.toggleTagAssignment(targAs, targTagA); @@ -727,7 +726,7 @@ public class TargetManagementTest extends AbstractIntegrationTest { @Description("Test the optimized quere for retrieving all ID/name pairs of targets.") public void findAllTargetIdNamePaiss() { final List targAs = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(25, "target-id-A", "first description")); + .createTargets(testdataFactory.generateTargets(25, "target-id-A", "first description")); final String[] createdTargetIds = targAs.stream().map(t -> t.getControllerId()) .toArray(size -> new String[size]); @@ -742,12 +741,12 @@ public class TargetManagementTest extends AbstractIntegrationTest { @Description("Test that NO TAG functionality which gives all targets with no tag assigned.") public void findTargetsWithNoTag() { - final TargetTag targTagA = tagManagement.createTargetTag(new TargetTag("Targ-A-Tag")); + final TargetTag targTagA = tagManagement.createTargetTag(new JpaTargetTag("Targ-A-Tag")); final List targAs = targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(25, "target-id-A", "first description")); + .createTargets(testdataFactory.generateTargets(25, "target-id-A", "first description")); targetManagement.toggleTagAssignment(targAs, targTagA); - targetManagement.createTargets(TestDataUtil.buildTargetFixtures(25, "target-id-B", "first description")); + targetManagement.createTargets(testdataFactory.generateTargets(25, "target-id-B", "first description")); final String[] tagNames = null; final List targetsListWithNoTag = targetManagement diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TenantConfigurationManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TenantConfigurationManagementTest.java similarity index 98% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TenantConfigurationManagementTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TenantConfigurationManagementTest.java index 1427df25b..73feda1c2 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TenantConfigurationManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TenantConfigurationManagementTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository; +package org.eclipse.hawkbit.repository.jpa; import static org.fest.assertions.api.Assertions.assertThat; import static org.junit.Assert.fail; @@ -16,7 +16,6 @@ import java.util.Arrays; import java.util.HashMap; import java.util.Map; -import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB; import org.eclipse.hawkbit.repository.model.TenantConfigurationValue; import org.eclipse.hawkbit.tenancy.configuration.DurationHelper; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; @@ -30,7 +29,7 @@ import ru.yandex.qatools.allure.annotations.Stories; @Features("Component Tests - Repository") @Stories("Tenant Configuration Management") -public class TenantConfigurationManagementTest extends AbstractIntegrationTestWithMongoDB { +public class TenantConfigurationManagementTest extends AbstractJpaIntegrationTestWithMongoDB { @Test @Description("Tests that tenant specific configuration can be persisted and in case the tenant does not have specific configuration the default from environment is used instead.") diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/cache/CacheKeysTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/cache/CacheKeysTest.java similarity index 95% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/cache/CacheKeysTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/cache/CacheKeysTest.java index b0da78abd..921d1953a 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/cache/CacheKeysTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/cache/CacheKeysTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.cache; +package org.eclipse.hawkbit.repository.jpa.cache; import static org.fest.assertions.api.Assertions.assertThat; diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/cache/CacheWriteNotifyTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/cache/CacheWriteNotifyTest.java similarity index 97% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/cache/CacheWriteNotifyTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/cache/CacheWriteNotifyTest.java index c88a3e717..603af17c9 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/cache/CacheWriteNotifyTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/cache/CacheWriteNotifyTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.cache; +package org.eclipse.hawkbit.repository.jpa.cache; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/eventbus/CacheFieldEntityListenerTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/eventbus/CacheFieldEntityListenerTest.java similarity index 92% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/eventbus/CacheFieldEntityListenerTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/eventbus/CacheFieldEntityListenerTest.java index 4943ea88a..3479ed232 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/eventbus/CacheFieldEntityListenerTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/eventbus/CacheFieldEntityListenerTest.java @@ -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; +package org.eclipse.hawkbit.repository.jpa.eventbus; import static org.fest.assertions.api.Assertions.assertThat; import static org.mockito.Matchers.anyString; @@ -14,9 +14,10 @@ import static org.mockito.Matchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import org.eclipse.hawkbit.cache.CacheField; -import org.eclipse.hawkbit.cache.CacheKeys; -import org.eclipse.hawkbit.repository.model.helper.CacheManagerHolder; +import org.eclipse.hawkbit.repository.jpa.cache.CacheField; +import org.eclipse.hawkbit.repository.jpa.cache.CacheKeys; +import org.eclipse.hawkbit.repository.jpa.model.CacheFieldEntityListener; +import org.eclipse.hawkbit.repository.jpa.model.helper.CacheManagerHolder; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/model/ModelEqualsHashcodeTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/model/ModelEqualsHashcodeTest.java similarity index 65% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/model/ModelEqualsHashcodeTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/model/ModelEqualsHashcodeTest.java index 45e56167a..9f4cefa5d 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/model/ModelEqualsHashcodeTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/model/ModelEqualsHashcodeTest.java @@ -6,11 +6,12 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.repository.jpa.model; import static org.fest.assertions.api.Assertions.assertThat; -import org.eclipse.hawkbit.AbstractIntegrationTest; +import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; +import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.junit.Test; import ru.yandex.qatools.allure.annotations.Description; @@ -19,35 +20,35 @@ import ru.yandex.qatools.allure.annotations.Stories; @Features("Unit Tests - Repository") @Stories("Repository Model") -public class ModelEqualsHashcodeTest extends AbstractIntegrationTest { +public class ModelEqualsHashcodeTest extends AbstractJpaIntegrationTest { @Test @Description("Verfies that different objects even with identical primary key, version and tenant " + "return different hash codes.") public void differentEntitiesReturnDifferentHashCodes() { - assertThat(new Action().hashCode()).as("action should have different hashcode than action status") - .isNotEqualTo(new ActionStatus().hashCode()); - assertThat(new DistributionSet().hashCode()) + assertThat(new JpaAction().hashCode()).as("action should have different hashcode than action status") + .isNotEqualTo(new JpaActionStatus().hashCode()); + assertThat(new JpaDistributionSet().hashCode()) .as("Distribution set should have different hashcode than software module") - .isNotEqualTo(new SoftwareModule().hashCode()); - assertThat(new DistributionSet().hashCode()) + .isNotEqualTo(new JpaSoftwareModule().hashCode()); + assertThat(new JpaDistributionSet().hashCode()) .as("Distribution set should have different hashcode than action status") - .isNotEqualTo(new ActionStatus().hashCode()); - assertThat(new DistributionSetType().hashCode()) + .isNotEqualTo(new JpaActionStatus().hashCode()); + assertThat(new JpaDistributionSetType().hashCode()) .as("Distribution set type should have different hashcode than action status") - .isNotEqualTo(new ActionStatus().hashCode()); + .isNotEqualTo(new JpaActionStatus().hashCode()); } @Test @Description("Verfies that different object even with identical primary key, version and tenant " + "are not equal.") public void differentEntitiesAreNotEqual() { - assertThat(new Action().equals(new ActionStatus())).as("action equals action status").isFalse(); - assertThat(new DistributionSet().equals(new SoftwareModule())).as("Distribution set equals software module") + assertThat(new JpaAction().equals(new JpaActionStatus())).as("action equals action status").isFalse(); + assertThat(new JpaDistributionSet().equals(new JpaSoftwareModule())) + .as("Distribution set equals software module").isFalse(); + assertThat(new JpaDistributionSet().equals(new JpaActionStatus())).as("Distribution set equals action status") .isFalse(); - assertThat(new DistributionSet().equals(new ActionStatus())).as("Distribution set equals action status") - .isFalse(); - assertThat(new DistributionSetType().equals(new ActionStatus())) + assertThat(new JpaDistributionSetType().equals(new JpaActionStatus())) .as("Distribution set type equals action status").isFalse(); } @@ -55,9 +56,9 @@ public class ModelEqualsHashcodeTest extends AbstractIntegrationTest { @Description("Verfies that updated entities are not equal.") public void changedEntitiesAreNotEqual() { final SoftwareModuleType type = softwareManagement - .createSoftwareModuleType(new SoftwareModuleType("test", "test", "test", 1)); + .createSoftwareModuleType(new JpaSoftwareModuleType("test", "test", "test", 1)); assertThat(type).as("persited entity is not equal to regular object") - .isNotEqualTo(new SoftwareModuleType("test", "test", "test", 1)); + .isNotEqualTo(new JpaSoftwareModuleType("test", "test", "test", 1)); type.setDescription("another"); final SoftwareModuleType updated = softwareManagement.updateSoftwareModuleType(type); @@ -68,9 +69,9 @@ public class ModelEqualsHashcodeTest extends AbstractIntegrationTest { @Description("Verify that no proxy of the entity manager has an influence on the equals or hashcode result.") public void managedEntityIsEqualToUnamangedObjectWithSameKey() { final SoftwareModuleType type = softwareManagement - .createSoftwareModuleType(new SoftwareModuleType("test", "test", "test", 1)); + .createSoftwareModuleType(new JpaSoftwareModuleType("test", "test", "test", 1)); - final SoftwareModuleType mock = new SoftwareModuleType("test", "test", "test", 1); + final JpaSoftwareModuleType mock = new JpaSoftwareModuleType("test", "test", "test", 1); mock.setId(type.getId()); mock.setOptLockRevision(type.getOptLockRevision()); mock.setTenant(type.getTenant()); @@ -84,9 +85,9 @@ public class ModelEqualsHashcodeTest extends AbstractIntegrationTest { @Description("Verfies that updated entities do not have the same hashcode.") public void updatedEntitiesHaveDifferentHashcodes() { final SoftwareModuleType type = softwareManagement - .createSoftwareModuleType(new SoftwareModuleType("test", "test", "test", 1)); + .createSoftwareModuleType(new JpaSoftwareModuleType("test", "test", "test", 1)); assertThat(type.hashCode()).as("persited entity does not have same hashcode as regular object") - .isNotEqualTo(new SoftwareModuleType("test", "test", "test", 1).hashCode()); + .isNotEqualTo(new JpaSoftwareModuleType("test", "test", "test", 1).hashCode()); final int beforeChange = type.hashCode(); type.setDescription("another"); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLActionFieldsTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLActionFieldsTest.java similarity index 82% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLActionFieldsTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLActionFieldsTest.java index 8b20af27d..3138c9f86 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLActionFieldsTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLActionFieldsTest.java @@ -6,13 +6,16 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.rsql; +package org.eclipse.hawkbit.repository.jpa.rsql; import static org.fest.assertions.api.Assertions.assertThat; import static org.junit.Assert.fail; -import org.eclipse.hawkbit.AbstractIntegrationTest; import org.eclipse.hawkbit.repository.ActionFields; +import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException; +import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; +import org.eclipse.hawkbit.repository.jpa.model.JpaAction; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.ActionType; import org.eclipse.hawkbit.repository.model.Target; @@ -20,7 +23,6 @@ import org.junit.Before; import org.junit.Test; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Slice; -import org.springframework.data.jpa.domain.Specification; import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; @@ -28,23 +30,23 @@ import ru.yandex.qatools.allure.annotations.Stories; @Features("Component Tests - Repository") @Stories("RSQL filter actions") -public class RSQLActionFieldsTest extends AbstractIntegrationTest { +public class RSQLActionFieldsTest extends AbstractJpaIntegrationTest { private Target target; - private Action action; + private JpaAction action; @Before public void setupBeforeTest() { - target = new Target("targetId123"); + target = new JpaTarget("targetId123"); target.setDescription("targetId123"); targetManagement.createTarget(target); - action = new Action(); + action = new JpaAction(); action.setActionType(ActionType.SOFT); target.getActions().add(action); action.setTarget(target); actionRepository.save(action); for (int i = 0; i < 10; i++) { - final Action newAction = new Action(); + final JpaAction newAction = new JpaAction(); newAction.setActionType(ActionType.SOFT); newAction.setActive(i % 2 == 0); newAction.setTarget(target); @@ -79,10 +81,9 @@ public class RSQLActionFieldsTest extends AbstractIntegrationTest { private void assertRSQLQuery(final String rsqlParam, final long expectedEntities) { - final Specification parse = RSQLUtility.parse(rsqlParam, ActionFields.class); - final Slice findEnitity = deploymentManagement.findActionsByTarget(parse, target, + final Slice findEnitity = deploymentManagement.findActionsByTarget(rsqlParam, target, new PageRequest(0, 100)); - final long countAllEntities = deploymentManagement.countActionsByTarget(parse, target); + final long countAllEntities = deploymentManagement.countActionsByTarget(rsqlParam, target); assertThat(findEnitity).isNotNull(); assertThat(countAllEntities).isEqualTo(expectedEntities); } diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetFieldTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetFieldTest.java similarity index 75% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetFieldTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetFieldTest.java index 6b1682820..6604e3152 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetFieldTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetFieldTest.java @@ -6,19 +6,21 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.rsql; +package org.eclipse.hawkbit.repository.jpa.rsql; import static org.fest.assertions.api.Assertions.assertThat; import static org.junit.Assert.fail; import java.util.Arrays; -import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.TestDataUtil; import org.eclipse.hawkbit.repository.DistributionSetFields; +import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException; +import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetMetadata; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag; 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.util.TestdataFactory; import org.junit.Before; import org.junit.Test; import org.springframework.data.domain.Page; @@ -30,28 +32,28 @@ import ru.yandex.qatools.allure.annotations.Stories; @Features("Component Tests - Repository") @Stories("RSQL filter distribution set") -public class RSQLDistributionSetFieldTest extends AbstractIntegrationTest { +public class RSQLDistributionSetFieldTest extends AbstractJpaIntegrationTest { @Before public void seuptBeforeTest() { - DistributionSet ds = TestDataUtil.generateDistributionSet("DS", softwareManagement, distributionSetManagement); + DistributionSet ds = testdataFactory.createDistributionSet("DS"); ds.setDescription("DS"); ds = distributionSetManagement.updateDistributionSet(ds); distributionSetManagement - .createDistributionSetMetadata(new DistributionSetMetadata("metaKey", ds, "metaValue")); + .createDistributionSetMetadata(new JpaDistributionSetMetadata("metaKey", ds, "metaValue")); - DistributionSet ds2 = TestDataUtil - .generateDistributionSets("NewDS", 3, softwareManagement, distributionSetManagement).get(0); + DistributionSet ds2 = testdataFactory.createDistributionSets("NewDS", 3).get(0); ds2.setDescription("DS%"); ds2 = distributionSetManagement.updateDistributionSet(ds2); - distributionSetManagement.createDistributionSetMetadata(new DistributionSetMetadata("metaKey", ds2, "value")); + distributionSetManagement + .createDistributionSetMetadata(new JpaDistributionSetMetadata("metaKey", ds2, "value")); - final DistributionSetTag targetTag = tagManagement.createDistributionSetTag(new DistributionSetTag("Tag1")); - tagManagement.createDistributionSetTag(new DistributionSetTag("Tag2")); - tagManagement.createDistributionSetTag(new DistributionSetTag("Tag3")); - tagManagement.createDistributionSetTag(new DistributionSetTag("Tag4")); + final DistributionSetTag targetTag = tagManagement.createDistributionSetTag(new JpaDistributionSetTag("Tag1")); + tagManagement.createDistributionSetTag(new JpaDistributionSetTag("Tag2")); + tagManagement.createDistributionSetTag(new JpaDistributionSetTag("Tag3")); + tagManagement.createDistributionSetTag(new JpaDistributionSetTag("Tag4")); distributionSetManagement.assignTag(Arrays.asList(ds.getId(), ds2.getId()), targetTag); } @@ -86,10 +88,12 @@ public class RSQLDistributionSetFieldTest extends AbstractIntegrationTest { @Test @Description("Test filter distribution set by version") public void testFilterByParameterVersion() { - assertRSQLQuery(DistributionSetFields.VERSION.name() + "==v1.0", 2); - assertRSQLQuery(DistributionSetFields.VERSION.name() + "!=v1.0", 2); - assertRSQLQuery(DistributionSetFields.VERSION.name() + "=in=(v1.0,v1.1)", 3); - assertRSQLQuery(DistributionSetFields.VERSION.name() + "=out=(v1.0,error)", 2); + assertRSQLQuery(DistributionSetFields.VERSION.name() + "==" + TestdataFactory.DEFAULT_VERSION, 1); + assertRSQLQuery(DistributionSetFields.VERSION.name() + "!=" + TestdataFactory.DEFAULT_VERSION, 3); + assertRSQLQuery( + DistributionSetFields.VERSION.name() + "=in=(" + TestdataFactory.DEFAULT_VERSION + ",1.0.0,1.0.1)", 3); + assertRSQLQuery(DistributionSetFields.VERSION.name() + "=out=(" + TestdataFactory.DEFAULT_VERSION + ",error)", + 3); } @Test @@ -118,10 +122,10 @@ public class RSQLDistributionSetFieldTest extends AbstractIntegrationTest { @Test @Description("Test filter distribution set by type") public void testFilterByType() { - assertRSQLQuery(DistributionSetFields.TYPE.name() + "==ecl_os_app_jvm", 4); + assertRSQLQuery(DistributionSetFields.TYPE.name() + "==" + TestdataFactory.DS_TYPE_DEFAULT, 4); assertRSQLQuery(DistributionSetFields.TYPE.name() + "==noExist*", 0); - assertRSQLQuery(DistributionSetFields.TYPE.name() + "=in=(ecl_os_app_jvm,ecl)", 4); - assertRSQLQuery(DistributionSetFields.TYPE.name() + "=out=(ecl_os_app_jvm)", 0); + assertRSQLQuery(DistributionSetFields.TYPE.name() + "=in=(" + TestdataFactory.DS_TYPE_DEFAULT + ",ecl)", 4); + assertRSQLQuery(DistributionSetFields.TYPE.name() + "=out=(" + TestdataFactory.DS_TYPE_DEFAULT + ")", 0); } @Test @@ -137,8 +141,8 @@ public class RSQLDistributionSetFieldTest extends AbstractIntegrationTest { } private void assertRSQLQuery(final String rsqlParam, final long excpectedEntity) { - final Page find = distributionSetManagement.findDistributionSetsAll( - RSQLUtility.parse(rsqlParam, DistributionSetFields.class), new PageRequest(0, 100), false); + final Page find = distributionSetManagement.findDistributionSetsAll(rsqlParam, + new PageRequest(0, 100), false); final long countAll = find.getTotalElements(); assertThat(find).as("Founded entity is should not be null").isNotNull(); assertThat(countAll).as("Founded entity size is wrong").isEqualTo(excpectedEntity); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetMetadataFieldsTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetMetadataFieldsTest.java similarity index 83% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetMetadataFieldsTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetMetadataFieldsTest.java index 755e5a61f..65b677693 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetMetadataFieldsTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetMetadataFieldsTest.java @@ -6,16 +6,16 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.rsql; +package org.eclipse.hawkbit.repository.jpa.rsql; import static org.fest.assertions.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; -import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.TestDataUtil; import org.eclipse.hawkbit.repository.DistributionSetMetadataFields; +import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetMetadata; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetMetadata; import org.junit.Before; @@ -29,19 +29,18 @@ import ru.yandex.qatools.allure.annotations.Stories; @Features("Component Tests - Repository") @Stories("RSQL filter distribution set metadata") -public class RSQLDistributionSetMetadataFieldsTest extends AbstractIntegrationTest { +public class RSQLDistributionSetMetadataFieldsTest extends AbstractJpaIntegrationTest { private Long distributionSetId; @Before public void setupBeforeTest() { - final DistributionSet distributionSet = TestDataUtil.generateDistributionSet("DS", softwareManagement, - distributionSetManagement); + final DistributionSet distributionSet = testdataFactory.createDistributionSet("DS"); distributionSetId = distributionSet.getId(); final List metadata = new ArrayList<>(); for (int i = 0; i < 5; i++) { - metadata.add(new DistributionSetMetadata("" + i, distributionSet, "" + i)); + metadata.add(new JpaDistributionSetMetadata("" + i, distributionSet, "" + i)); } distributionSetManagement.createDistributionSetMetadata(metadata); @@ -68,8 +67,7 @@ public class RSQLDistributionSetMetadataFieldsTest extends AbstractIntegrationTe private void assertRSQLQuery(final String rsqlParam, final long expectedEntities) { final Page findEnitity = distributionSetManagement - .findDistributionSetMetadataByDistributionSetId(distributionSetId, - RSQLUtility.parse(rsqlParam, DistributionSetMetadataFields.class), new PageRequest(0, 100)); + .findDistributionSetMetadataByDistributionSetId(distributionSetId, rsqlParam, new PageRequest(0, 100)); final long countAllEntities = findEnitity.getTotalElements(); assertThat(findEnitity).isNotNull(); assertThat(countAllEntities).isEqualTo(expectedEntities); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLRolloutGroupFields.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLRolloutGroupFields.java similarity index 84% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLRolloutGroupFields.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLRolloutGroupFields.java index 78d333826..fd48aed94 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLRolloutGroupFields.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLRolloutGroupFields.java @@ -6,18 +6,18 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.rsql; +package org.eclipse.hawkbit.repository.jpa.rsql; import static org.fest.assertions.api.Assertions.assertThat; -import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.TestDataUtil; import org.eclipse.hawkbit.repository.RolloutGroupFields; +import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; +import org.eclipse.hawkbit.repository.jpa.model.JpaRollout; 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.RolloutGroupConditionBuilder; import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessCondition; +import org.eclipse.hawkbit.repository.model.RolloutGroupConditionBuilder; import org.junit.Before; import org.junit.Test; import org.springframework.data.domain.Page; @@ -29,7 +29,7 @@ import ru.yandex.qatools.allure.annotations.Stories; @Features("Component Tests - Repository") @Stories("RSQL filter rollout group") -public class RSQLRolloutGroupFields extends AbstractIntegrationTest { +public class RSQLRolloutGroupFields extends AbstractJpaIntegrationTest { private Long rolloutGroupId; private Rollout rollout; @@ -37,9 +37,8 @@ public class RSQLRolloutGroupFields extends AbstractIntegrationTest { @Before public void seuptBeforeTest() { 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(""); rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*"); rollout = rolloutManagement.findRolloutById(rollout.getId()); this.rolloutGroupId = rollout.getRolloutGroups().get(0).getId(); @@ -75,8 +74,8 @@ public class RSQLRolloutGroupFields extends AbstractIntegrationTest { } private void assertRSQLQuery(final String rsqlParam, final long expcetedTargets) { - final Page findTargetPage = rolloutGroupManagement.findRolloutGroupsByPredicate(rollout, - RSQLUtility.parse(rsqlParam, RolloutGroupFields.class), new PageRequest(0, 100)); + final Page findTargetPage = rolloutGroupManagement.findRolloutGroupsAll(rollout, rsqlParam, + new PageRequest(0, 100)); final long countTargetsAll = findTargetPage.getTotalElements(); assertThat(findTargetPage).isNotNull(); assertThat(countTargetsAll).isEqualTo(expcetedTargets); @@ -84,7 +83,7 @@ public class RSQLRolloutGroupFields extends AbstractIntegrationTest { private Rollout createRollout(final String name, final int amountGroups, final long distributionSetId, final String targetFilterQuery) { - final Rollout rollout = new Rollout(); + final Rollout rollout = new JpaRollout(); rollout.setDistributionSet(distributionSetManagement.findDistributionSetById(distributionSetId)); rollout.setName(name); rollout.setTargetFilterQuery(targetFilterQuery); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleFieldTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleFieldTest.java similarity index 75% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleFieldTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleFieldTest.java index 0c113fd2b..47732dac2 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleFieldTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleFieldTest.java @@ -6,14 +6,17 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.rsql; +package org.eclipse.hawkbit.repository.jpa.rsql; import static org.fest.assertions.api.Assertions.assertThat; -import org.eclipse.hawkbit.AbstractIntegrationTest; import org.eclipse.hawkbit.repository.SoftwareModuleFields; +import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleMetadata; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; +import org.eclipse.hawkbit.repository.util.TestdataFactory; import org.junit.Before; import org.junit.Test; import org.springframework.data.domain.Page; @@ -25,22 +28,22 @@ import ru.yandex.qatools.allure.annotations.Stories; @Features("Component Tests - Repository") @Stories("RSQL filter software module") -public class RSQLSoftwareModuleFieldTest extends AbstractIntegrationTest { +public class RSQLSoftwareModuleFieldTest extends AbstractJpaIntegrationTest { @Before public void setupBeforeTest() { - final SoftwareModule ah = softwareManagement - .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", "agent-hub", "")); - softwareManagement.createSoftwareModule(new SoftwareModule(runtimeType, "oracle-jre", "1.7.2", "aa", "")); - softwareManagement.createSoftwareModule(new SoftwareModule(osType, "poky", "3.0.2", "aa", "")); + final JpaSoftwareModule ah = (JpaSoftwareModule) softwareManagement + .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", "agent-hub", "")); + softwareManagement.createSoftwareModule(new JpaSoftwareModule(runtimeType, "oracle-jre", "1.7.2", "aa", "")); + softwareManagement.createSoftwareModule(new JpaSoftwareModule(osType, "poky", "3.0.2", "aa", "")); - final SoftwareModule ah2 = softwareManagement - .createSoftwareModule(new SoftwareModule(appType, "agent-hub2", "1.0.1", "agent-hub2", "")); + final JpaSoftwareModule ah2 = (JpaSoftwareModule) softwareManagement + .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub2", "1.0.1", "agent-hub2", "")); - final SoftwareModuleMetadata softwareModuleMetadata = new SoftwareModuleMetadata("metaKey", ah, "metaValue"); + final SoftwareModuleMetadata softwareModuleMetadata = new JpaSoftwareModuleMetadata("metaKey", ah, "metaValue"); softwareManagement.createSoftwareModuleMetadata(softwareModuleMetadata); - final SoftwareModuleMetadata softwareModuleMetadata2 = new SoftwareModuleMetadata("metaKey", ah2, "value"); + final SoftwareModuleMetadata softwareModuleMetadata2 = new JpaSoftwareModuleMetadata("metaKey", ah2, "value"); softwareManagement.createSoftwareModuleMetadata(softwareModuleMetadata2); } @@ -82,10 +85,10 @@ public class RSQLSoftwareModuleFieldTest extends AbstractIntegrationTest { @Test @Description("Test filter software module by type") public void testFilterByType() { - assertRSQLQuery(SoftwareModuleFields.TYPE.name() + "==application", 2); + assertRSQLQuery(SoftwareModuleFields.TYPE.name() + "==" + TestdataFactory.SM_TYPE_APP, 2); assertRSQLQuery(SoftwareModuleFields.TYPE.name() + "==noExist*", 0); - assertRSQLQuery(SoftwareModuleFields.TYPE.name() + "=in=(application)", 2); - assertRSQLQuery(SoftwareModuleFields.TYPE.name() + "=out=(application)", 2); + assertRSQLQuery(SoftwareModuleFields.TYPE.name() + "=in=(" + TestdataFactory.SM_TYPE_APP + ")", 2); + assertRSQLQuery(SoftwareModuleFields.TYPE.name() + "=out=(" + TestdataFactory.SM_TYPE_APP + ")", 2); } @Test @@ -101,8 +104,8 @@ public class RSQLSoftwareModuleFieldTest extends AbstractIntegrationTest { } private void assertRSQLQuery(final String rsqlParam, final long excpectedEntity) { - final Page find = softwareManagement.findSoftwareModulesByPredicate( - RSQLUtility.parse(rsqlParam, SoftwareModuleFields.class), new PageRequest(0, 100)); + final Page find = softwareManagement.findSoftwareModulesByPredicate(rsqlParam, + new PageRequest(0, 100)); final long countAll = find.getTotalElements(); assertThat(find).isNotNull(); assertThat(countAll).isEqualTo(excpectedEntity); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleMetadataFieldsTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleMetadataFieldsTest.java similarity index 80% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleMetadataFieldsTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleMetadataFieldsTest.java index 44fa3e3cd..3f843bffc 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleMetadataFieldsTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleMetadataFieldsTest.java @@ -6,18 +6,19 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.rsql; +package org.eclipse.hawkbit.repository.jpa.rsql; import static org.fest.assertions.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; -import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.TestDataUtil; import org.eclipse.hawkbit.repository.SoftwareModuleMetadataFields; +import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleMetadata; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; +import org.eclipse.hawkbit.repository.util.TestdataFactory; import org.junit.Before; import org.junit.Test; import org.springframework.data.domain.Page; @@ -29,20 +30,19 @@ import ru.yandex.qatools.allure.annotations.Stories; @Features("Component Tests - Repository") @Stories("RSQL filter software module metadata") -public class RSQLSoftwareModuleMetadataFieldsTest extends AbstractIntegrationTest { +public class RSQLSoftwareModuleMetadataFieldsTest extends AbstractJpaIntegrationTest { private Long softwareModuleId; @Before public void setupBeforeTest() { - final SoftwareModule softwareModule = softwareManagement.createSoftwareModule( - new SoftwareModule(TestDataUtil.findOrCreateSoftwareModuleType(softwareManagement, "application"), - "application", "1.0.0", "Desc", "vendor Limited, California")); + final SoftwareModule softwareModule = testdataFactory.createSoftwareModule(TestdataFactory.SM_TYPE_APP); + softwareModuleId = softwareModule.getId(); final List metadata = new ArrayList<>(); for (int i = 0; i < 5; i++) { - metadata.add(new SoftwareModuleMetadata("" + i, softwareModule, "" + i)); + metadata.add(new JpaSoftwareModuleMetadata("" + i, softwareModule, "" + i)); } softwareManagement.createSoftwareModuleMetadata(metadata); @@ -70,8 +70,7 @@ public class RSQLSoftwareModuleMetadataFieldsTest extends AbstractIntegrationTes private void assertRSQLQuery(final String rsqlParam, final long expectedEntities) { final Page findEnitity = softwareManagement - .findSoftwareModuleMetadataBySoftwareModuleId(softwareModuleId, - RSQLUtility.parse(rsqlParam, SoftwareModuleMetadataFields.class), new PageRequest(0, 100)); + .findSoftwareModuleMetadataBySoftwareModuleId(softwareModuleId, rsqlParam, new PageRequest(0, 100)); final long countAllEntities = findEnitity.getTotalElements(); assertThat(findEnitity).isNotNull(); assertThat(countAllEntities).isEqualTo(expectedEntities); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleTypeFieldsTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleTypeFieldsTest.java similarity index 87% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleTypeFieldsTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleTypeFieldsTest.java index 268bddf50..e1538aaee 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleTypeFieldsTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleTypeFieldsTest.java @@ -6,12 +6,12 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.rsql; +package org.eclipse.hawkbit.repository.jpa.rsql; import static org.fest.assertions.api.Assertions.assertThat; -import org.eclipse.hawkbit.AbstractIntegrationTest; import org.eclipse.hawkbit.repository.SoftwareModuleTypeFields; +import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.junit.Test; import org.springframework.data.domain.Page; @@ -23,7 +23,7 @@ import ru.yandex.qatools.allure.annotations.Stories; @Features("Component Tests - Repository") @Stories("RSQL filter software module test type") -public class RSQLSoftwareModuleTypeFieldsTest extends AbstractIntegrationTest { +public class RSQLSoftwareModuleTypeFieldsTest extends AbstractJpaIntegrationTest { @Test @Description("Test filter software module test type by id") @@ -34,7 +34,7 @@ public class RSQLSoftwareModuleTypeFieldsTest extends AbstractIntegrationTest { @Test @Description("Test filter software module test type by name") public void testFilterByParameterName() { - assertRSQLQuery(SoftwareModuleTypeFields.NAME.name() + "==ECL*", 3); + assertRSQLQuery(SoftwareModuleTypeFields.NAME.name() + "==Firmware", 1); } @Test @@ -55,12 +55,12 @@ public class RSQLSoftwareModuleTypeFieldsTest extends AbstractIntegrationTest { @Test @Description("Test filter software module test type by max") public void testFilterByMaxAssignment() { - assertRSQLQuery(SoftwareModuleTypeFields.MAXASSIGNMENTS.name() + "==1", 3); + assertRSQLQuery(SoftwareModuleTypeFields.MAXASSIGNMENTS.name() + "==1", 2); } private void assertRSQLQuery(final String rsqlParam, final long excpectedEntity) { - final Page find = softwareManagement.findSoftwareModuleTypesByPredicate( - RSQLUtility.parse(rsqlParam, SoftwareModuleTypeFields.class), new PageRequest(0, 100)); + final Page find = softwareManagement.findSoftwareModuleTypesAll(rsqlParam, + new PageRequest(0, 100)); final long countAll = find.getTotalElements(); assertThat(find).isNotNull(); assertThat(countAll).isEqualTo(excpectedEntity); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLTagFieldsTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTagFieldsTest.java similarity index 87% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLTagFieldsTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTagFieldsTest.java index b35ed13d1..3772bb372 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLTagFieldsTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTagFieldsTest.java @@ -6,12 +6,14 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.rsql; +package org.eclipse.hawkbit.repository.jpa.rsql; import static org.fest.assertions.api.Assertions.assertThat; -import org.eclipse.hawkbit.AbstractIntegrationTest; import org.eclipse.hawkbit.repository.TagFields; +import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag; import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.repository.model.TargetTag; import org.junit.Before; @@ -25,15 +27,15 @@ import ru.yandex.qatools.allure.annotations.Stories; @Features("Component Tests - Repository") @Stories("RSQL filter target and distribution set tags") -public class RSQLTagFieldsTest extends AbstractIntegrationTest { +public class RSQLTagFieldsTest extends AbstractJpaIntegrationTest { @Before public void seuptBeforeTest() { for (int i = 0; i < 5; i++) { - final TargetTag targetTag = new TargetTag("" + i, "" + i, i % 2 == 0 ? "red" : "blue"); + final TargetTag targetTag = new JpaTargetTag("" + i, "" + i, i % 2 == 0 ? "red" : "blue"); tagManagement.createTargetTag(targetTag); - final DistributionSetTag distributionSetTag = new DistributionSetTag("" + i, "" + i, + final DistributionSetTag distributionSetTag = new JpaDistributionSetTag("" + i, "" + i, i % 2 == 0 ? "red" : "blue"); tagManagement.createDistributionSetTag(distributionSetTag); } @@ -101,8 +103,8 @@ public class RSQLTagFieldsTest extends AbstractIntegrationTest { private void assertRSQLQueryDistributionSet(final String rsqlParam, final long expectedEntities) { - final Page findEnitity = tagManagement - .findAllDistributionSetTags(RSQLUtility.parse(rsqlParam, TagFields.class), new PageRequest(0, 100)); + final Page findEnitity = tagManagement.findAllDistributionSetTags(rsqlParam, + new PageRequest(0, 100)); final long countAllEntities = findEnitity.getTotalElements(); assertThat(findEnitity).isNotNull(); assertThat(countAllEntities).isEqualTo(expectedEntities); @@ -110,8 +112,7 @@ public class RSQLTagFieldsTest extends AbstractIntegrationTest { private void assertRSQLQueryTarget(final String rsqlParam, final long expectedEntities) { - final Page findEnitity = tagManagement - .findAllTargetTags(RSQLUtility.parse(rsqlParam, TagFields.class), new PageRequest(0, 100)); + final Page findEnitity = tagManagement.findAllTargetTags(rsqlParam, new PageRequest(0, 100)); final long countAllEntities = findEnitity.getTotalElements(); assertThat(findEnitity).isNotNull(); assertThat(countAllEntities).isEqualTo(expectedEntities); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLTargetFieldTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTargetFieldTest.java similarity index 79% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLTargetFieldTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTargetFieldTest.java index 54efab860..f21e4c938 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLTargetFieldTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTargetFieldTest.java @@ -6,21 +6,25 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.rsql; +package org.eclipse.hawkbit.repository.jpa.rsql; import static org.fest.assertions.api.Assertions.assertThat; import static org.junit.Assert.fail; import java.util.Arrays; -import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.TestDataUtil; import org.eclipse.hawkbit.repository.TargetFields; +import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException; +import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetInfo; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetInfo; import org.eclipse.hawkbit.repository.model.TargetTag; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; +import org.eclipse.hawkbit.repository.util.TestdataFactory; import org.junit.Before; import org.junit.Test; import org.springframework.data.domain.Page; @@ -32,35 +36,33 @@ import ru.yandex.qatools.allure.annotations.Stories; @Features("Component Tests - Repository") @Stories("RSQL filter target") -public class RSQLTargetFieldTest extends AbstractIntegrationTest { +public class RSQLTargetFieldTest extends AbstractJpaIntegrationTest { @Before public void seuptBeforeTest() { - final DistributionSet ds = TestDataUtil.generateDistributionSet("AssignedDs", softwareManagement, - distributionSetManagement); + final DistributionSet ds = testdataFactory.createDistributionSet("AssignedDs"); - final Target target = new Target("targetId123"); + final Target target = entityFactory.generateTarget("targetId123"); target.setDescription("targetId123"); - final TargetInfo targetInfo = new TargetInfo(target); + final TargetInfo targetInfo = target.getTargetInfo(); targetInfo.getControllerAttributes().put("revision", "1.1"); - target.setTargetInfo(targetInfo); - target.getTargetInfo().setUpdateStatus(TargetUpdateStatus.PENDING); + ((JpaTargetInfo) target.getTargetInfo()).setUpdateStatus(TargetUpdateStatus.PENDING); targetManagement.createTarget(target); - final Target target2 = new Target("targetId1234"); + final JpaTarget target2 = new JpaTarget("targetId1234"); target2.setDescription("targetId1234"); - final TargetInfo targetInfo2 = new TargetInfo(target2); + final TargetInfo targetInfo2 = new JpaTargetInfo(target2); targetInfo2.getControllerAttributes().put("revision", "1.2"); target2.setTargetInfo(targetInfo2); targetManagement.createTarget(target2); - targetManagement.createTarget(new Target("targetId1235")); - targetManagement.createTarget(new Target("targetId1236")); + targetManagement.createTarget(new JpaTarget("targetId1235")); + targetManagement.createTarget(new JpaTarget("targetId1236")); - final TargetTag targetTag = tagManagement.createTargetTag(new TargetTag("Tag1")); - tagManagement.createTargetTag(new TargetTag("Tag2")); - tagManagement.createTargetTag(new TargetTag("Tag3")); - tagManagement.createTargetTag(new TargetTag("Tag4")); + final TargetTag targetTag = tagManagement.createTargetTag(new JpaTargetTag("Tag1")); + tagManagement.createTargetTag(new JpaTargetTag("Tag2")); + tagManagement.createTargetTag(new JpaTargetTag("Tag3")); + tagManagement.createTargetTag(new JpaTargetTag("Tag4")); targetManagement.assignTag(Arrays.asList(target.getControllerId(), target2.getControllerId()), targetTag); @@ -145,11 +147,13 @@ public class RSQLTargetFieldTest extends AbstractIntegrationTest { @Test @Description("Test filter target by assigned ds version") public void testFilterByAssignedDsVersion() { - assertRSQLQuery(TargetFields.ASSIGNEDDS.name() + ".version==v1.0", 1); + assertRSQLQuery(TargetFields.ASSIGNEDDS.name() + ".version==" + TestdataFactory.DEFAULT_VERSION, 1); assertRSQLQuery(TargetFields.ASSIGNEDDS.name() + ".version==*1*", 1); assertRSQLQuery(TargetFields.ASSIGNEDDS.name() + ".version==noExist*", 0); - assertRSQLQuery(TargetFields.ASSIGNEDDS.name() + ".version=in=(v1.0,notexist)", 1); - assertRSQLQuery(TargetFields.ASSIGNEDDS.name() + ".version=out=(v1.0,notexist)", 0); + assertRSQLQuery( + TargetFields.ASSIGNEDDS.name() + ".version=in=(" + TestdataFactory.DEFAULT_VERSION + ",notexist)", 1); + assertRSQLQuery( + TargetFields.ASSIGNEDDS.name() + ".version=out=(" + TestdataFactory.DEFAULT_VERSION + ",notexist)", 0); } @Test @@ -163,8 +167,7 @@ public class RSQLTargetFieldTest extends AbstractIntegrationTest { } private void assertRSQLQuery(final String rsqlParam, final long expcetedTargets) { - final Page findTargetPage = targetManagement - .findTargetsAll(RSQLUtility.parse(rsqlParam, TargetFields.class), new PageRequest(0, 100)); + final Page findTargetPage = targetManagement.findTargetsAll(rsqlParam, new PageRequest(0, 100)); final long countTargetsAll = findTargetPage.getTotalElements(); assertThat(findTargetPage).isNotNull(); assertThat(countTargetsAll).isEqualTo(expcetedTargets); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLUtilityTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLUtilityTest.java similarity index 98% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLUtilityTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLUtilityTest.java index 356464bc2..04901d948 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLUtilityTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLUtilityTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.rsql; +package org.eclipse.hawkbit.repository.jpa.rsql; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; @@ -30,6 +30,8 @@ import org.eclipse.hawkbit.repository.DistributionSetFields; import org.eclipse.hawkbit.repository.FieldNameProvider; import org.eclipse.hawkbit.repository.SoftwareModuleFields; import org.eclipse.hawkbit.repository.TargetFields; +import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException; +import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/tenancy/MultiTenancyEntityTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/tenancy/MultiTenancyEntityTest.java similarity index 91% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/tenancy/MultiTenancyEntityTest.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/tenancy/MultiTenancyEntityTest.java index 67b9b5a26..86a0389d5 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/tenancy/MultiTenancyEntityTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/tenancy/MultiTenancyEntityTest.java @@ -6,16 +6,18 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.tenancy; +package org.eclipse.hawkbit.repository.jpa.tenancy; import static org.fest.assertions.api.Assertions.assertThat; -import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.WithSpringAuthorityRule; -import org.eclipse.hawkbit.WithUser; +import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; import org.eclipse.hawkbit.repository.model.DistributionSet; -import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.Target; +import org.eclipse.hawkbit.repository.util.WithSpringAuthorityRule; +import org.eclipse.hawkbit.repository.util.WithUser; import org.junit.Test; import org.springframework.data.domain.Page; import org.springframework.data.domain.Slice; @@ -32,7 +34,7 @@ import ru.yandex.qatools.allure.annotations.Stories; */ @Features("Component Tests - Repository") @Stories("Multi Tenancy") -public class MultiTenancyEntityTest extends AbstractIntegrationTest { +public class MultiTenancyEntityTest extends AbstractJpaIntegrationTest { @Test @Description(value = "Ensures that multiple targets with same controller-ID can be created for different tenants.") @@ -162,7 +164,7 @@ public class MultiTenancyEntityTest extends AbstractIntegrationTest { private Target createTargetForTenant(final String controllerId, final String tenant) throws Exception { return securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant), - () -> targetManagement.createTarget(new Target(controllerId))); + () -> targetManagement.createTarget(new JpaTarget(controllerId))); } private Slice findTargetsForTenant(final String tenant) throws Exception { @@ -180,19 +182,19 @@ public class MultiTenancyEntityTest extends AbstractIntegrationTest { private DistributionSet createDistributionSetForTenant(final String name, final String version, final String tenant) throws Exception { return securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant), () -> { - final DistributionSet ds = new DistributionSet(); + final JpaDistributionSet ds = new JpaDistributionSet(); ds.setName(name); ds.setTenant(tenant); ds.setVersion(version); ds.setType(distributionSetManagement - .createDistributionSetType(new DistributionSetType("typetest", "test", "foobar"))); + .createDistributionSetType(new JpaDistributionSetType("typetest", "test", "foobar"))); return distributionSetManagement.createDistributionSet(ds); }); } private Page findDistributionSetForTenant(final String tenant) throws Exception { return securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant), - () -> distributionSetManagement.findDistributionSetsAll(pageReq, false, false)); + () -> distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, false)); } } diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/utils/MultipleInvokeHelper.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/utils/MultipleInvokeHelper.java similarity index 98% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/utils/MultipleInvokeHelper.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/utils/MultipleInvokeHelper.java index d40fe1fd0..c4710ca4b 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/utils/MultipleInvokeHelper.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/utils/MultipleInvokeHelper.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.utils; +package org.eclipse.hawkbit.repository.jpa.utils; import java.util.concurrent.Callable; diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/utils/SuccessCondition.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/utils/SuccessCondition.java similarity index 92% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/utils/SuccessCondition.java rename to hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/utils/SuccessCondition.java index 6c9553dc8..b5e421107 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/utils/SuccessCondition.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/utils/SuccessCondition.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.utils; +package org.eclipse.hawkbit.repository.jpa.utils; /** * SuccessCondition Interface. diff --git a/hawkbit-repository/src/test/resources/application-test.properties b/hawkbit-repository/hawkbit-repository-jpa/src/test/resources/application-test.properties similarity index 100% rename from hawkbit-repository/src/test/resources/application-test.properties rename to hawkbit-repository/hawkbit-repository-jpa/src/test/resources/application-test.properties diff --git a/hawkbit-repository/hawkbit-repository-test/pom.xml b/hawkbit-repository/hawkbit-repository-test/pom.xml new file mode 100644 index 000000000..4a05735ac --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-test/pom.xml @@ -0,0 +1,75 @@ + + + 4.0.0 + + org.eclipse.hawkbit + hawkbit-repository + 0.2.0-SNAPSHOT + + hawkbit-repository-test + hawkBit :: Repository Test Utilities + + + + org.eclipse.hawkbit + hawkbit-repository-api + ${project.version} + + + org.eclipse.hawkbit + hawkbit-repository-core + ${project.version} + + + org.eclipse.hawkbit + hawkbit-artifact-repository-mongo + ${project.version} + + + org.springframework + spring-context-support + + + de.flapdoodle.embed + de.flapdoodle.embed.mongo + + + net._01001111 + jlorem + + + commons-io + commons-io + 2.5 + + + org.springframework.boot + spring-boot-starter-test + + + org.springframework.security + spring-security-config + + + org.springframework.security + spring-security-aspects + + + org.springframework + spring-test + + + org.springframework.security + spring-security-web + + + \ No newline at end of file diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/AbstractIntegrationTest.java b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/AbstractIntegrationTest.java similarity index 57% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/AbstractIntegrationTest.java rename to hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/AbstractIntegrationTest.java index 2649a9060..c2bd61676 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/AbstractIntegrationTest.java +++ b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/AbstractIntegrationTest.java @@ -6,47 +6,25 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit; +package org.eclipse.hawkbit.repository.util; -import static org.fest.assertions.api.Assertions.assertThat; - -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; - -import org.eclipse.hawkbit.cache.TenantAwareCacheManager; -import org.eclipse.hawkbit.repository.ActionRepository; -import org.eclipse.hawkbit.repository.ActionStatusRepository; +import org.eclipse.hawkbit.ExcludePathAwareShallowETagFilter; import org.eclipse.hawkbit.repository.ArtifactManagement; import org.eclipse.hawkbit.repository.ControllerManagement; import org.eclipse.hawkbit.repository.DeploymentManagement; import org.eclipse.hawkbit.repository.DistributionSetManagement; -import org.eclipse.hawkbit.repository.DistributionSetRepository; -import org.eclipse.hawkbit.repository.DistributionSetTagRepository; -import org.eclipse.hawkbit.repository.DistributionSetTypeRepository; -import org.eclipse.hawkbit.repository.ExternalArtifactRepository; -import org.eclipse.hawkbit.repository.LocalArtifactRepository; +import org.eclipse.hawkbit.repository.EntityFactory; +import org.eclipse.hawkbit.repository.RepositoryConstants; import org.eclipse.hawkbit.repository.RolloutGroupManagement; -import org.eclipse.hawkbit.repository.RolloutGroupRepository; import org.eclipse.hawkbit.repository.RolloutManagement; -import org.eclipse.hawkbit.repository.RolloutRepository; import org.eclipse.hawkbit.repository.SoftwareManagement; -import org.eclipse.hawkbit.repository.SoftwareModuleMetadataRepository; -import org.eclipse.hawkbit.repository.SoftwareModuleRepository; -import org.eclipse.hawkbit.repository.SoftwareModuleTypeRepository; import org.eclipse.hawkbit.repository.SystemManagement; import org.eclipse.hawkbit.repository.TagManagement; import org.eclipse.hawkbit.repository.TargetFilterQueryManagement; -import org.eclipse.hawkbit.repository.TargetInfoRepository; import org.eclipse.hawkbit.repository.TargetManagement; -import org.eclipse.hawkbit.repository.TargetRepository; -import org.eclipse.hawkbit.repository.TargetTagRepository; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; -import org.eclipse.hawkbit.repository.TenantMetaDataRepository; import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; -import org.eclipse.hawkbit.repository.utils.RepositoryDataGenerator.DatabaseCleanupUtil; import org.eclipse.hawkbit.security.DosFilter; import org.eclipse.hawkbit.security.SystemSecurityContext; import org.eclipse.hawkbit.tenancy.TenantAware; @@ -67,7 +45,6 @@ import org.springframework.core.env.Environment; import org.springframework.data.auditing.AuditingHandler; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; -import org.springframework.data.mongodb.gridfs.GridFsOperations; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ActiveProfiles; @@ -76,14 +53,13 @@ import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@SpringApplicationConfiguration(classes = { RepositoryApplicationConfiguration.class, TestConfiguration.class }) @ActiveProfiles({ "test" }) @WithUser(principal = "bumlux", allSpPermissions = true, authorities = "ROLE_CONTROLLER") +@SpringApplicationConfiguration(classes = { TestConfiguration.class }) // destroy the context after each test class because otherwise we get problem // when context is // refreshed we e.g. get two instances of CacheManager which leads to very @@ -94,44 +70,16 @@ public abstract class AbstractIntegrationTest implements EnvironmentAware { protected static final Pageable pageReq = new PageRequest(0, 400); - @PersistenceContext - protected EntityManager entityManager; + /** + * Number of {@link DistributionSetType}s that exist in every test case. One + * generated by using + * {@link TestdataFactory#findOrCreateDefaultTestDsType()} and two + * {@link SystemManagement#getTenantMetadata()}; + */ + protected static final int DEFAULT_DS_TYPES = RepositoryConstants.DEFAULT_DS_TYPES_IN_TENANT + 1; @Autowired - protected TargetRepository targetRepository; - - @Autowired - protected ActionRepository actionRepository; - - @Autowired - protected DistributionSetRepository distributionSetRepository; - - @Autowired - protected SoftwareModuleRepository softwareModuleRepository; - - @Autowired - protected TenantMetaDataRepository tenantMetaDataRepository; - - @Autowired - protected DistributionSetTypeRepository distributionSetTypeRepository; - - @Autowired - protected SoftwareModuleTypeRepository softwareModuleTypeRepository; - - @Autowired - protected TargetTagRepository targetTagRepository; - - @Autowired - protected DistributionSetTagRepository distributionSetTagRepository; - - @Autowired - protected SoftwareModuleMetadataRepository softwareModuleMetadataRepository; - - @Autowired - protected ActionStatusRepository actionStatusRepository; - - @Autowired - protected ExternalArtifactRepository externalArtifactRepository; + protected EntityFactory entityFactory; @Autowired protected SoftwareManagement softwareManagement; @@ -157,15 +105,6 @@ public abstract class AbstractIntegrationTest implements EnvironmentAware { @Autowired protected ArtifactManagement artifactManagement; - @Autowired - protected LocalArtifactRepository artifactRepository; - - @Autowired - protected TargetInfoRepository targetInfoRepository; - - @Autowired - protected GridFsOperations operations; - @Autowired protected WebApplicationContext context; @@ -181,9 +120,6 @@ public abstract class AbstractIntegrationTest implements EnvironmentAware { @Autowired protected SystemManagement systemManagement; - @Autowired - protected TenantAwareCacheManager cacheManager; - @Autowired protected TenantConfigurationManagement tenantConfigurationManagement; @@ -193,19 +129,13 @@ public abstract class AbstractIntegrationTest implements EnvironmentAware { @Autowired protected RolloutGroupManagement rolloutGroupManagement; - @Autowired - protected RolloutGroupRepository rolloutGroupRepository; - - @Autowired - protected RolloutRepository rolloutRepository; - @Autowired protected SystemSecurityContext systemSecurityContext; - protected MockMvc mvc; - @Autowired - protected DatabaseCleanupUtil dbCleanupUtil; + protected TestRepositoryManagement testRepositoryManagement; + + protected MockMvc mvc; protected SoftwareModuleType osType; protected SoftwareModuleType appType; @@ -213,13 +143,14 @@ public abstract class AbstractIntegrationTest implements EnvironmentAware { protected DistributionSetType standardDsType; + @Autowired + protected TestdataFactory testdataFactory; + @Rule public final WithSpringAuthorityRule securityRule = new WithSpringAuthorityRule(); protected Environment environment = null; - private static CIMySqlTestDatabase tesdatabase; - @Override public void setEnvironment(final Environment environment) { this.environment = environment; @@ -228,20 +159,29 @@ public abstract class AbstractIntegrationTest implements EnvironmentAware { @Before public void before() throws Exception { mvc = createMvcWebAppContext().build(); + final String description = "Updated description to have lastmodified available in tests"; - standardDsType = securityRule.runAsPrivileged(() -> systemManagement.getTenantMetadata().getDefaultDsType()); - - osType = securityRule.runAsPrivileged(() -> softwareManagement.findSoftwareModuleTypeByKey("os")); - osType.setDescription("Updated description to have lastmodified available in tests"); + osType = securityRule + .runAsPrivileged(() -> testdataFactory.findOrCreateSoftwareModuleType(TestdataFactory.SM_TYPE_OS)); + osType.setDescription(description); osType = securityRule.runAsPrivileged(() -> softwareManagement.updateSoftwareModuleType(osType)); - appType = securityRule.runAsPrivileged(() -> softwareManagement.findSoftwareModuleTypeByKey("application")); - appType.setDescription("Updated description to have lastmodified available in tests"); + appType = securityRule.runAsPrivileged( + () -> testdataFactory.findOrCreateSoftwareModuleType(TestdataFactory.SM_TYPE_APP, Integer.MAX_VALUE)); + appType.setDescription(description); appType = securityRule.runAsPrivileged(() -> softwareManagement.updateSoftwareModuleType(appType)); - runtimeType = securityRule.runAsPrivileged(() -> softwareManagement.findSoftwareModuleTypeByKey("runtime")); - runtimeType.setDescription("Updated description to have lastmodified available in tests"); + runtimeType = securityRule + .runAsPrivileged(() -> testdataFactory.findOrCreateSoftwareModuleType(TestdataFactory.SM_TYPE_RT)); + runtimeType.setDescription(description); runtimeType = securityRule.runAsPrivileged(() -> softwareManagement.updateSoftwareModuleType(runtimeType)); + + standardDsType = securityRule.runAsPrivileged(() -> testdataFactory.findOrCreateDefaultTestDsType()); + } + + @After + public void after() { + testRepositoryManagement.clearTestRepository(); } protected DefaultMockMvcBuilder createMvcWebAppContext() { @@ -252,59 +192,6 @@ public abstract class AbstractIntegrationTest implements EnvironmentAware { "/rest/v1/softwaremodules/{smId}/artifacts/{artId}/download", "/*/controller/artifacts/**")); } - @BeforeClass - public static void beforeClass() { - createTestdatabaseAndStart(); - } - - private static void createTestdatabaseAndStart() { - if ("MYSQL".equals(System.getProperty("spring.jpa.database"))) { - tesdatabase = new CIMySqlTestDatabase(); - tesdatabase.before(); - } - } - - @AfterClass - public static void afterClass() { - if (tesdatabase != null) { - tesdatabase.after(); - } - } - - @After - public void after() throws Exception { - deleteAllRepos(); - cacheManager.getDirectCacheNames().forEach(name -> cacheManager.getDirectCache(name).clear()); - assertThat(actionStatusRepository.findAll()).isEmpty(); - assertThat(targetRepository.findAll()).isEmpty(); - assertThat(actionRepository.findAll()).isEmpty(); - assertThat(distributionSetRepository.findAll()).isEmpty(); - assertThat(targetTagRepository.findAll()).isEmpty(); - assertThat(distributionSetTagRepository.findAll()).isEmpty(); - assertThat(softwareModuleRepository.findAll()).isEmpty(); - assertThat(softwareModuleTypeRepository.findAll()).isEmpty(); - assertThat(distributionSetTypeRepository.findAll()).isEmpty(); - assertThat(tenantMetaDataRepository.findAll()).isEmpty(); - assertThat(rolloutGroupRepository.findAll()).isEmpty(); - assertThat(rolloutRepository.findAll()).isEmpty(); - } - - @Transactional - protected void deleteAllRepos() throws Exception { - final List tenants = securityRule.runAs(WithSpringAuthorityRule.withUser(false), - () -> systemManagement.findTenants()); - tenants.forEach(tenant -> { - try { - securityRule.runAs(WithSpringAuthorityRule.withUser(false), () -> { - systemManagement.deleteTenant(tenant); - return null; - }); - } catch (final Exception e) { - e.printStackTrace(); - } - }); - } - @Rule public MethodRule watchman = new TestWatchman() { @Override @@ -328,4 +215,25 @@ public abstract class AbstractIntegrationTest implements EnvironmentAware { } } }; + + private static CIMySqlTestDatabase tesdatabase; + + @BeforeClass + public static void beforeClass() { + createTestdatabaseAndStart(); + } + + private static void createTestdatabaseAndStart() { + if ("MYSQL".equals(System.getProperty("spring.jpa.database"))) { + tesdatabase = new CIMySqlTestDatabase(); + tesdatabase.before(); + } + } + + @AfterClass + public static void afterClass() { + if (tesdatabase != null) { + tesdatabase.after(); + } + } } diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/AbstractIntegrationTestWithMongoDB.java b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/AbstractIntegrationTestWithMongoDB.java similarity index 89% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/AbstractIntegrationTestWithMongoDB.java rename to hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/AbstractIntegrationTestWithMongoDB.java index 6d116c5f0..28d8add3a 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/AbstractIntegrationTestWithMongoDB.java +++ b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/AbstractIntegrationTestWithMongoDB.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit; +package org.eclipse.hawkbit.repository.util; import java.io.IOException; import java.net.UnknownHostException; @@ -15,7 +15,9 @@ import java.util.concurrent.atomic.AtomicInteger; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.gridfs.GridFsOperations; import de.flapdoodle.embed.mongo.Command; import de.flapdoodle.embed.mongo.MongodExecutable; @@ -38,10 +40,14 @@ import de.flapdoodle.embed.process.runtime.Network; * */ public abstract class AbstractIntegrationTestWithMongoDB extends AbstractIntegrationTest { + protected static volatile MongodExecutable mongodExecutable = null; private static final AtomicInteger mongoLease = new AtomicInteger(0); private static volatile Integer port; + @Autowired + protected GridFsOperations operations; + @BeforeClass public static void setupMongo() throws UnknownHostException, IOException { mongoLease.incrementAndGet(); @@ -67,8 +73,8 @@ public abstract class AbstractIntegrationTestWithMongoDB extends AbstractIntegra new ArtifactStoreBuilder().defaults(command) .download(new DownloadConfigBuilder().defaultsForCommand(command) .proxyFactory(new HttpProxyFactory( - System.getProperty("http.proxyHost").trim(), - Integer.valueOf(System.getProperty("http.proxyPort")))))); + System.getProperty("http.proxyHost").trim(), Integer + .valueOf(System.getProperty("http.proxyPort")))))); } final IMongodConfig mongodConfig = new MongodConfigBuilder().version(version) @@ -86,7 +92,7 @@ public abstract class AbstractIntegrationTestWithMongoDB extends AbstractIntegra operations.delete(new Query()); } - public void internalShutDownMongo() { + public static void internalShutDownMongo() { if (mongodExecutable != null && mongoLease.decrementAndGet() <= 0) { mongodExecutable.stop(); mongodExecutable = null; diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/CIMySqlTestDatabase.java b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/CIMySqlTestDatabase.java similarity index 70% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/CIMySqlTestDatabase.java rename to hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/CIMySqlTestDatabase.java index 0a9b4b1b3..e6bbe1f6a 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/CIMySqlTestDatabase.java +++ b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/CIMySqlTestDatabase.java @@ -6,10 +6,11 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit; +package org.eclipse.hawkbit.repository.util; import java.sql.Connection; import java.sql.DriverManager; +import java.sql.PreparedStatement; import java.sql.SQLException; import org.apache.commons.lang3.RandomStringUtils; @@ -17,17 +18,20 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * + * {@link Testdatabase} implementation for MySQL. * */ public class CIMySqlTestDatabase implements Testdatabase { - private final static Logger LOG = LoggerFactory.getLogger(CIMySqlTestDatabase.class); + private static final Logger LOG = LoggerFactory.getLogger(CIMySqlTestDatabase.class); private String schemaName; private String uri; private final String username; private final String password; + /** + * Constructor. + */ public CIMySqlTestDatabase() { this.username = System.getProperty("spring.datasource.username"); this.password = System.getProperty("spring.datasource.password"); @@ -43,7 +47,7 @@ public class CIMySqlTestDatabase implements Testdatabase { private void createSchemaUri() { schemaName = "SP" + RandomStringUtils.randomAlphanumeric(10); - this.uri = this.uri.substring(0, uri.lastIndexOf("/") + 1); + this.uri = this.uri.substring(0, uri.lastIndexOf('/') + 1); System.setProperty("spring.datasource.url", uri + schemaName); } @@ -55,10 +59,12 @@ public class CIMySqlTestDatabase implements Testdatabase { private void createSchema() { try (Connection connection = DriverManager.getConnection(uri, username, password)) { - connection.prepareStatement("CREATE SCHEMA " + schemaName + ";").execute(); - LOG.info("Schema {} created on uri {}", schemaName, uri); + try (PreparedStatement statement = connection.prepareStatement("CREATE SCHEMA " + schemaName + ";")) { + statement.execute(); + LOG.info("Schema {} created on uri {}", schemaName, uri); + } } catch (final SQLException e) { - e.printStackTrace(); + LOG.error("Schema creation failed!", e); } } @@ -70,10 +76,12 @@ public class CIMySqlTestDatabase implements Testdatabase { private void dropSchema() { try (Connection connection = DriverManager.getConnection(uri, username, password)) { - connection.prepareStatement("DROP SCHEMA " + schemaName + ";").execute(); - LOG.info("Schema {} dropped on uri {}", schemaName, uri); + try (PreparedStatement statement = connection.prepareStatement("DROP SCHEMA " + schemaName + ";")) { + statement.execute(); + LOG.info("Schema {} dropped on uri {}", schemaName, uri); + } } catch (final SQLException e) { - e.printStackTrace(); + LOG.error("Schema drop failed!", e); } } diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/FreePortFileWriter.java b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/FreePortFileWriter.java similarity index 97% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/FreePortFileWriter.java rename to hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/FreePortFileWriter.java index c67928910..383722a75 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/FreePortFileWriter.java +++ b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/FreePortFileWriter.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit; +package org.eclipse.hawkbit.repository.util; import java.io.File; import java.net.InetSocketAddress; diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/HashGeneratorUtils.java b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/HashGeneratorUtils.java similarity index 74% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/HashGeneratorUtils.java rename to hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/HashGeneratorUtils.java index 10f4ede4c..e222007f1 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/HashGeneratorUtils.java +++ b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/HashGeneratorUtils.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit; +package org.eclipse.hawkbit.repository.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -14,13 +14,10 @@ import java.security.NoSuchAlgorithmException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.google.common.io.BaseEncoding; + /** - * Hash utility calls copied from - * http://www.codejava.net/coding/how-to-calculate-md5-and-sha-hash-values-in- - * java. - * - * - * + * Hash digest utility. */ public final class HashGeneratorUtils { @@ -68,18 +65,11 @@ public final class HashGeneratorUtils { try { final MessageDigest digest = MessageDigest.getInstance(algorithm); final byte[] hashedBytes = digest.digest(message); - return convertByteArrayToHexString(hashedBytes); + return BaseEncoding.base16().lowerCase().encode(hashedBytes); } catch (final NoSuchAlgorithmException e) { - LOG.error("Algorithm could not be find", e); + LOG.error("Algorithm could not be found", e); } return null; } - private static String convertByteArrayToHexString(final byte[] arrayBytes) { - final StringBuilder builder = new StringBuilder(); - for (int i = 0; i < arrayBytes.length; i++) { - builder.append(Integer.toString((arrayBytes[i] & 0xff) + 0x100, 16).substring(1)); - } - return builder.toString(); - } } diff --git a/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/JpaTestRepositoryManagement.java b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/JpaTestRepositoryManagement.java new file mode 100644 index 000000000..7ec5bb407 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/JpaTestRepositoryManagement.java @@ -0,0 +1,50 @@ +/** + * 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.util; + +import java.util.List; + +import org.eclipse.hawkbit.cache.TenantAwareCacheManager; +import org.eclipse.hawkbit.repository.SystemManagement; +import org.eclipse.hawkbit.security.SystemSecurityContext; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +public class JpaTestRepositoryManagement implements TestRepositoryManagement { + + @Autowired + private TenantAwareCacheManager cacheManager; + + @Autowired + private SystemSecurityContext systemSecurityContext; + + @Autowired + private SystemManagement systemManagement; + + @Override + public void clearTestRepository() { + deleteAllRepos(); + cacheManager.getDirectCacheNames().forEach(name -> cacheManager.getDirectCache(name).clear()); + } + + @Transactional + public void deleteAllRepos() { + final List tenants = systemSecurityContext.runAsSystem(() -> systemManagement.findTenants()); + tenants.forEach(tenant -> { + try { + systemSecurityContext.runAsSystem(() -> { + systemManagement.deleteTenant(tenant); + return null; + }); + } catch (final Exception e) { + e.printStackTrace(); + } + }); + } +} diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestConfiguration.java b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/TestConfiguration.java similarity index 88% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestConfiguration.java rename to hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/TestConfiguration.java index d96856557..acbaae2b4 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestConfiguration.java +++ b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/TestConfiguration.java @@ -6,17 +6,16 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit; +package org.eclipse.hawkbit.repository.util; import java.util.concurrent.Executor; import java.util.concurrent.Executors; +import org.eclipse.hawkbit.HawkbitServerProperties; import org.eclipse.hawkbit.cache.CacheConstants; import org.eclipse.hawkbit.cache.TenancyCacheManager; import org.eclipse.hawkbit.cache.TenantAwareCacheManager; -import org.eclipse.hawkbit.repository.model.helper.EventBusHolder; -import org.eclipse.hawkbit.repository.utils.RepositoryDataGenerator; -import org.eclipse.hawkbit.repository.utils.RepositoryDataGenerator.DatabaseCleanupUtil; +import org.eclipse.hawkbit.repository.jpa.model.helper.EventBusHolder; import org.eclipse.hawkbit.security.DdiSecurityProperties; import org.eclipse.hawkbit.security.SecurityContextTenantAware; import org.eclipse.hawkbit.security.SpringSecurityAuditorAware; @@ -51,14 +50,14 @@ import com.mongodb.MongoClientOptions; @Profile("test") public class TestConfiguration implements AsyncConfigurer { - /** - * DB cleanup utility bean is created. - * - * @return the {@link DatabaseCleanupUtil} bean - */ @Bean - public DatabaseCleanupUtil createDatabaseCleanupUtil() { - return new RepositoryDataGenerator.DatabaseCleanupUtil(); + public TestRepositoryManagement testRepositoryManagement() { + return new JpaTestRepositoryManagement(); + } + + @Bean + public TestdataFactory testdataFactory() { + return new TestdataFactory(); } @Bean diff --git a/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/TestRepositoryManagement.java b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/TestRepositoryManagement.java new file mode 100644 index 000000000..ddad59990 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/TestRepositoryManagement.java @@ -0,0 +1,22 @@ +/** + * 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.util; + +/** + * Repository support for tests. + * + */ +@FunctionalInterface +public interface TestRepositoryManagement { + /** + * Empty the test repository. + */ + void clearTestRepository(); + +} diff --git a/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/TestdataFactory.java b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/TestdataFactory.java new file mode 100644 index 000000000..1ed5679c8 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/TestdataFactory.java @@ -0,0 +1,743 @@ +/** + * 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.util; + +import java.io.InputStream; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Random; +import java.util.UUID; + +import org.apache.commons.io.IOUtils; +import org.eclipse.hawkbit.repository.ArtifactManagement; +import org.eclipse.hawkbit.repository.ControllerManagement; +import org.eclipse.hawkbit.repository.DeploymentManagement; +import org.eclipse.hawkbit.repository.DistributionSetManagement; +import org.eclipse.hawkbit.repository.EntityFactory; +import org.eclipse.hawkbit.repository.SoftwareManagement; +import org.eclipse.hawkbit.repository.TagManagement; +import org.eclipse.hawkbit.repository.TargetManagement; +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.Artifact; +import org.eclipse.hawkbit.repository.model.BaseEntity; +import org.eclipse.hawkbit.repository.model.DistributionSet; +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.NamedEntity; +import org.eclipse.hawkbit.repository.model.NamedVersionedEntity; +import org.eclipse.hawkbit.repository.model.SoftwareModule; +import org.eclipse.hawkbit.repository.model.SoftwareModuleType; +import org.eclipse.hawkbit.repository.model.Target; +import org.eclipse.hawkbit.repository.model.TargetTag; +import org.springframework.beans.factory.annotation.Autowired; + +import com.google.common.base.Strings; +import com.google.common.collect.Lists; + +import net._01001111.text.LoremIpsum; + +/** + * Data generator utility for tests. + */ +public class TestdataFactory { + private static final LoremIpsum LOREM = new LoremIpsum(); + + /** + * default {@link Target#getControllerId()}. + */ + public static final String DEFAULT_CONTROLLER_ID = "targetExist"; + + /** + * Default {@link SoftwareModule#getVendor()}. + */ + public static final String DEFAULT_VENDOR = "Vendor Limited, California"; + + /** + * Default {@link NamedVersionedEntity#getVersion()}. + */ + public static final String DEFAULT_VERSION = "1.0"; + + /** + * Default {@link NamedEntity#getDescription()}. + */ + public static final String DEFAULT_DESCRIPTION = "Desc: " + LOREM.words(10); + + /** + * Key of test default {@link DistributionSetType}. + */ + public static final String DS_TYPE_DEFAULT = "test_default_ds_type"; + + /** + * Key of test "os" {@link SoftwareModuleType} -> mandatory firmware in + * {@link #DS_TYPE_DEFAULT}. + */ + public static final String SM_TYPE_OS = "os"; + + /** + * Key of test "runtime" {@link SoftwareModuleType} -> optional firmware in + * {@link #DS_TYPE_DEFAULT}. + */ + public static final String SM_TYPE_RT = "runtime"; + + /** + * Key of test "application" {@link SoftwareModuleType} -> optional software + * in {@link #DS_TYPE_DEFAULT}. + */ + public static final String SM_TYPE_APP = "application"; + + @Autowired + private ControllerManagement controllerManagament; + + @Autowired + private SoftwareManagement softwareManagement; + + @Autowired + private DistributionSetManagement distributionSetManagement; + + @Autowired + private TargetManagement targetManagement; + + @Autowired + private DeploymentManagement deploymentManagement; + + @Autowired + private TagManagement tagManagement; + + @Autowired + private EntityFactory entityFactory; + + @Autowired + private ArtifactManagement artifactManagement; + + /** + * Creates {@link DistributionSet} in repository including three + * {@link SoftwareModule}s of types {@link #SM_TYPE_OS}, {@link #SM_TYPE_RT} + * , {@link #SM_TYPE_APP} with {@link #DEFAULT_VERSION} and + * {@link DistributionSet#isRequiredMigrationStep()} false. + * + * @param prefix + * for {@link SoftwareModule}s and {@link DistributionSet}s name, + * vendor and description. + * + * @return {@link DistributionSet} entity. + */ + public DistributionSet createDistributionSet(final String prefix) { + return createDistributionSet(prefix, DEFAULT_VERSION, false); + } + + /** + * Creates {@link DistributionSet} in repository including three + * {@link SoftwareModule}s of types {@link #SM_TYPE_OS}, {@link #SM_TYPE_RT} + * , {@link #SM_TYPE_APP} with {@link #DEFAULT_VERSION}. + * + * @param prefix + * for {@link SoftwareModule}s and {@link DistributionSet}s name, + * vendor and description. + * @param isRequiredMigrationStep + * for {@link DistributionSet#isRequiredMigrationStep()} + * + * @return {@link DistributionSet} entity. + */ + public DistributionSet createDistributionSet(final String prefix, final boolean isRequiredMigrationStep) { + return createDistributionSet(prefix, DEFAULT_VERSION, isRequiredMigrationStep); + } + + /** + * Creates {@link DistributionSet} in repository including three + * {@link SoftwareModule}s of types {@link #SM_TYPE_OS}, {@link #SM_TYPE_RT} + * , {@link #SM_TYPE_APP} with {@link #DEFAULT_VERSION} and + * {@link DistributionSet#isRequiredMigrationStep()} false. + * + * @param prefix + * for {@link SoftwareModule}s and {@link DistributionSet}s name, + * vendor and description. + * @param tags + * {@link DistributionSet#getTags()} + * + * @return {@link DistributionSet} entity. + */ + public DistributionSet createDistributionSet(final String prefix, final Collection tags) { + return createDistributionSet(prefix, DEFAULT_VERSION, tags); + } + + /** + * Creates {@link DistributionSet} in repository including three + * {@link SoftwareModule}s of types {@link #SM_TYPE_OS}, {@link #SM_TYPE_RT} + * , {@link #SM_TYPE_APP}. + * + * @param prefix + * for {@link SoftwareModule}s and {@link DistributionSet}s name, + * vendor and description. + * @param version + * {@link DistributionSet#getVersion()} and + * {@link SoftwareModule#getVersion()} extended by a random + * number. + * @param isRequiredMigrationStep + * for {@link DistributionSet#isRequiredMigrationStep()} + * + * @return {@link DistributionSet} entity. + */ + public DistributionSet createDistributionSet(final String prefix, final String version, + final boolean isRequiredMigrationStep) { + + final SoftwareModule appMod = softwareManagement.createSoftwareModule(entityFactory.generateSoftwareModule( + findOrCreateSoftwareModuleType(SM_TYPE_APP, Integer.MAX_VALUE), prefix + SM_TYPE_APP, + version + "." + new Random().nextInt(100), LOREM.words(20), prefix + " vendor Limited, California")); + final SoftwareModule runtimeMod = softwareManagement + .createSoftwareModule(entityFactory.generateSoftwareModule(findOrCreateSoftwareModuleType(SM_TYPE_RT), + prefix + "app runtime", version + "." + new Random().nextInt(100), LOREM.words(20), + prefix + " vendor GmbH, Stuttgart, Germany")); + final SoftwareModule osMod = softwareManagement + .createSoftwareModule(entityFactory.generateSoftwareModule(findOrCreateSoftwareModuleType(SM_TYPE_OS), + prefix + " Firmware", version + "." + new Random().nextInt(100), LOREM.words(20), + prefix + " vendor Limited Inc, California")); + + return distributionSetManagement + .createDistributionSet(generateDistributionSet(prefix != null && prefix.length() > 0 ? prefix : "DS", + version, findOrCreateDefaultTestDsType(), Lists.newArrayList(osMod, runtimeMod, appMod)) + .setRequiredMigrationStep(isRequiredMigrationStep)); + } + + /** + * Creates {@link DistributionSet} in repository including three + * {@link SoftwareModule}s of types {@link #SM_TYPE_OS}, {@link #SM_TYPE_RT} + * , {@link #SM_TYPE_APP}. + * + * @param prefix + * for {@link SoftwareModule}s and {@link DistributionSet}s name, + * vendor and description. + * @param version + * {@link DistributionSet#getVersion()} and + * {@link SoftwareModule#getVersion()} extended by a random + * number.updat + * @param tags + * {@link DistributionSet#getTags()} + * + * @return {@link DistributionSet} entity. + */ + public DistributionSet createDistributionSet(final String prefix, final String version, + final Collection tags) { + + final DistributionSet set = createDistributionSet(prefix, version, false); + + final List sets = new ArrayList<>(); + sets.add(set); + + tags.forEach(tag -> distributionSetManagement.toggleTagAssignment(sets, tag)); + + return distributionSetManagement.findDistributionSetById(set.getId()); + + } + + /** + * Creates {@link DistributionSet}s in repository including three + * {@link SoftwareModule}s of types {@link #SM_TYPE_OS}, {@link #SM_TYPE_RT} + * , {@link #SM_TYPE_APP} with {@link #DEFAULT_VERSION} followed by an + * iterative number and {@link DistributionSet#isRequiredMigrationStep()} + * false. + * + * @param number + * of {@link DistributionSet}s to create + * + * @return {@link List} of {@link DistributionSet} entities + */ + public List createDistributionSets(final int number) { + + return createDistributionSets("", number); + } + + /** + * Creates {@link DistributionSet}s in repository including three + * {@link SoftwareModule}s of types {@link #SM_TYPE_OS}, {@link #SM_TYPE_RT} + * , {@link #SM_TYPE_APP} with {@link #DEFAULT_VERSION} followed by an + * iterative number and {@link DistributionSet#isRequiredMigrationStep()} + * false. + * + * @param prefix + * for {@link SoftwareModule}s and {@link DistributionSet}s name, + * vendor and description. + * @param number + * of {@link DistributionSet}s to create + * + * @return {@link List} of {@link DistributionSet} entities + */ + public List createDistributionSets(final String prefix, final int number) { + + final List sets = new ArrayList<>(); + for (int i = 0; i < number; i++) { + sets.add(createDistributionSet(prefix, DEFAULT_VERSION + "." + i, false)); + } + + return sets; + } + + /** + * Creates {@link DistributionSet}s in repository with + * {@link #DEFAULT_DESCRIPTION} and + * {@link DistributionSet#isRequiredMigrationStep()} false. + * + * @param name + * {@link DistributionSet#getName()} + * @param version + * {@link DistributionSet#getVersion()} + * + * @return {@link DistributionSet} entity + */ + public DistributionSet createDistributionSetWithNoSoftwareModules(final String name, final String version) { + + final DistributionSet dis = entityFactory.generateDistributionSet(); + dis.setName(name); + dis.setVersion(version); + dis.setDescription(DEFAULT_DESCRIPTION); + dis.setType(findOrCreateDefaultTestDsType()); + return distributionSetManagement.createDistributionSet(dis); + } + + /** + * Creates {@link LocalArtifact}s for given {@link SoftwareModule} with a + * small text payload. + * + * @param moduleId + * the {@link Artifact}s belong to. + * + * @return {@link LocalArtifact} entity. + */ + public List createLocalArtifacts(final Long moduleId) { + final List artifacts = new ArrayList<>(); + for (int i = 0; i < 3; i++) { + final InputStream stubInputStream = IOUtils.toInputStream("some test data" + i, Charset.forName("UTF-8")); + artifacts.add(artifactManagement.createLocalArtifact(stubInputStream, moduleId, "filename" + i, false)); + + } + + return artifacts; + } + + /** + * Creates {@link SoftwareModule} with {@link #DEFAULT_VENDOR} and + * {@link #DEFAULT_VERSION} and random generated + * {@link Target#getDescription()} in the repository. + * + * @param typeKey + * of the {@link SoftwareModuleType} + * + * @return persisted {@link SoftwareModule}. + */ + public SoftwareModule createSoftwareModule(final String typeKey) { + return softwareManagement.createSoftwareModule(entityFactory.generateSoftwareModule( + findOrCreateSoftwareModuleType(typeKey), typeKey, DEFAULT_VERSION, LOREM.words(10), DEFAULT_VENDOR)); + } + + /** + * @return persisted {@link Target} with {@link #DEFAULT_CONTROLLER_ID}. + */ + public Target createTarget() { + return targetManagement.createTarget(entityFactory.generateTarget(DEFAULT_CONTROLLER_ID)); + } + + /** + * Creates {@link DistributionSet}s in repository including three + * {@link SoftwareModule}s of types {@link #SM_TYPE_OS}, {@link #SM_TYPE_RT} + * , {@link #SM_TYPE_APP} with {@link #DEFAULT_VERSION} followed by an + * iterative number and {@link DistributionSet#isRequiredMigrationStep()} + * false. + * + * In addition it updates the ccreated {@link DistributionSet}s and + * {@link SoftwareModule}s to ensure that + * {@link BaseEntity#getLastModifiedAt()} and + * {@link BaseEntity#getLastModifiedBy()} is filled. + * + * @return persisted {@link DistributionSet}. + */ + public DistributionSet createUpdatedDistributionSet() { + DistributionSet set = createDistributionSet(""); + set.setVersion(DEFAULT_VERSION); + set = distributionSetManagement.updateDistributionSet(set); + + set.getModules().forEach(module -> { + module.setDescription("Updated " + DEFAULT_DESCRIPTION); + softwareManagement.updateSoftwareModule(module); + }); + + // load also lazy stuff + set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()); + + return set; + } + + /** + * @return {@link DistributionSetType} with key {@link #DS_TYPE_DEFAULT} and + * {@link SoftwareModuleType}s {@link #SM_TYPE_OS}, + * {@link #SM_TYPE_RT} , {@link #SM_TYPE_APP}. + */ + public DistributionSetType findOrCreateDefaultTestDsType() { + final List mand = new ArrayList<>(); + mand.add(findOrCreateSoftwareModuleType(SM_TYPE_OS)); + + final List opt = new ArrayList<>(); + opt.add(findOrCreateSoftwareModuleType(SM_TYPE_APP, Integer.MAX_VALUE)); + opt.add(findOrCreateSoftwareModuleType(SM_TYPE_RT)); + + return findOrCreateDistributionSetType(DS_TYPE_DEFAULT, "OS (FW) mandatory, runtime (FW) and app (SW) optional", + mand, opt); + } + + /** + * Creates {@link DistributionSetType} in repository. + * + * @param dsTypeKey + * {@link DistributionSetType#getKey()} + * @param dsTypeName + * {@link DistributionSetType#getName()} + * + * @return persisted {@link DistributionSetType} + */ + public DistributionSetType findOrCreateDistributionSetType(final String dsTypeKey, final String dsTypeName) { + final DistributionSetType findDistributionSetTypeByname = distributionSetManagement + .findDistributionSetTypeByKey(dsTypeKey); + + if (findDistributionSetTypeByname != null) { + return findDistributionSetTypeByname; + } + + final DistributionSetType type = entityFactory.generateDistributionSetType(dsTypeKey, dsTypeName, + LOREM.words(10)); + + return distributionSetManagement.createDistributionSetType(type); + } + + /** + * Finds {@link DistributionSetType} in repository with given + * {@link DistributionSetType#getKey()} or creates if it does not exist yet. + * + * @param dsTypeKey + * {@link DistributionSetType#getKey()} + * @param dsTypeName + * {@link DistributionSetType#getName()} + * @param mandatory + * {@link DistributionSetType#getMandatoryModuleTypes()} + * @param optional + * {@link DistributionSetType#getOptionalModuleTypes()} + * + * @return persisted {@link DistributionSetType} + */ + public DistributionSetType findOrCreateDistributionSetType(final String dsTypeKey, final String dsTypeName, + final Collection mandatory, final Collection optional) { + final DistributionSetType findDistributionSetTypeByname = distributionSetManagement + .findDistributionSetTypeByKey(dsTypeKey); + + if (findDistributionSetTypeByname != null) { + return findDistributionSetTypeByname; + } + + final DistributionSetType type = entityFactory.generateDistributionSetType(dsTypeKey, dsTypeName, + LOREM.words(10)); + mandatory.forEach(type::addMandatoryModuleType); + optional.forEach(type::addOptionalModuleType); + + return distributionSetManagement.createDistributionSetType(type); + } + + /** + * Finds {@link SoftwareModuleType} in repository with given + * {@link SoftwareModuleType#getKey()} or creates if it does not exist yet + * with {@link SoftwareModuleType#getMaxAssignments()} = 1. + * + * @param key + * {@link SoftwareModuleType#getKey()} + * + * @return persisted {@link SoftwareModuleType} + */ + public SoftwareModuleType findOrCreateSoftwareModuleType(final String key) { + return findOrCreateSoftwareModuleType(key, 1); + } + + /** + * Finds {@link SoftwareModuleType} in repository with given + * {@link SoftwareModuleType#getKey()} or creates if it does not exist yet. + * + * @param key + * {@link SoftwareModuleType#getKey()} + * @param maxAssignments + * {@link SoftwareModuleType#getMaxAssignments()} + * + * @return persisted {@link SoftwareModuleType} + */ + public SoftwareModuleType findOrCreateSoftwareModuleType(final String key, final int maxAssignments) { + final SoftwareModuleType findSoftwareModuleTypeByKey = softwareManagement.findSoftwareModuleTypeByKey(key); + if (findSoftwareModuleTypeByKey != null) { + return findSoftwareModuleTypeByKey; + } + return softwareManagement.createSoftwareModuleType( + entityFactory.generateSoftwareModuleType(key, key, LOREM.words(10), maxAssignments)); + } + + /** + * builder method for creating a {@link DistributionSet}. + * + * @param name + * {@link DistributionSet#getName()} + * @param version + * {@link DistributionSet#getVersion()} + * @param type + * {@link DistributionSet#getType()} + * @param modules + * {@link DistributionSet#getModules()} + * + * @return the created {@link DistributionSet} + */ + public DistributionSet generateDistributionSet(final String name, final String version, + final DistributionSetType type, final Collection modules) { + final DistributionSet distributionSet = entityFactory.generateDistributionSet(name, version, null, type, + modules); + distributionSet.setDescription(LOREM.words(10)); + return distributionSet; + } + + /** + * Creates {@link DistributionSetTag}s in repository. + * + * @param number + * of {@link DistributionSetTag}s + * + * @return the persisted {@link DistributionSetTag}s + */ + public List createDistributionSetTags(final int number) { + final List result = new ArrayList<>(); + + for (int i = 0; i < number; i++) { + result.add(entityFactory.generateDistributionSetTag("tag" + i, "tagdesc" + i, String.valueOf(i))); + } + + return tagManagement.createDistributionSetTags(result); + } + + /** + * builder method for creating a single target object. + * + * @param ctrlID + * the ID of the target + * @param description + * of the target + * @return the created target object + */ + public Target generateTarget(final String ctrlID, final String description) { + return generateTarget(ctrlID, description, null); + } + + /** + * Builds a single {@link Target} from the given parameters. + * + * @param ctrlID + * controllerID + * @param description + * the description of the target + * @param tags + * assigned {@link TargetTag}s + * @return the generated {@link Target} + */ + private Target generateTarget(final String ctrlID, final String description, final TargetTag[] tags) { + final Target target = entityFactory.generateTarget(ctrlID); + target.setName("Prov.Target ".concat(ctrlID)); + target.setDescription(description); + if (tags != null && tags.length > 0) { + for (final TargetTag t : tags) { + target.getTags().add(t); + } + } + return target; + } + + /** + * Creates {@link Target}s in repository and with + * {@link #DEFAULT_CONTROLLER_ID} as prefix for + * {@link Target#getControllerId()}. + * + * @param number + * of {@link Target}s to create + * + * @return {@link List} of {@link Target} entities + */ + public List createTargets(final int number) { + return targetManagement.createTargets(generateTargets(0, number, DEFAULT_CONTROLLER_ID)); + } + + /** + * Builds {@link Target} objects with given prefix for + * {@link Target#getControllerId()} followed by a number suffix. + * + * @param start + * value for the controllerId suffix + * @param numberOfTargets + * of {@link Target}s to generate + * @param controllerIdPrefix + * for {@link Target#getControllerId()} generation. + * @return list of {@link Target} objects + */ + private List generateTargets(final int start, final int numberOfTargets, final String controllerIdPrefix) { + final List targets = new ArrayList<>(); + for (int i = start; i < start + numberOfTargets; i++) { + targets.add(entityFactory.generateTarget(controllerIdPrefix + i)); + } + + return targets; + } + + /** + * Builds {@link Target} objects with given prefix for + * {@link Target#getControllerId()} followed by a number suffix starting + * with 0. + * + * @param numberOfTargets + * of {@link Target}s to generate + * @param controllerIdPrefix + * for {@link Target#getControllerId()} generation. + * @return list of {@link Target} objects + */ + public List generateTargets(final int numberOfTargets, final String controllerIdPrefix) { + return generateTargets(0, numberOfTargets, controllerIdPrefix); + } + + /** + * builds a set of {@link Target} fixtures from the given parameters. + * + * @param numberOfTargets + * number of targets to create + * @param controllerIdPrefix + * prefix used for the controller ID + * @param descriptionPrefix + * prefix used for the description + * @return set of {@link Target} + */ + public List generateTargets(final int numberOfTargets, final String controllerIdPrefix, + final String descriptionPrefix) { + return generateTargets(numberOfTargets, controllerIdPrefix, descriptionPrefix, null); + } + + /** + * method creates set of targets by by generating the controller ID and the + * description like: prefix + no of target. + * + * @param noOfTgts + * number of targets which should be created + * @param controllerIdPrefix + * prefix of the controllerID which is concatenated with the + * number of the target. Randomly generated if null. + * @param descriptionPrefix + * prefix of the target description which is concatenated with + * the number of the target + * @param tags + * tags which should be added to the created {@link Target}s + * @return set of created targets + */ + private List generateTargets(final int noOfTgts, final String controllerIdPrefix, + final String descriptionPrefix, final TargetTag[] tags) { + final List list = new ArrayList<>(); + for (int i = 0; i < noOfTgts; i++) { + String ctrlID = controllerIdPrefix; + if (Strings.isNullOrEmpty(ctrlID)) { + ctrlID = UUID.randomUUID().toString(); + } + ctrlID = String.format("%s-%05d", ctrlID, i); + + final String description = descriptionPrefix + DEFAULT_DESCRIPTION; + + final Target target = generateTarget(ctrlID, description, tags); + list.add(target); + + } + return list; + } + + /** + * Generates {@link TargetTag}s. + * + * @param number + * of {@link TargetTag}s to generate. + * + * @return generated {@link TargetTag}s. + */ + public List generateTargetTags(final int number) { + final List result = new ArrayList<>(); + + for (int i = 0; i < number; i++) { + result.add(entityFactory.generateTargetTag("tag" + i, "tagdesc" + i, String.valueOf(i))); + } + + return result; + } + + /** + * Create a set of {@link TargetTag}s. + * + * @param noOfTags + * number of {@link TargetTag}. to be created + * @param tagPrefix + * prefix for the {@link TargetTag#getName()} + * @return the created set of {@link TargetTag}s + */ + public List generateTargetTags(final int noOfTags, final String tagPrefix) { + final List list = new ArrayList<>(); + for (int i = 0; i < noOfTags; i++) { + String tagName = "myTag"; + if (!Strings.isNullOrEmpty(tagPrefix)) { + tagName = tagPrefix; + } + tagName = String.format("%s-%05d", tagName, i); + + final TargetTag targetTag = entityFactory.generateTargetTag(tagName); + list.add(targetTag); + } + return list; + } + + private Action sendUpdateActionStatusToTarget(final Status status, final Action updActA, final String... msgs) { + updActA.setStatus(status); + + final ActionStatus statusMessages = entityFactory.generateActionStatus(); + statusMessages.setAction(updActA); + statusMessages.setOccurredAt(System.currentTimeMillis()); + statusMessages.setStatus(status); + for (final String msg : msgs) { + statusMessages.addMessage(msg); + } + + return controllerManagament.addUpdateActionStatus(statusMessages); + } + + /** + * Append {@link ActionStatus} to all {@link Action}s of given + * {@link Target}s. + * + * @param targets + * to add {@link ActionStatus} + * @param status + * to add + * @param msgs + * to add + * + * @return updated {@link Action}. + */ + public List sendUpdateActionStatusToTargets(final Collection targets, final Status status, + final String... msgs) { + final List result = new ArrayList<>(); + for (final Target target : targets) { + final List findByTarget = deploymentManagement.findActionsByTarget(target); + for (final Action action : findByTarget) { + result.add(sendUpdateActionStatusToTarget(status, action, msgs)); + } + } + return result; + } +} diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/Testdatabase.java b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/Testdatabase.java similarity index 91% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/Testdatabase.java rename to hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/Testdatabase.java index a11984481..b24d34533 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/Testdatabase.java +++ b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/Testdatabase.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit; +package org.eclipse.hawkbit.repository.util; /** * diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/WithSpringAuthorityRule.java b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/WithSpringAuthorityRule.java similarity index 98% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/WithSpringAuthorityRule.java rename to hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/WithSpringAuthorityRule.java index 40f6a64c2..b456cc32b 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/WithSpringAuthorityRule.java +++ b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/WithSpringAuthorityRule.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit; +package org.eclipse.hawkbit.repository.util; import java.lang.annotation.Annotation; import java.lang.reflect.Field; @@ -17,7 +17,7 @@ import java.util.concurrent.Callable; import org.eclipse.hawkbit.im.authentication.SpPermission; import org.eclipse.hawkbit.im.authentication.TenantAwareAuthenticationDetails; -import org.eclipse.hawkbit.repository.model.helper.SystemManagementHolder; +import org.eclipse.hawkbit.repository.jpa.model.helper.SystemManagementHolder; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/WithUser.java b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/WithUser.java similarity index 97% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/WithUser.java rename to hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/WithUser.java index 3b0412ff1..04af9196b 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/WithUser.java +++ b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/util/WithUser.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit; +package org.eclipse.hawkbit.repository.util; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; diff --git a/hawkbit-repository/pom.xml b/hawkbit-repository/pom.xml index 28d20af3e..981f3225a 100644 --- a/hawkbit-repository/pom.xml +++ b/hawkbit-repository/pom.xml @@ -18,239 +18,14 @@ hawkbit-repository hawkBit :: Repository + pom + + + hawkbit-repository-jpa + hawkbit-repository-api + hawkbit-repository-test + hawkbit-repository-core + - - - - com.ethlo.eclipselink.tools - http://ethlo.com/maven - - - - - - com.ethlo.eclipselink.tools - http://ethlo.com/maven - - - - - - - - com.fasterxml.jackson.core - jackson-core - - - com.fasterxml.jackson.core - jackson-databind - - - - - org.eclipse.hawkbit - hawkbit-artifact-repository-mongo - ${project.version} - - - org.eclipse.hawkbit - hawkbit-core - ${project.version} - - - org.eclipse.hawkbit - hawkbit-security-core - ${project.version} - - - org.hibernate - hibernate-validator - - - javax.validation - validation-api - - - com.google.guava - guava - - - net._01001111 - jlorem - - - org.springframework.boot - spring-boot - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.eclipse.persistence - org.eclipse.persistence.jpa - - - org.springframework.security - spring-security-core - - - org.springframework.hateoas - spring-hateoas - - - org.flywaydb - flyway-core - - - org.springframework.boot - spring-boot-configuration-processor - true - - - - - com.h2database - h2 - test - - - org.mariadb.jdbc - mariadb-java-client - test - - - javax.el - javax.el-api - test - - - org.springframework - spring-context-support - test - - - ru.yandex.qatools.allure - allure-junit-adaptor - test - - - org.springframework.data - spring-data-rest-webmvc - test - - - org.springframework.security - spring-security-aspects - test - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework - spring-test - test - - - org.easytesting - fest-assert-core - test - - - org.easytesting - fest-assert - test - - - de.flapdoodle.embed - de.flapdoodle.embed.mongo - test - - - org.springframework.security - spring-security-config - test - - - org.springframework.security - spring-security-web - test - - - cz.jirutka.rsql - rsql-parser - - - - - - - - org.bsc.maven - maven-processor-plugin - - - process - - process - - generate-sources - - - org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor - - - - - - - org.hibernate - hibernate-jpamodelgen - ${hibernate.version} - - - - - - com.ethlo.persistence.tools - eclipselink-maven-plugin - 2.6.2 - - - process-classes - - weave - - - - - - org.eclipse.persistence - org.eclipse.persistence.jpa - ${eclipselink.version} - - - org.javassist - javassist - 3.20.0-GA - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - test-jar - - - - - - diff --git a/hawkbit-repository/src/fbExcludeFilter.xml b/hawkbit-repository/src/fbExcludeFilter.xml deleted file mode 100644 index bd85e5e73..000000000 --- a/hawkbit-repository/src/fbExcludeFilter.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ArtifactManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ArtifactManagement.java deleted file mode 100644 index e4b4cd5b8..000000000 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ArtifactManagement.java +++ /dev/null @@ -1,493 +0,0 @@ -/** - * 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.ArtifactRepository; -import org.eclipse.hawkbit.artifact.repository.ArtifactStoreException; -import org.eclipse.hawkbit.artifact.repository.HashNotMatchException; -import org.eclipse.hawkbit.artifact.repository.model.DbArtifact; -import org.eclipse.hawkbit.artifact.repository.model.DbArtifactHash; -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.eclipse.hawkbit.repository.specifications.SoftwareModuleSpecification; -import org.hibernate.validator.constraints.NotEmpty; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.domain.Specification; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.hateoas.Identifiable; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.transaction.annotation.Isolation; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.validation.annotation.Validated; - -/** - * Service for {@link Artifact} management operations. - * - */ -@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) -@Validated -public class ArtifactManagement { - - private static final Logger LOG = LoggerFactory.getLogger(ArtifactManagement.class); - - @Autowired - private LocalArtifactRepository localArtifactRepository; - - @Autowired - private ExternalArtifactRepository externalArtifactRepository; - - @Autowired - private SoftwareModuleRepository softwareModuleRepository; - - @Autowired - private ExternalArtifactProviderRepository externalArtifactProviderRepository; - - @Autowired - private ArtifactRepository artifactRepository; - - /** - * 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 true 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 - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - public LocalArtifact createLocalArtifact(@NotNull final InputStream stream, @NotNull final Long moduleId, - @NotEmpty final String filename, final String providedMd5Sum, final String providedSha1Sum, - final boolean overrideExisting, final String contentType) { - DbArtifact result = null; - - final SoftwareModule softwareModule = getModuleAndThrowExceptionIfThatFails(moduleId); - - final LocalArtifact existing = checkForExistingArtifact(filename, overrideExisting, softwareModule); - - try { - result = artifactRepository.store(stream, filename, contentType, - new DbArtifactHash(providedSha1Sum, providedMd5Sum)); - } catch (final ArtifactStoreException e) { - throw new ArtifactUploadFailedException(e); - } catch (final HashNotMatchException e) { - if (e.getHashFunction().equals(HashNotMatchException.SHA1)) { - throw new InvalidSHA1HashException(e.getMessage(), e); - } else { - throw new InvalidMD5HashException(e.getMessage(), e); - } - } - if (result == null) { - return null; - } - - return storeArtifactMetadata(softwareModule, filename, result, existing); - } - - private static LocalArtifact checkForExistingArtifact(final String filename, final boolean overrideExisting, - final SoftwareModule softwareModule) { - if (softwareModule.getLocalArtifactByFilename(filename).isPresent()) { - if (overrideExisting) { - LOG.debug("overriding existing artifact with new filename {}", filename); - return softwareModule.getLocalArtifactByFilename(filename).get(); - } else { - throw new EntityAlreadyExistsException("File with that name already exists in the Software Module"); - } - } - return null; - } - - private SoftwareModule getModuleAndThrowExceptionIfThatFails(final Long moduleId) { - final SoftwareModule softwareModule = findSoftwareModuleWithDetails(moduleId); - - if (softwareModule == null) { - LOG.debug("no software module with ID {} exists", moduleId); - throw new EntityNotFoundException("Software Module: " + moduleId); - } - return softwareModule; - } - - /** - * 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) - protected SoftwareModule findSoftwareModuleWithDetails(@NotNull final Long id) { - final SoftwareModule result = findSoftwareModuleById(id); - if (result != null) { - result.getArtifacts().size(); - } - - return result; - } - - /** - * 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) - public LocalArtifact findFirstLocalArtifactsBySHA1(final String sha1) { - return localArtifactRepository.findFirstByGridFsFileName(sha1); - } - - /** - * Finds {@link SoftwareModule} by given id. - * - * @param id - * to search for - * @return the found {@link SoftwareModule}s or null if not - * found. - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR - + SpringEvalExpressions.IS_CONTROLLER) - protected SoftwareModule findSoftwareModuleById(@NotNull final Long id) { - - final Specification spec = SoftwareModuleSpecification.byId(id); - - return softwareModuleRepository.findOne(spec); - } - - private LocalArtifact storeArtifactMetadata(final SoftwareModule softwareModule, final String providedFilename, - final DbArtifact result, final LocalArtifact existing) { - LocalArtifact artifact = existing; - if (existing == null) { - artifact = new LocalArtifact(result.getHashes().getSha1(), providedFilename, softwareModule); - } - artifact.setMd5Hash(result.getHashes().getMd5()); - artifact.setSha1Hash(result.getHashes().getSha1()); - artifact.setSize(result.getSize()); - - LOG.debug("storing new artifact into repository {}", artifact); - return localArtifactRepository.save(artifact); - } - - /** - * 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} - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - public ExternalArtifactProvider createExternalArtifactProvider(@NotEmpty final String name, - final String description, @NotNull final String basePath, final String defaultUrlSuffix) { - return externalArtifactProviderRepository - .save(new ExternalArtifactProvider(name, description, basePath, defaultUrlSuffix)); - } - - /** - * 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 - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - public ExternalArtifact createExternalArtifact(@NotNull final ExternalArtifactProvider externalRepository, - final String urlSuffix, @NotNull final Long moduleId) { - - final SoftwareModule module = getModuleAndThrowExceptionIfThatFails(moduleId); - return externalArtifactRepository.save(new ExternalArtifact(externalRepository, urlSuffix, module)); - } - - /** - * 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) - * - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) - public void deleteLocalArtifact(@NotNull final Long id) { - final LocalArtifact existing = localArtifactRepository.findOne(id); - - if (null == existing) { - return; - } - - deleteGridFsArtifact(existing); - - existing.getSoftwareModule().removeArtifact(existing); - softwareModuleRepository.save(existing.getSoftwareModule()); - localArtifactRepository.delete(id); - } - - /** - * Delete a grid fs file. - * - * @param existing - * the related local artifact - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) - public void deleteGridFsArtifact(@NotNull final LocalArtifact existing) { - if (existing == null) { - return; - } - - boolean artifactIsOnlyUsedByOneSoftwareModule = true; - for (final LocalArtifact lArtifact : localArtifactRepository - .findByGridFsFileName(existing.getGridFsFileName())) { - if (!lArtifact.getSoftwareModule().isDeleted() - && Long.compare(lArtifact.getSoftwareModule().getId(), existing.getSoftwareModule().getId()) != 0) { - artifactIsOnlyUsedByOneSoftwareModule = false; - break; - } - } - - if (artifactIsOnlyUsedByOneSoftwareModule) { - try { - LOG.debug("deleting artifact from repository {}", existing.getGridFsFileName()); - artifactRepository.deleteBySha1(existing.getGridFsFileName()); - } catch (final ArtifactStoreException e) { - throw new ArtifactDeleteFailedException(e); - } - } - } - - /** - * 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) - * - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) - public void deleteExternalArtifact(@NotNull final Long id) { - final ExternalArtifact existing = externalArtifactRepository.findOne(id); - - if (null == existing) { - return; - } - - existing.getSoftwareModule().removeArtifact(existing); - softwareModuleRepository.save(existing.getSoftwareModule()); - externalArtifactRepository.delete(id); - } - - /** - * Searches for {@link Artifact} with given file name. - * - * @param filename - * to search for - * @return found List of {@link LocalArtifact}s. - */ - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR - + SpringEvalExpressions.IS_CONTROLLER) - public List findLocalArtifactByFilename(@NotNull final String filename) { - return localArtifactRepository.findByFilename(filename); - } - - /** - * Searches for {@link Artifact} with given {@link Identifiable}. - * - * @param id - * to search for - * @return found {@link Artifact} or null is it could not be - * found. - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public Artifact findArtifact(@NotNull final Long id) { - return localArtifactRepository.findOne(id); - } - - /** - * Loads {@link org.eclipse.hawkbit.artifact.server.json.model.Artifact} - * from store for given {@link LocalArtifact}. - * - * @param artifact - * to search for - * @return loaded - * {@link org.eclipse.hawkbit.artifact.server.json.model.Artifact} - * - * @throws GridFSDBFileNotFoundException - * if file could not be found in store - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DOWNLOAD_ARTIFACT + SpringEvalExpressions.HAS_AUTH_OR - + SpringEvalExpressions.HAS_CONTROLLER_DOWNLOAD) - public DbArtifact loadLocalArtifactBinary(@NotNull final LocalArtifact artifact) { - final DbArtifact result = artifactRepository.getArtifactBySha1(artifact.getGridFsFileName()); - if (result == null) { - throw new GridFSDBFileNotFoundException(artifact.getGridFsFileName()); - } - - return result; - } - - /** - * 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 true 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 - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public LocalArtifact createLocalArtifact(final InputStream inputStream, final Long moduleId, final String filename, - final boolean overrideExisting, final String contentType) { - return createLocalArtifact(inputStream, moduleId, filename, null, null, overrideExisting, contentType); - } - - /** - * 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 true if the artifact binary can be overdiden - * if it already exists - * - * @return uploaded {@link LocalArtifact} - * - * @throw ArtifactUploadFailedException if upload failes - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public LocalArtifact createLocalArtifact(final InputStream inputStream, final Long moduleId, final String filename, - final boolean overrideExisting) { - return createLocalArtifact(inputStream, moduleId, filename, null, null, overrideExisting, null); - } - - /** - * Get local artifact for a base software module. - * - * @param pageReq - * Pageable - * @param swId - * software module id - * @return Page - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public Page findLocalArtifactBySoftwareModule(@NotNull final Pageable pageReq, - @NotNull final Long swId) { - return localArtifactRepository.findBySoftwareModuleId(pageReq, swId); - } - - /** - * Find by artifact by software module id and filename. - * - * @param filename - * file name - * @param softwareModuleId - * software module id. - * @return LocalArtifact if artifact present - */ - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR - + SpringEvalExpressions.IS_CONTROLLER) - public List findByFilenameAndSoftwareModule(@NotNull final String filename, - @NotNull final Long softwareModuleId) { - return localArtifactRepository.findByFilenameAndSoftwareModuleId(filename, softwareModuleId); - } -} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java deleted file mode 100644 index 11879edfd..000000000 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java +++ /dev/null @@ -1,612 +0,0 @@ -/** - * 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.persistence.EntityManager; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; -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.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.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.repository.model.Target_; -import org.eclipse.hawkbit.repository.model.TenantConfiguration; -import org.eclipse.hawkbit.repository.specifications.ActionSpecifications; -import org.eclipse.hawkbit.security.HawkbitSecurityProperties; -import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; -import org.hibernate.validator.constraints.NotEmpty; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.jpa.domain.Specification; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Isolation; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.validation.annotation.Validated; - -/** - * Service layer for all operations of the controller API (with access - * permissions only for the controller). - * - * - * - */ -@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) -@Validated -@Service -public class ControllerManagement { - private static final Logger LOG = LoggerFactory.getLogger(ControllerManagement.class); - private static final Logger LOG_DOS = LoggerFactory.getLogger("server-security.dos"); - - public static final String SERVER_MESSAGE_PREFIX = "Update Server: "; - - @Autowired - private EntityManager entityManager; - - @Autowired - private ActionRepository actionRepository; - - @Autowired - private TargetRepository targetRepository; - - @Autowired - private TargetManagement targetManagement; - - @Autowired - private DeploymentManagement deploymentManagement; - - @Autowired - private TargetInfoRepository targetInfoRepository; - - @Autowired - private SoftwareModuleRepository softwareModuleRepository; - - @Autowired - private ActionStatusRepository actionStatusRepository; - - @Autowired - private HawkbitSecurityProperties securityProperties; - - @Autowired - private TenantConfigurationRepository tenantConfigurationRepository; - - @Autowired - private TenantConfigurationManagement tenantConfigurationManagement; - - /** - * 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) - public String findPollingTime() { - final TenantConfigurationKey configurationKey = TenantConfigurationKey.POLLING_TIME_INTERVAL; - final Class propertyType = String.class; - tenantConfigurationManagement.validateTenantConfigurationDataType(configurationKey, propertyType); - final TenantConfiguration tenantConfiguration = tenantConfigurationRepository - .findByKey(configurationKey.getKeyName()); - return tenantConfigurationManagement - .buildTenantConfigurationValueByKey(configurationKey, propertyType, tenantConfiguration).getValue(); - } - - /** - * Refreshes the time of the last time the controller has been connected to - * the server. - * - * @param targetid - * 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 - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) - public Target updateLastTargetQuery(@NotEmpty final String targetid, final URI address) { - final Target target = targetRepository.findByControllerId(targetid); - if (target == null) { - throw new EntityNotFoundException(targetid); - } - - return updateLastTargetQuery(target.getTargetInfo(), address).getTarget(); - } - - /** - * Retrieves last {@link UpdateAction} for a download of an artifact of - * given module and target. - * - * @param targetId - * to look for - * @param module - * that should be assigned to the target - * @return last {@link UpdateAction} for given combination - * - * @throws EntityNotFoundException - * if action for given combination could not be found - */ - @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) - public Action getActionForDownloadByTargetAndSoftwareModule(@NotNull final String targetId, - @NotNull final SoftwareModule module) { - final List action = actionRepository.findActionByTargetAndSoftwareModule(targetId, module); - - if (action.isEmpty() || action.get(0).isCancelingOrCanceled()) { - throw new EntityNotFoundException( - "No assigment found for module " + module.getId() + " to target " + targetId); - } - - return action.get(0); - } - - /** - * 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 targetId - * 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} - */ - public boolean hasTargetArtifactAssigned(@NotNull final String targetId, - @NotNull final LocalArtifact localArtifact) { - final Target target = targetRepository.findByControllerId(targetId); - if (target == null) { - return false; - } - return actionRepository.count(ActionSpecifications.hasTargetAssignedArtifact(target, localArtifact)) > 0; - } - - /** - * 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 - * - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) - public TargetInfo updateLastTargetQuery(@NotNull final TargetInfo target, final URI address) { - return updateTargetStatus(target, null, System.currentTimeMillis(), address); - } - - /** - * 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) - public List findActionByTargetAndActive(final Target target) { - return actionRepository.findByTargetAndActiveOrderByIdAsc(target, true); - } - - /** - * 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) - public List findSoftwareModulesByDistributionSet(final DistributionSet distributionSet) { - return softwareModuleRepository.findByAssignedTo(distributionSet); - } - - /** - * 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) - public Action findActionWithDetails(@NotNull final Long actionId) { - return actionRepository.findById(actionId); - } - - /** - * register new target in the repository (plug-and-play). - * - * @param targetid - * reference - * @param address - * the client IP address of the target, might be {@code null} - * @return target reference - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) - public Target findOrRegisterTargetIfItDoesNotexist(@NotEmpty final String targetid, final URI address) { - final Specification spec = (targetRoot, query, cb) -> cb.equal(targetRoot.get(Target_.controllerId), - targetid); - - Target target = targetRepository.findOne(spec); - - if (target == null) { - target = new Target(targetid); - target.setDescription("Plug and Play target: " + targetid); - target.setName(targetid); - return targetManagement.createTarget(target, TargetUpdateStatus.REGISTERED, System.currentTimeMillis(), - address); - } - - return updateLastTargetQuery(target.getTargetInfo(), address).getTarget(); - } - - /** - * 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 - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) - public TargetInfo updateTargetStatus(@NotNull final TargetInfo targetInfo, final TargetUpdateStatus status, - final Long lastTargetQuery, final URI address) { - final TargetInfo mtargetInfo = entityManager.merge(targetInfo); - if (status != null) { - mtargetInfo.setUpdateStatus(status); - } - if (lastTargetQuery != null) { - mtargetInfo.setLastTargetQuery(lastTargetQuery); - } - if (address != null) { - mtargetInfo.setAddress(address.toString()); - } - return targetInfoRepository.save(mtargetInfo); - } - - /** - * Adds an {@link ActionStatus} for a {@link UpdateAction} and cancels the - * {@link UpdateAction} if necessary. - * - * @param actionStatus - * to be updated - * @param action - * the status is for - * @return the persisted {@link Action} - * - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) - public Action addCancelActionStatus(@NotNull final ActionStatus actionStatus, final Action action) { - - checkForToManyStatusEntries(action); - action.setStatus(actionStatus.getStatus()); - - switch (actionStatus.getStatus()) { - case WARNING: - case ERROR: - case RUNNING: - break; - case CANCELED: - case FINISHED: - // in case of successful cancellation we also report the success at - // the canceled action itself. - actionStatus.addMessage( - ControllerManagement.SERVER_MESSAGE_PREFIX + "Cancellation completion is finished sucessfully."); - deploymentManagement.successCancellation(action); - break; - case RETRIEVED: - actionStatus.addMessage(ControllerManagement.SERVER_MESSAGE_PREFIX + "Cancellation request retrieved."); - break; - default: - } - actionRepository.save(action); - actionStatusRepository.save(actionStatus); - - return action; - } - - /** - * Updates an {@link ActionStatus} for a {@link UpdateAction}. - * - * @param actionStatus - * to be updated - * @param action - * the update is for - * @return the persisted {@link Action} - * - * @throws EntityAlreadyExistsException - * if a given entity already exists - * @throws ToManyStatusEntriesException - * if more than the allowed number of status entries are - * inserted - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) - public Action addUpdateActionStatus(@NotNull final ActionStatus actionStatus, final Action action) { - - if (!action.isActive()) { - LOG.debug("Update of actionStatus {} for action {} not possible since action not active anymore.", - actionStatus.getId(), action.getId()); - return action; - } - return handleAddUpdateActionStatus(actionStatus, action); - } - - /** - * Sets {@link TargetUpdateStatus} based on given {@link ActionStatus}. - * - * @param actionStatus - * @param action - * @return - */ - public Action handleAddUpdateActionStatus(final ActionStatus actionStatus, final Action action) { - LOG.debug("addUpdateActionStatus for action {}", action.getId()); - - final Action mergedAction = entityManager.merge(action); - Target mergedTarget = mergedAction.getTarget(); - // check for a potential DOS attack - checkForToManyStatusEntries(action); - - switch (actionStatus.getStatus()) { - case ERROR: - mergedTarget = deploymentManagement.updateTargetInfo(mergedTarget, TargetUpdateStatus.ERROR, false); - handleErrorOnAction(mergedAction, mergedTarget); - break; - case FINISHED: - handleFinishedAndStoreInTargetStatus(mergedTarget, mergedAction); - break; - case CANCELED: - case WARNING: - case RUNNING: - deploymentManagement.updateTargetInfo(mergedTarget, TargetUpdateStatus.PENDING, false); - break; - default: - break; - } - - actionStatusRepository.save(actionStatus); - - LOG.debug("addUpdateActionStatus {} for target {} is finished.", action.getId(), mergedTarget.getId()); - - return actionRepository.save(mergedAction); - } - - private void handleErrorOnAction(final Action mergedAction, final Target mergedTarget) { - mergedAction.setActive(false); - mergedAction.setStatus(Status.ERROR); - mergedTarget.setAssignedDistributionSet(null); - targetManagement.updateTarget(mergedTarget); - } - - private void checkForToManyStatusEntries(final Action action) { - if (securityProperties.getDos().getMaxStatusEntriesPerAction() > 0) { - - final Long statusCount = actionStatusRepository.countByAction(action); - - if (statusCount >= securityProperties.getDos().getMaxStatusEntriesPerAction()) { - LOG_DOS.error( - "Potential denial of service (DOS) attack identfied. More status entries in the system than permitted ({})!", - securityProperties.getDos().getMaxStatusEntriesPerAction()); - throw new ToManyStatusEntriesException( - String.valueOf(securityProperties.getDos().getMaxStatusEntriesPerAction())); - } - } - } - - private void handleFinishedAndStoreInTargetStatus(final Target target, final Action action) { - action.setActive(false); - action.setStatus(Status.FINISHED); - final TargetInfo targetInfo = target.getTargetInfo(); - final DistributionSet ds = entityManager.merge(action.getDistributionSet()); - targetInfo.setInstalledDistributionSet(ds); - if (target.getAssignedDistributionSet() != null && targetInfo.getInstalledDistributionSet() != null && target - .getAssignedDistributionSet().getId().equals(targetInfo.getInstalledDistributionSet().getId())) { - targetInfo.setUpdateStatus(TargetUpdateStatus.IN_SYNC); - targetInfo.setInstallationDate(System.currentTimeMillis()); - } else { - targetInfo.setUpdateStatus(TargetUpdateStatus.PENDING); - targetInfo.setInstallationDate(System.currentTimeMillis()); - } - targetInfoRepository.save(targetInfo); - entityManager.detach(ds); - } - - /** - * Updates attributes of the controller. - * - * @param targetid - * to update - * @param data - * to insert - * - * @return updated {@link Target} - * - * @throws EntityNotFoundException - * if target that has to be updated could not be found - * @throws ToManyAttributeEntriesException - * if maximum - */ - @Modifying - @NotNull - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) - public Target updateControllerAttributes(@NotEmpty final String targetid, @NotNull final Map data) { - final Target target = targetRepository.findByControllerId(targetid); - - if (target == null) { - throw new EntityNotFoundException(targetid); - } - - target.getTargetInfo().getControllerAttributes().putAll(data); - - if (target.getTargetInfo().getControllerAttributes().size() > securityProperties.getDos() - .getMaxAttributeEntriesPerTarget()) { - LOG_DOS.info("Target tries to insert more than the allowed number of entries ({}). DOS attack anticipated!", - securityProperties.getDos().getMaxAttributeEntriesPerTarget()); - throw new ToManyAttributeEntriesException( - String.valueOf(securityProperties.getDos().getMaxAttributeEntriesPerTarget())); - } - - target.getTargetInfo().setLastTargetQuery(System.currentTimeMillis()); - target.getTargetInfo().setRequestControllerAttributes(false); - return targetRepository.save(target); - } - - /** - * Registers retrieved status for given {@link Target} and {@link Action} if - * it does not exist yet. - * - * @param action - * to the handle status for - * @param target - * 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} - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) - public Action registerRetrieved(final Action action, final String message) { - return handleRegisterRetrieved(action, message); - } - - /** - * 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 updated action in case the status has been changed to - * {@link Status#RETRIEVED} - */ - public Action handleRegisterRetrieved(final Action action, final String message) { - // do a manual query with CriteriaBuilder to avoid unnecessary field - // queries and an extra - // count query made by spring-data when using pageable requests, we - // don't need an extra count - // query, we just want to check if the last action status is a retrieved - // or not. - final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); - final CriteriaQuery queryActionStatus = cb.createQuery(Object[].class); - final Root actionStatusRoot = queryActionStatus.from(ActionStatus.class); - final CriteriaQuery query = queryActionStatus - .multiselect(actionStatusRoot.get(ActionStatus_.id), actionStatusRoot.get(ActionStatus_.status)) - .where(cb.equal(actionStatusRoot.get(ActionStatus_.action), action)) - .orderBy(cb.desc(actionStatusRoot.get(ActionStatus_.id))); - final List resultList = entityManager.createQuery(query).setFirstResult(0).setMaxResults(1) - .getResultList(); - - // if the latest status is not in retrieve state then we add a retrieved - // state again, we want - // to document a deployment retrieved status and a cancel retrieved - // status, but multiple - // retrieves after the other we don't want to store to protect to - // overflood action status in - // case controller retrieves a action multiple times. - if (resultList.isEmpty() || resultList.get(0)[1] != Status.RETRIEVED) { - // document that the status has been retrieved - actionStatusRepository - .save(new ActionStatus(action, Status.RETRIEVED, System.currentTimeMillis(), message)); - - // don't change the action status itself in case the action is in - // canceling state otherwise - // we modify the action status and the controller won't get the - // cancel job anymore. - if (!action.isCancelingOrCanceled()) { - final Action actionMerge = entityManager.merge(action); - actionMerge.setStatus(Status.RETRIEVED); - return actionRepository.save(actionMerge); - } - } - return action; - } - - /** - * @param statusMessage - */ - @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - public void addActionStatusMessage(final ActionStatus statusMessage) { - actionStatusRepository.save(statusMessage); - } - - /** - * 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 - */ - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - public String getSecurityTokenByControllerId(final String controllerId) { - final Target target = targetRepository.findByControllerId(controllerId); - return target != null ? target.getSecurityToken() : null; - } -} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DeploymentManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DeploymentManagement.java deleted file mode 100644 index de35f48f6..000000000 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DeploymentManagement.java +++ /dev/null @@ -1,1020 +0,0 @@ -/** - * 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.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Function; -import java.util.stream.Collectors; - -import javax.persistence.EntityManager; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Join; -import javax.persistence.criteria.JoinType; -import javax.persistence.criteria.ListJoin; -import javax.persistence.criteria.Root; -import javax.validation.constraints.NotNull; - -import org.eclipse.hawkbit.Constants; -import org.eclipse.hawkbit.eventbus.event.CancelTargetAssignmentEvent; -import org.eclipse.hawkbit.eventbus.event.TargetAssignDistributionSetEvent; -import org.eclipse.hawkbit.eventbus.event.TargetInfoUpdateEvent; -import org.eclipse.hawkbit.executor.AfterTransactionCommitExecutor; -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.ForceQuitActionNotAllowedException; -import org.eclipse.hawkbit.repository.exception.IncompleteDistributionSetException; -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.Action_; -import org.eclipse.hawkbit.repository.model.DistributionSet; -import org.eclipse.hawkbit.repository.model.DistributionSetType; -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.Rollout_; -import org.eclipse.hawkbit.repository.model.SoftwareModule; -import org.eclipse.hawkbit.repository.model.SoftwareModuleType; -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.repository.specifications.TargetSpecifications; -import org.eclipse.hawkbit.security.SystemSecurityContext; -import org.hibernate.validator.constraints.NotEmpty; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.annotation.CacheEvict; -import org.springframework.data.domain.AuditorAware; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Slice; -import org.springframework.data.jpa.domain.Specification; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.transaction.annotation.Isolation; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.validation.annotation.Validated; - -import com.google.common.collect.Lists; -import com.google.common.eventbus.EventBus; - -/** - * Business service facade for managing all deployment related data and actions. - * - * - */ -@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) -@Validated -public class DeploymentManagement { - private static final Logger LOG = LoggerFactory.getLogger(DeploymentManagement.class); - - @Autowired - private EntityManager entityManager; - - @Autowired - private ActionRepository actionRepository; - - @Autowired - private DistributionSetRepository distributoinSetRepository; - - @Autowired - private SoftwareModuleRepository softwareModuleRepository; - - @Autowired - private TargetRepository targetRepository; - - @Autowired - private ActionStatusRepository actionStatusRepository; - - @Autowired - private TargetManagement targetManagement; - - @Autowired - private TargetInfoRepository targetInfoRepository; - - @Autowired - private AuditorAware auditorProvider; - - @Autowired - private EventBus eventBus; - - @Autowired - private AfterTransactionCommitExecutor afterCommit; - - @Autowired - private SystemSecurityContext systemSecurityContext; - - /** - * 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}. * - */ - @Transactional(isolation = Isolation.READ_COMMITTED) - @Modifying - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET) - @CacheEvict(value = { "distributionUsageAssigned" }, allEntries = true) - public DistributionSetAssignmentResult assignDistributionSet(@NotNull final DistributionSet pset, - @NotEmpty final List targets) { - - return assignDistributionSetByTargetId(pset, - targets.stream().map(target -> target.getControllerId()).collect(Collectors.toList()), - ActionType.FORCED, Action.NO_FORCE_TIME); - - } - - /** - * 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}. - */ - @Modifying - @Transactional(isolation = Isolation.READ_COMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET) - @CacheEvict(value = { "distributionUsageAssigned" }, allEntries = true) - public DistributionSetAssignmentResult assignDistributionSet(@NotNull final Long dsID, - @NotEmpty final String... targetIDs) { - return assignDistributionSet(dsID, ActionType.FORCED, Action.NO_FORCE_TIME, 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 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}. - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET) - @CacheEvict(value = { "distributionUsageAssigned" }, allEntries = true) - // Exception squid:S2095: see - // https://jira.sonarsource.com/browse/SONARJAVA-1478 - @SuppressWarnings({ "squid:S2095" }) - public DistributionSetAssignmentResult assignDistributionSet(@NotNull final Long dsID, final ActionType actionType, - final long forcedTimestamp, @NotEmpty final String... targetIDs) { - return assignDistributionSet(dsID, Arrays.stream(targetIDs) - .map(t -> new TargetWithActionType(t, actionType, forcedTimestamp)).collect(Collectors.toList())); - } - - /** - * 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}. - */ - @Modifying - @Transactional(isolation = Isolation.READ_COMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET) - @CacheEvict(value = { "distributionUsageAssigned" }, allEntries = true) - public DistributionSetAssignmentResult assignDistributionSet(@NotNull final Long dsID, - final List targets) { - final DistributionSet set = distributoinSetRepository.findOne(dsID); - if (set == null) { - throw new EntityNotFoundException( - String.format("no %s with id %d found", DistributionSet.class.getSimpleName(), dsID)); - } - - return assignDistributionSetToTargets(set, targets, null, null); - } - - /** - * 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}. - */ - @Modifying - @Transactional(isolation = Isolation.READ_COMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET) - @CacheEvict(value = { "distributionUsageAssigned" }, allEntries = true) - public DistributionSetAssignmentResult assignDistributionSet(@NotNull final Long dsID, - final List targets, final Rollout rollout, final RolloutGroup rolloutGroup) { - final DistributionSet set = distributoinSetRepository.findOne(dsID); - if (set == null) { - throw new EntityNotFoundException( - String.format("no %s with id %d found", DistributionSet.class.getSimpleName(), dsID)); - } - - return assignDistributionSetToTargets(set, targets, rollout, rolloutGroup); - } - - /** - * 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}. - */ - private DistributionSetAssignmentResult assignDistributionSetToTargets(@NotNull final DistributionSet set, - final List targetsWithActionType, final Rollout rollout, - final RolloutGroup rolloutGroup) { - - if (!set.isComplete()) { - throw new IncompleteDistributionSetException( - "Distribution set of type " + set.getType().getKey() + " is incomplete: " + set.getId()); - } - - final List controllerIDs = targetsWithActionType.stream().map(TargetWithActionType::getTargetId) - .collect(Collectors.toList()); - - LOG.debug("assignDistribution({}) to {} targets", set, controllerIDs.size()); - - final Map targetsWithActionMap = targetsWithActionType.stream() - .collect(Collectors.toMap(TargetWithActionType::getTargetId, Function.identity())); - - // split tIDs length into max entries in-statement because many database - // have constraint of max entries in in-statements e.g. Oracle with - // maximum 1000 elements, so we need to split the entries here and - // execute multiple statements we take the target only into account if - // the requested operation is no duplicate of a previous one - final List targets = Lists.partition(controllerIDs, Constants.MAX_ENTRIES_IN_STATEMENT).stream() - .map(ids -> targetRepository - .findAll(TargetSpecifications.hasControllerIdAndAssignedDistributionSetIdNot(ids, set.getId()))) - .flatMap(t -> t.stream()).collect(Collectors.toList()); - - if (targets.isEmpty()) { - // detaching as it is not necessary to persist the set itself - entityManager.detach(set); - // return with nothing as all targets had the DS already assigned - return new DistributionSetAssignmentResult(Collections.emptyList(), 0, targetsWithActionType.size(), - Collections.emptyList(), targetManagement); - } - - final List> targetIds = Lists.partition( - targets.stream().map(Target::getId).collect(Collectors.toList()), Constants.MAX_ENTRIES_IN_STATEMENT); - - // override all active actions and set them into canceling state, we - // need to remember which one we have been switched to canceling state - // because for targets which we have changed to canceling we don't want - // to publish the new action update event. - final Set targetIdsCancellList = new HashSet<>(); - targetIds.forEach(ids -> targetIdsCancellList.addAll(overrideObsoleteUpdateActions(ids))); - - // cancel all scheduled actions which are in-active, these actions were - // not active before and the manual assignment which has been done - // cancels the - targetIds.forEach(tIds -> actionRepository.switchStatus(Status.CANCELED, tIds, false, Status.SCHEDULED)); - - // set assigned distribution set and TargetUpdateStatus - final String currentUser; - if (auditorProvider != null) { - currentUser = auditorProvider.getCurrentAuditor(); - } else { - currentUser = null; - } - - targetIds.forEach(tIds -> targetRepository.setAssignedDistributionSet(set, System.currentTimeMillis(), - currentUser, tIds)); - targetIds.forEach(tIds -> targetInfoRepository.setTargetUpdateStatus(TargetUpdateStatus.PENDING, tIds)); - final Map targetIdsToActions = actionRepository - .save(targets.stream().map(t -> createTargetAction(targetsWithActionMap, t, set, rollout, rolloutGroup)) - .collect(Collectors.toList())) - .stream().collect(Collectors.toMap(a -> a.getTarget().getControllerId(), Function.identity())); - - // create initial action status when action is created so we remember - // the initial running status because we will change the status - // of the action itself and with this action status we have a nicer - // action history. - targetIdsToActions.values().forEach(action -> { - final ActionStatus actionStatus = new ActionStatus(); - actionStatus.setAction(action); - actionStatus.setOccurredAt(action.getCreatedAt()); - actionStatus.setStatus(Status.RUNNING); - actionStatusRepository.save(actionStatus); - }); - - // flush to get action IDs - entityManager.flush(); - // collect updated target and actions IDs in order to return them - final DistributionSetAssignmentResult result = new DistributionSetAssignmentResult( - targets.stream().map(target -> target.getControllerId()).collect(Collectors.toList()), targets.size(), - controllerIDs.size() - targets.size(), - targetIdsToActions.values().stream().map(Action::getId).collect(Collectors.toList()), targetManagement); - - LOG.debug("assignDistribution({}) finished {}", set, result); - - final List softwareModules = softwareModuleRepository.findByAssignedTo(set); - - // detaching as it is not necessary to persist the set itself - entityManager.detach(set); - - sendDistributionSetAssignmentEvent(targets, targetIdsCancellList, targetIdsToActions, softwareModules); - - return result; - } - - private void sendDistributionSetAssignmentEvent(final List targets, final Set targetIdsCancellList, - final Map targetIdsToActions, final List softwareModules) { - targets.stream().filter(t -> !!!targetIdsCancellList.contains(t.getId())) - .forEach(t -> assignDistributionSetEvent(t, targetIdsToActions.get(t.getControllerId()).getId(), - softwareModules)); - } - - private static Action createTargetAction(final Map targetsWithActionMap, - final Target target, final DistributionSet set, final Rollout rollout, final RolloutGroup rolloutGroup) { - final Action actionForTarget = new Action(); - final TargetWithActionType targetWithActionType = targetsWithActionMap.get(target.getControllerId()); - actionForTarget.setActionType(targetWithActionType.getActionType()); - actionForTarget.setForcedTime(targetWithActionType.getForceTime()); - actionForTarget.setActive(true); - actionForTarget.setStatus(Status.RUNNING); - actionForTarget.setTarget(target); - actionForTarget.setDistributionSet(set); - actionForTarget.setRollout(rollout); - actionForTarget.setRolloutGroup(rolloutGroup); - return actionForTarget; - } - - /** - * Sends the {@link TargetAssignDistributionSetEvent} for a specific target - * to the {@link EventBus}. - * - * @param target - * the Target which has been assigned to a distribution set - * @param actionId - * the action id of the assignment - * @param softwareModules - * the software modules which have been assigned - */ - private void assignDistributionSetEvent(final Target target, final Long actionId, - final List softwareModules) { - target.getTargetInfo().setUpdateStatus(TargetUpdateStatus.PENDING); - final String targetSecurityToken = systemSecurityContext.runAsSystem(() -> { - return target.getSecurityToken(); - }); - afterCommit.afterCommit(() -> { - eventBus.post(new TargetInfoUpdateEvent(target.getTargetInfo())); - eventBus.post(new TargetAssignDistributionSetEvent(target.getOptLockRevision(), target.getTenant(), - target.getControllerId(), actionId, softwareModules, target.getTargetInfo().getAddress(), - targetSecurityToken)); - }); - } - - /** - * Removes {@link UpdateAction}s that are no longer necessary and sends - * cancellations to the controller. - * - * @param myTarget - * to override {@link UpdateAction}s - */ - private Set overrideObsoleteUpdateActions(final List targetsIds) { - - final Set cancelledTargetIds = new HashSet<>(); - - // Figure out if there are potential target/action combinations that - // need to be considered - // for cancelation - final List activeActions = actionRepository - .findByActiveAndTargetIdInAndActionStatusNotEqualToAndDistributionSetRequiredMigrationStep(targetsIds, - Action.Status.CANCELING); - activeActions.forEach(action -> { - action.setStatus(Status.CANCELING); - // document that the status has been retrieved - - actionStatusRepository.save(new ActionStatus(action, Status.CANCELING, System.currentTimeMillis(), - "manual cancelation requested")); - - cancelAssignDistributionSetEvent(action.getTarget(), action.getId()); - - cancelledTargetIds.add(action.getTarget().getId()); - }); - - actionRepository.save(activeActions); - - return cancelledTargetIds; - - } - - private DistributionSetAssignmentResult assignDistributionSetByTargetId(@NotNull final DistributionSet set, - @NotEmpty final List tIDs, final ActionType actionType, final long forcedTime) { - - return assignDistributionSetToTargets(set, tIDs.stream() - .map(t -> new TargetWithActionType(t, actionType, forcedTime)).collect(Collectors.toList()), null, - null); - - } - - /** - * Internal helper method used only inside service level. As a result is no - * additional security necessary. - * - * @param target - * to update - * @param status - * of the target - * @param setInstalledDate - * to set - * - * @return updated target - */ - Target updateTargetInfo(@NotNull final Target target, @NotNull final TargetUpdateStatus status, - final boolean setInstalledDate) { - final TargetInfo ts = target.getTargetInfo(); - ts.setUpdateStatus(status); - - if (setInstalledDate) { - ts.setInstallationDate(System.currentTimeMillis()); - } - targetInfoRepository.save(ts); - return entityManager.merge(target); - } - - /** - * Cancels given {@link Action} for given {@link Target}. The method will - * immediately add a {@link ActionStatus.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 CancelAction} or null if not in - * {@link Target#getActiveActions()}. - * @throws CancelActionNotAllowedException - * in case the given action is not active or is already a cancel - * action - */ - @Modifying - @Transactional(isolation = Isolation.READ_COMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) - public Action cancelAction(@NotNull final Action action, @NotNull final Target target) { - LOG.debug("cancelAction({}, {})", action, target); - if (action.isCancelingOrCanceled()) { - throw new CancelActionNotAllowedException("Actions in canceling or canceled state cannot be canceled"); - } - final Action myAction = entityManager.merge(action); - - if (myAction.isActive()) { - LOG.debug("action ({}) was still active. Change to {}.", action, Status.CANCELING); - myAction.setStatus(Status.CANCELING); - - // document that the status has been retrieved - actionStatusRepository.save(new ActionStatus(myAction, Status.CANCELING, System.currentTimeMillis(), - "manual cancelation requested")); - final Action saveAction = actionRepository.save(myAction); - cancelAssignDistributionSetEvent(target, myAction.getId()); - - return saveAction; - } else { - throw new CancelActionNotAllowedException( - "Action [id: " + action.getId() + "] is not active and cannot be canceled"); - } - } - - /** - * Sends the {@link CancelTargetAssignmentEvent} for a specific target to - * the {@link EventBus}. - * - * @param target - * the Target which has been assigned to a distribution set - * @param actionId - * the action id of the assignment - */ - private void cancelAssignDistributionSetEvent(final Target target, final Long actionId) { - afterCommit.afterCommit(() -> eventBus.post(new CancelTargetAssignmentEvent(target.getOptLockRevision(), - target.getTenant(), target.getControllerId(), actionId, target.getTargetInfo().getAddress()))); - } - - /** - * 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 CancelAction} or null if not in - * {@link Target#getActiveActions()}. - * @throws CancelActionNotAllowedException - * in case the given action is not active - */ - @Modifying - @Transactional(isolation = Isolation.READ_COMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) - public Action forceQuitAction(@NotNull final Action action) { - final Action mergedAction = entityManager.merge(action); - - if (!mergedAction.isCancelingOrCanceled()) { - throw new ForceQuitActionNotAllowedException( - "Action [id: " + action.getId() + "] is not canceled yet and cannot be force quit"); - } - - if (!mergedAction.isActive()) { - throw new ForceQuitActionNotAllowedException( - "Action [id: " + action.getId() + "] is not active and cannot be force quit"); - } - - LOG.warn("action ({}) was still activ and has been force quite.", action); - - // document that the status has been retrieved - actionStatusRepository.save(new ActionStatus(mergedAction, Status.CANCELED, System.currentTimeMillis(), - "A force quit has been performed.")); - - successCancellation(mergedAction); - - return actionRepository.save(mergedAction); - } - - /** - * 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 rollout for this action - * @param rolloutGroup - * the rolloutgroup for this action - */ - @Modifying - @Transactional(isolation = Isolation.READ_COMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) - public void createScheduledAction(final List targets, final DistributionSet distributionSet, - final ActionType actionType, final long forcedTime, final Rollout rollout, - final RolloutGroup rolloutGroup) { - // cancel all current scheduled actions for this target. E.g. an action - // is already scheduled and a next action is created then cancel the - // current scheduled action to cancel. E.g. a new scheduled action is - // created. - final List targetIds = targets.stream().map(t -> t.getId()).collect(Collectors.toList()); - actionRepository.switchStatus(Action.Status.CANCELED, targetIds, false, Action.Status.SCHEDULED); - targets.forEach(target -> { - final Action action = new Action(); - action.setTarget(target); - action.setActive(false); - action.setDistributionSet(distributionSet); - action.setActionType(actionType); - action.setForcedTime(forcedTime); - action.setStatus(Status.SCHEDULED); - action.setRollout(rollout); - action.setRolloutGroup(rolloutGroup); - actionRepository.save(action); - }); - } - - /** - * Starting an action which is scheduled, e.g. in case of rollout a - * scheduled action must be started now. - * - * @param action - * the action to start now. - * @return the action which has been started - */ - @Modifying - @Transactional(isolation = Isolation.READ_COMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET + SpringEvalExpressions.HAS_AUTH_OR - + SpringEvalExpressions.IS_SYSTEM_CODE) - public Action startScheduledAction(@NotNull final Action action) { - - final Action mergedAction = entityManager.merge(action); - final Target mergedTarget = entityManager.merge(action.getTarget()); - - // check if we need to override running update actions - final Set overrideObsoleteUpdateActions = overrideObsoleteUpdateActions( - Collections.singletonList(action.getTarget().getId())); - - final boolean hasDistributionSetAlreadyAssigned = targetRepository - .count(TargetSpecifications.hasControllerIdAndAssignedDistributionSetIdNot( - Collections.singletonList(mergedTarget.getControllerId()), - action.getDistributionSet().getId())) == 0; - if (hasDistributionSetAlreadyAssigned) { - // the target has already the distribution set assigned, we don't - // need to start the scheduled action, just finished it. - mergedAction.setStatus(Status.FINISHED); - mergedAction.setActive(false); - return actionRepository.save(mergedAction); - } - - mergedAction.setActive(true); - mergedAction.setStatus(Status.RUNNING); - final Action savedAction = actionRepository.save(mergedAction); - - final ActionStatus actionStatus = new ActionStatus(); - actionStatus.setAction(action); - actionStatus.setOccurredAt(action.getCreatedAt()); - actionStatus.setStatus(Status.RUNNING); - actionStatusRepository.save(actionStatus); - - mergedTarget.setAssignedDistributionSet(action.getDistributionSet()); - final TargetInfo targetInfo = mergedTarget.getTargetInfo(); - targetInfo.setUpdateStatus(TargetUpdateStatus.PENDING); - targetRepository.save(mergedTarget); - targetInfoRepository.save(targetInfo); - - // in case we canceled an action before for this target, then don't fire - // assignment event - if (!overrideObsoleteUpdateActions.contains(savedAction.getId())) { - final List softwareModules = softwareModuleRepository - .findByAssignedTo(action.getDistributionSet()); - // send distribution set assignment event - - assignDistributionSetEvent(mergedAction.getTarget(), mergedAction.getId(), softwareModules); - } - return savedAction; - } - - /** - * 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) - public Action findAction(@NotNull final Long actionId) { - return actionRepository.findOne(actionId); - } - - /** - * 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) - public Action findActionWithDetails(@NotNull final Long actionId) { - return actionRepository.findById(actionId); - } - - /** - * 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) - public Slice findActionsByTarget(final Pageable pageable, final Target target) { - return actionRepository.findByTarget(pageable, target); - } - - /** - * 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) - public List findActionsByTarget(final Target target) { - return actionRepository.findByTarget(target); - } - - /** - * 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) - public List findActionsWithStatusCountByTargetOrderByIdDesc(final Target target) { - final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); - final CriteriaQuery query = cb.createQuery(ActionWithStatusCount.class); - final Root actionRoot = query.from(Action.class); - final ListJoin actionStatusJoin = actionRoot.join(Action_.actionStatus, JoinType.LEFT); - final Join actionDsJoin = actionRoot.join(Action_.distributionSet); - final Join actionRolloutJoin = actionRoot.join(Action_.rollout, JoinType.LEFT); - - final CriteriaQuery multiselect = query.distinct(true).multiselect( - actionRoot.get(Action_.id), actionRoot.get(Action_.actionType), actionRoot.get(Action_.active), - actionRoot.get(Action_.forcedTime), actionRoot.get(Action_.status), actionRoot.get(Action_.createdAt), - actionRoot.get(Action_.lastModifiedAt), actionDsJoin.get(DistributionSet_.id), - actionDsJoin.get(DistributionSet_.name), actionDsJoin.get(DistributionSet_.version), - cb.count(actionStatusJoin), actionRolloutJoin.get(Rollout_.name)); - multiselect.where(cb.equal(actionRoot.get(Action_.target), target)); - multiselect.orderBy(cb.desc(actionRoot.get(Action_.id))); - multiselect.groupBy(actionRoot.get(Action_.id)); - return entityManager.createQuery(multiselect).getResultList(); - } - - /** - * Retrieves all {@link Action}s assigned to a specific {@link Target} and a - * given specification. - * - * @param specifiction - * the specification to narrow down the search - * @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 - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public Slice findActionsByTarget(final Specification specifiction, final Target target, - final Pageable pageable) { - - return actionRepository.findAll((Specification) (root, query, cb) -> cb - .and(specifiction.toPredicate(root, query, cb), cb.equal(root.get(Action_.target), target)), pageable); - } - - /** - * 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) - public Slice findActionsByTarget(final Target foundTarget, final Pageable pageable) { - return actionRepository.findByTarget(pageable, foundTarget); - } - - /** - * 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) - public Page findActiveActionsByTarget(final Pageable pageable, final Target target) { - return actionRepository.findByActiveAndTarget(pageable, target, true); - } - - /** - * 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) - public List findActiveActionsByTarget(final Target target) { - return actionRepository.findByActiveAndTarget(target, true); - } - - /** - * 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) - public List findInActiveActionsByTarget(final Target target) { - return actionRepository.findByActiveAndTarget(target, false); - } - - /** - * 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) - public Page findInActiveActionsByTarget(final Pageable pageable, final Target target) { - return actionRepository.findByActiveAndTarget(pageable, target, false); - } - - /** - * 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) - public Long countActionsByTarget(@NotNull final Target target) { - return actionRepository.countByTarget(target); - } - - /** - * counts all actions associated to a specific target. - * - * @param spec - * the specification to filter the count result - * @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) - public Long countActionsByTarget(@NotNull final Specification spec, @NotNull final Target target) { - return actionRepository.count((root, query, cb) -> cb.and(spec.toPredicate(root, query, cb), - cb.equal(root.get(Action_.target), target))); - } - - /** - * Updates a {@link TargetAction} and forces the {@link TargetAction} 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 TargetAction} - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) - public Action forceTargetAction(final Long actionId) { - final Action action = actionRepository.findOne(actionId); - if (action != null && !action.isForced()) { - action.setActionType(ActionType.FORCED); - return actionRepository.save(action); - } - return action; - } - - /** - * 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 true if {@link ActionStatus#getMessages()} - * need to be fetched. - * @return the corresponding {@link Page} of {@link ActionStatus} - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public Page findActionStatusByAction(final Pageable pageReq, final Action action, - final boolean withMessages) { - if (withMessages) { - return actionStatusRepository.getByAction(pageReq, action); - } else { - return actionStatusRepository.findByAction(pageReq, action); - } - } - - /** - * This method is called, when cancellation has been successful. It sets the - * action to canceled, resets the meta data of the target and in case there - * is a new action this action is triggered. - * - * @param action - * the action which is set to canceled - */ - void successCancellation(final Action action) { - - // set action inactive - action.setActive(false); - action.setStatus(Status.CANCELED); - - final Target target = action.getTarget(); - final List nextActiveActions = actionRepository.findByTargetAndActiveOrderByIdAsc(target, true).stream() - .filter(a -> !a.getId().equals(action.getId())).collect(Collectors.toList()); - - if (nextActiveActions.isEmpty()) { - target.setAssignedDistributionSet(target.getTargetInfo().getInstalledDistributionSet()); - updateTargetInfo(target, TargetUpdateStatus.IN_SYNC, false); - } else { - target.setAssignedDistributionSet(nextActiveActions.get(0).getDistributionSet()); - } - targetManagement.updateTarget(target); - } - - /** - * 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) - public List findActionsByRolloutGroupParentAndStatus(final Rollout rollout, - final RolloutGroup rolloutGroupParent, final Action.Status actionStatus) { - return actionRepository.findByRolloutAndRolloutGroupParentAndStatus(rollout, rolloutGroupParent, actionStatus); - } - - /** - * 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) - public List findActionsByRolloutAndStatus(final Rollout rollout, final Action.Status actionStatus) { - return actionRepository.findByRolloutAndStatus(rollout, actionStatus); - } -} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java deleted file mode 100644 index 40a578d2b..000000000 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java +++ /dev/null @@ -1,1110 +0,0 @@ -/** - * 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 static com.google.common.base.Preconditions.checkNotNull; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -import javax.persistence.Entity; -import javax.persistence.EntityManager; -import javax.validation.constraints.NotNull; - -import org.eclipse.hawkbit.eventbus.event.DistributionSetTagAssigmentResultEvent; -import org.eclipse.hawkbit.executor.AfterTransactionCommitExecutor; -import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; -import org.eclipse.hawkbit.repository.DistributionSetFilter.DistributionSetFilterBuilder; -import org.eclipse.hawkbit.repository.exception.DistributionSetCreationFailedMissingMandatoryModuleException; -import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; -import org.eclipse.hawkbit.repository.exception.EntityLockedException; -import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; -import org.eclipse.hawkbit.repository.exception.EntityReadOnlyException; -import org.eclipse.hawkbit.repository.model.Action; -import org.eclipse.hawkbit.repository.model.DistributionSet; -import org.eclipse.hawkbit.repository.model.DistributionSetMetadata; -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.DistributionSetTypeElement; -import org.eclipse.hawkbit.repository.model.DistributionSet_; -import org.eclipse.hawkbit.repository.model.DsMetadataCompositeKey; -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.specifications.DistributionSetSpecification; -import org.eclipse.hawkbit.repository.specifications.DistributionSetTypeSpecification; -import org.eclipse.hawkbit.repository.specifications.SpecificationsBuilder; -import org.hibernate.validator.constraints.NotEmpty; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.domain.Specification; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.transaction.annotation.Isolation; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.validation.annotation.Validated; - -import com.google.common.base.Strings; -import com.google.common.eventbus.EventBus; - -/** - * Business facade for managing the {@link DistributionSet}s. - * - */ -@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) -@Validated -public class DistributionSetManagement { - - @Autowired - private EntityManager entityManager; - - @Autowired - private DistributionSetRepository distributionSetRepository; - - @Autowired - private TagManagement tagManagement; - - @Autowired - private SystemManagement systemManagement; - - @Autowired - private DistributionSetTypeRepository distributionSetTypeRepository; - - @Autowired - private DistributionSetMetadataRepository distributionSetMetadataRepository; - - @Autowired - private ActionRepository actionRepository; - - @Autowired - private EventBus eventBus; - - @Autowired - private AfterTransactionCommitExecutor afterCommit; - - /** - * 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 null if it does not exist - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public DistributionSet findDistributionSetByIdWithDetails(@NotNull final Long distid) { - return distributionSetRepository.findOne(DistributionSetSpecification.byId(distid)); - } - - /** - * Find {@link DistributionSet} based on given ID without details, e.g. - * {@link DistributionSet#getAgentHub()}. - * - * @param distid - * to look for. - * @return {@link DistributionSet} or null if it does not exist - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public DistributionSet findDistributionSetById(@NotNull final Long distid) { - return distributionSetRepository.findOne(distid); - } - - /** - * {@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. - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public DistributionSetTagAssignmentResult toggleTagAssignment(@NotEmpty final List sets, - @NotNull final DistributionSetTag tag) { - return toggleTagAssignment(sets.stream().map(ds -> ds.getId()).collect(Collectors.toList()), tag.getName()); - } - - /** - * 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. - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public DistributionSetTagAssignmentResult toggleTagAssignment(@NotEmpty final Collection dsIds, - @NotNull final String tagName) { - - final Iterable sets = findDistributionSetListWithDetails(dsIds); - final DistributionSetTag myTag = tagManagement.findDistributionSetTag(tagName); - - DistributionSetTagAssignmentResult result; - final List toBeChangedDSs = new ArrayList<>(); - for (final DistributionSet set : sets) { - if (set.getTags().add(myTag)) { - toBeChangedDSs.add(set); - } - } - - // un-assignment case - if (toBeChangedDSs.isEmpty()) { - for (final DistributionSet set : sets) { - if (set.getTags().remove(myTag)) { - toBeChangedDSs.add(set); - } - } - result = new DistributionSetTagAssignmentResult(dsIds.size() - toBeChangedDSs.size(), 0, - toBeChangedDSs.size(), Collections.emptyList(), distributionSetRepository.save(toBeChangedDSs), - myTag); - } else { - result = new DistributionSetTagAssignmentResult(dsIds.size() - toBeChangedDSs.size(), toBeChangedDSs.size(), - 0, distributionSetRepository.save(toBeChangedDSs), Collections.emptyList(), myTag); - } - - final DistributionSetTagAssignmentResult resultAssignment = result; - afterCommit.afterCommit(() -> eventBus.post(new DistributionSetTagAssigmentResultEvent(resultAssignment))); - - // no reason to persist the tag - entityManager.detach(myTag); - return result; - } - - /** - * Retrieves {@link DistributionSet} List including details information, - * i.e. @link BaseSoftwareModule}s and {@link DistributionSetTag}s. - * - * @param distributionIdSet - * List of {@link DistributionSet} IDs to be found - * @return the found {@link DistributionSet}s - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public List findDistributionSetListWithDetails( - @NotEmpty final Collection distributionIdSet) { - return distributionSetRepository.findAll(DistributionSetSpecification.byIds(distributionIdSet)); - } - - /** - * Updates existing {@link DistributionSet}. - * - * @param ds - * to update - * @return the saved {@link Entity}. - * @throws NullPointerException - * of {@link DistributionSet#getId()} is null - * @throw DataDependencyViolationException in case of illegal update - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public DistributionSet updateDistributionSet(@NotNull final DistributionSet ds) { - checkNotNull(ds.getId()); - final DistributionSet persisted = findDistributionSetByIdWithDetails(ds.getId()); - checkDistributionSetSoftwareModulesIsAllowedToModify(ds, persisted.getModules()); - return distributionSetRepository.save(ds); - } - - /** - *

- * {@link DistributionSet} can be deleted/erased from the repository if they - * have never been assigned to any {@link UpdateAction} or {@link Target}. - *

- * - *

- * 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()) - *

- * - * @param set - * to delete - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) - public void deleteDistributionSet(@NotNull final DistributionSet set) { - deleteDistributionSet(set.getId()); - } - - /** - * 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 - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) - public void deleteDistributionSet(@NotEmpty final Long... distributionSetIDs) { - final List toHardDelete = new ArrayList<>(); - - final List assigned = distributionSetRepository.findAssignedDistributionSetsById(distributionSetIDs); - - // soft delete assigned - if (!assigned.isEmpty()) { - distributionSetRepository.deleteDistributionSet(assigned.toArray(new Long[assigned.size()])); - } - - // mark the rest as hard delete - for (final Long setId : distributionSetIDs) { - if (!assigned.contains(setId)) { - toHardDelete.add(setId); - } - } - - // hard delete the rest if exixts - if (!toHardDelete.isEmpty()) { - // don't give the delete statement an empty list, JPA/Oracle cannot - // handle the empty list - distributionSetRepository.deleteByIdIn(toHardDelete); - } - } - - /** - * 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. - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - public DistributionSet createDistributionSet(@NotNull final DistributionSet dSet) { - prepareDsSave(dSet); - if (dSet.getType() == null) { - dSet.setType(systemManagement.getTenantMetadata().getDefaultDsType()); - } - return distributionSetRepository.save(dSet); - } - - private void prepareDsSave(final DistributionSet dSet) { - if (dSet.getId() != null) { - throw new EntityAlreadyExistsException("Parameter seems to be an existing, already persisted entity"); - } - - if (distributionSetRepository.countByNameAndVersion(dSet.getName(), dSet.getVersion()) > 0) { - throw new EntityAlreadyExistsException("DistributionSet with that name and version already exists."); - } - - } - - /** - * 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. - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - public List createDistributionSets(@NotNull final Iterable distributionSets) { - for (final DistributionSet ds : distributionSets) { - prepareDsSave(ds); - if (ds.getType() == null) { - ds.setType(systemManagement.getTenantMetadata().getDefaultDsType()); - } - } - return distributionSetRepository.save(distributionSets); - } - - /** - * Assigns {@link SoftwareModule} to existing {@link DistributionSet}. - * - * @param ds - * to assign and update - * @param softwareModules - * to get assigned - * @return the updated {@link DistributionSet}. - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public DistributionSet assignSoftwareModules(@NotNull final DistributionSet ds, - final Set softwareModules) { - checkDistributionSetSoftwareModulesIsAllowedToModify(ds, softwareModules); - for (final SoftwareModule softwareModule : softwareModules) { - ds.addModule(softwareModule); - } - return distributionSetRepository.save(ds); - } - - /** - * 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}. - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public DistributionSet unassignSoftwareModule(@NotNull final DistributionSet ds, - final SoftwareModule softwareModule) { - final Set softwareModules = new HashSet<>(); - softwareModules.add(softwareModule); - ds.removeModule(softwareModule); - checkDistributionSetSoftwareModulesIsAllowedToModify(ds, softwareModules); - return distributionSetRepository.save(ds); - } - - /** - * 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. - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public DistributionSetType updateDistributionSetType(@NotNull final DistributionSetType dsType) { - checkNotNull(dsType.getId()); - - final DistributionSetType persisted = distributionSetTypeRepository.findOne(dsType.getId()); - - // throw exception if user tries to update a DS type that is already in - // use - if (!persisted.areModuleEntriesIdentical(dsType) && distributionSetRepository.countByType(persisted) > 0) { - throw new EntityReadOnlyException( - String.format("distribution set type %s set is already assigned to targets and cannot be changed", - dsType.getName())); - } - - return distributionSetTypeRepository.save(dsType); - } - - /** - * Generic predicate based query for {@link DistributionSetType}. - * - * @param spec - * of the search - * @param pageable - * parameter for paging - * - * @return the found {@link SoftwareModuleType}s - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public Page findDistributionSetTypesByPredicate( - @NotNull final Specification spec, @NotNull final Pageable pageable) { - return distributionSetTypeRepository.findAll(spec, pageable); - } - - /** - * @param pageable - * parameter - * @return all {@link DistributionSetType}s in the repository. - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public Page findDistributionSetTypesAll(@NotNull final Pageable pageable) { - return distributionSetTypeRepository.findByDeleted(pageable, false); - } - - /** - * 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) - public Page findDistributionSetsByFilters(@NotNull final Pageable pageable, - final DistributionSetFilter distributionSetFilter) { - final List> specList = buildDistributionSetSpecifications(distributionSetFilter); - return findByCriteriaAPI(pageable, specList); - } - - /** - * - * @param distributionSetFilter - * had details of filters to be applied - * @return a single DistributionSet which is either installed or assigned to - * a specific target or {@code null}. - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - private DistributionSet findDistributionSetsByFiltersAndInstalledOrAssignedTarget( - final DistributionSetFilter distributionSetFilter) { - final List> specList = buildDistributionSetSpecifications(distributionSetFilter); - if (specList == null || specList.isEmpty()) { - return null; - } - return distributionSetRepository.findOne(SpecificationsBuilder.combineWithAnd(specList)); - } - - /** - * 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. - * null if both are to be returned - * @param complete - * to true for returning only completed distribution - * sets or false for only incomplete ones nor - * null to return both.. - * @param complete - * set to if false uncomplete DS should also be - * shown. - * - * - * @return all found {@link DistributionSet}s - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public Page findDistributionSetsAll(@NotNull final Pageable pageReq, final Boolean deleted, - final Boolean complete) { - final List> specList = new ArrayList<>(); - - if (deleted != null) { - final Specification spec = DistributionSetSpecification.isDeleted(deleted); - specList.add(spec); - } - - if (complete != null) { - final Specification spec = DistributionSetSpecification.isCompleted(complete); - specList.add(spec); - } - - return findByCriteriaAPI(pageReq, specList); - } - - /** - * finds all {@link DistributionSet}s. - * - * @param spec - * the specification to add for the search query. - * @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. - * null if both are to be returned - * @return all found {@link DistributionSet}s - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public Page findDistributionSetsAll(@NotNull final Specification spec, - @NotNull final Pageable pageReq, final Boolean deleted) { - final List> specList = new ArrayList<>(); - if (deleted != null) { - specList.add(DistributionSetSpecification.isDeleted(deleted)); - } - specList.add(spec); - return findByCriteriaAPI(pageReq, specList); - } - - /** - * method retrieves all {@link DistributionSet}s from the repo in the - * following order: - *

- * 1) {@link DistributionSet}s which have the given {@link Target} as - * {@link TargetStatus#getInstalledDistributionSet()} - *

- * 2) {@link DistributionSet}s which have the given {@link Target} as - * {@link Target#getAssignedDistributionSet()} - *

- * 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 ID of the Target to be ordered by - * @return - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public Page findDistributionSetsAllOrderedByLinkTarget(@NotNull final Pageable pageable, - @NotNull final DistributionSetFilterBuilder distributionSetFilterBuilder, - @NotNull final String assignedOrInstalled) { - - final DistributionSetFilter filterWithInstalledTargets = distributionSetFilterBuilder - .setInstalledTargetId(assignedOrInstalled).setAssignedTargetId(null).build(); - final DistributionSet installedDS = findDistributionSetsByFiltersAndInstalledOrAssignedTarget( - filterWithInstalledTargets); - - final DistributionSetFilter filterWithAssignedTargets = distributionSetFilterBuilder.setInstalledTargetId(null) - .setAssignedTargetId(assignedOrInstalled).build(); - final DistributionSet assignedDS = findDistributionSetsByFiltersAndInstalledOrAssignedTarget( - filterWithAssignedTargets); - - final DistributionSetFilter dsFilterWithNoTargetLinked = distributionSetFilterBuilder.setInstalledTargetId(null) - .setAssignedTargetId(null).build(); - // first fine the distribution sets filtered by the given filter - // parameters - final Page findDistributionSetsByFilters = findDistributionSetsByFilters(pageable, - dsFilterWithNoTargetLinked); - - final List resultSet = new LinkedList<>(findDistributionSetsByFilters.getContent()); - int orderIndex = 0; - if (installedDS != null) { - final boolean remove = resultSet.remove(installedDS); - if (!remove) { - resultSet.remove(resultSet.size() - 1); - } - resultSet.add(orderIndex, installedDS); - orderIndex++; - } - if (assignedDS != null && !assignedDS.equals(installedDS)) { - final boolean remove = resultSet.remove(assignedDS); - if (!remove) { - resultSet.remove(resultSet.size() - 1); - } - resultSet.add(orderIndex, assignedDS); - } - - return new PageImpl<>(resultSet, pageable, findDistributionSetsByFilters.getTotalElements()); - } - - /** - * 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) - public DistributionSet findDistributionSetByNameAndVersion(@NotEmpty final String distributionName, - @NotEmpty final String version) { - final Specification spec = DistributionSetSpecification - .equalsNameAndVersionIgnoreCase(distributionName, version); - return distributionSetRepository.findOne(spec); - - } - - /** - * 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) - public Iterable findDistributionSetList(@NotEmpty final Collection dist) { - return distributionSetRepository.findAll(dist); - } - - /** - * 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) - public Long countDistributionSetsAll() { - - final List> specList = new ArrayList<>(); - - final Specification spec = DistributionSetSpecification.isDeleted(Boolean.FALSE); - specList.add(spec); - - return distributionSetRepository.count(SpecificationsBuilder.combineWithAnd(specList)); - } - - /** - * @return number of {@link DistributionSetType}s in the repository. - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public Long countDistributionSetTypesAll() { - return distributionSetTypeRepository.countByDeleted(false); - } - - /** - * @param name - * as {@link DistributionSetType#getName()} - * @return {@link DistributionSetType} if found or null if not - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public DistributionSetType findDistributionSetTypeByName(@NotNull final String name) { - return distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byName(name)); - } - - /** - * @param id - * as {@link DistributionSetType#getId()} - * @return {@link DistributionSetType} if found or null if not - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public DistributionSetType findDistributionSetTypeById(@NotNull final Long id) { - return distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byId(id)); - } - - /** - * @param key - * as {@link DistributionSetType#getKey()} - * @return {@link DistributionSetType} if found or null if not - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public DistributionSetType findDistributionSetTypeByKey(@NotNull final String key) { - return distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byKey(key)); - } - - /** - * Creates new {@link DistributionSetType}. - * - * @param type - * to create - * @return created {@link Entity} - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - public DistributionSetType createDistributionSetType(@NotNull final DistributionSetType type) { - if (type.getId() != null) { - throw new EntityAlreadyExistsException("Given type contains an Id!"); - } - - return distributionSetTypeRepository.save(type); - } - - /** - * Deletes or markes as delete in case the type is in use. - * - * @param type - * to delete - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) - public void deleteDistributionSetType(@NotNull final DistributionSetType type) { - - if (distributionSetRepository.countByType(type) > 0) { - final DistributionSetType toDelete = entityManager.merge(type); - toDelete.setDeleted(true); - distributionSetTypeRepository.save(toDelete); - } else { - distributionSetTypeRepository.delete(type.getId()); - } - } - - /** - * 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 - */ - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @Modifying - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public DistributionSetMetadata createDistributionSetMetadata(@NotNull final DistributionSetMetadata metadata) { - if (distributionSetMetadataRepository.exists(metadata.getId())) { - throwMetadataKeyAlreadyExists(metadata.getId().getKey()); - } - // merge base distribution set so optLockRevision gets updated and audit - // log written because - // modifying metadata is modifying the base distribution set itself for - // auditing purposes. - entityManager.merge(metadata.getDistributionSet()).setLastModifiedAt(0L); - return distributionSetMetadataRepository.save(metadata); - } - - /** - * 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 - */ - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @Modifying - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public List createDistributionSetMetadata( - @NotEmpty final Collection metadata) { - for (final DistributionSetMetadata distributionSetMetadata : metadata) { - checkAndThrowAlreadyIfDistributionSetMetadataExists(distributionSetMetadata.getId()); - } - metadata.forEach(m -> entityManager.merge(m.getDistributionSet()).setLastModifiedAt(-1L)); - return (List) distributionSetMetadataRepository.save(metadata); - } - - /** - * 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 - */ - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @Modifying - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public DistributionSetMetadata updateDistributionSetMetadata(@NotNull final DistributionSetMetadata metadata) { - // check if exists otherwise throw entity not found exception - findOne(metadata.getId()); - // touch it to update the lock revision because we are modifying the - // DS indirectly - entityManager.merge(metadata.getDistributionSet()).setLastModifiedAt(0L); - return distributionSetMetadataRepository.save(metadata); - } - - /** - * deletes a distribution set meta data entry. - * - * @param id - * the ID of the distribution set meta data to delete - */ - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @Modifying - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public void deleteDistributionSetMetadata(@NotNull final DsMetadataCompositeKey id) { - distributionSetMetadataRepository.delete(id); - } - - /** - * 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) - public Page findDistributionSetMetadataByDistributionSetId( - @NotNull final Long distributionSetId, @NotNull final Pageable pageable) { - - return distributionSetMetadataRepository.findAll( - (Specification) (root, query, cb) -> cb.equal( - root.get(DistributionSetMetadata_.distributionSet).get(DistributionSet_.id), distributionSetId), - pageable); - - } - - /** - * finds all meta data by the given distribution set id. - * - * @param distributionSetId - * the distribution set 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 distribution - * set id - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public Page findDistributionSetMetadataByDistributionSetId( - @NotNull final Long distributionSetId, @NotNull final Specification spec, - @NotNull final Pageable pageable) { - return distributionSetMetadataRepository - .findAll( - (Specification) (root, query, - cb) -> cb.and( - cb.equal(root.get(DistributionSetMetadata_.distributionSet) - .get(DistributionSet_.id), distributionSetId), - spec.toPredicate(root, query, cb)), - 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) - public DistributionSetMetadata findOne(@NotNull final DsMetadataCompositeKey id) { - final DistributionSetMetadata findOne = distributionSetMetadataRepository.findOne(id); - if (findOne == null) { - throw new EntityNotFoundException("Metadata with key '" + id.getKey() + "' does not exist"); - } - return findOne; - } - - /** - * 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) - public DistributionSet findDistributionSetByAction(@NotNull final Action action) { - return distributionSetRepository.findByAction(action); - } - - /** - * Creates multiple {@link DistributionSetType}s. - * - * @param types - * to create - * @return created {@link Entity} - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - public List createDistributionSetTypes(@NotNull final Collection types) { - return types.stream().map(this::createDistributionSetType).collect(Collectors.toList()); - } - - /** - * Checking Distribution Set is already using while assign Software module. - * - * @param distributionSet - * @param softwareModules - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public void checkDistributionSetAlreadyUse(final DistributionSet distributionSet) { - checkDistributionSetSoftwareModulesIsAllowedToModify(distributionSet); - } - - private List> buildDistributionSetSpecifications( - final DistributionSetFilter distributionSetFilter) { - final List> specList = new ArrayList<>(); - - Specification spec; - - if (null != distributionSetFilter.getIsComplete()) { - spec = DistributionSetSpecification.isCompleted(distributionSetFilter.getIsComplete()); - specList.add(spec); - } - - if (null != distributionSetFilter.getIsDeleted()) { - spec = DistributionSetSpecification.isDeleted(distributionSetFilter.getIsDeleted()); - specList.add(spec); - } - - if (distributionSetFilter.getType() != null) { - spec = DistributionSetSpecification.byType(distributionSetFilter.getType()); - specList.add(spec); - } - - if (!Strings.isNullOrEmpty(distributionSetFilter.getSearchText())) { - spec = DistributionSetSpecification.likeNameOrDescriptionOrVersion(distributionSetFilter.getSearchText()); - specList.add(spec); - } - - if (isDSWithNoTagSelected(distributionSetFilter) || isTagsSelected(distributionSetFilter)) { - spec = DistributionSetSpecification.hasTags(distributionSetFilter.getTagNames(), - distributionSetFilter.getSelectDSWithNoTag()); - specList.add(spec); - } - if (distributionSetFilter.getInstalledTargetId() != null) { - spec = DistributionSetSpecification.installedTarget(distributionSetFilter.getInstalledTargetId()); - specList.add(spec); - } - if (distributionSetFilter.getAssignedTargetId() != null) { - spec = DistributionSetSpecification.assignedTarget(distributionSetFilter.getAssignedTargetId()); - specList.add(spec); - } - return specList; - } - - private void checkDistributionSetSoftwareModulesIsAllowedToModify(final DistributionSet distributionSet, - final Set softwareModules) { - if (!new HashSet(distributionSet.getModules()).equals(softwareModules) - && actionRepository.countByDistributionSet(distributionSet) > 0) { - throw new EntityLockedException( - String.format("distribution set %s:%s is already assigned to targets and cannot be changed", - distributionSet.getName(), distributionSet.getVersion())); - } - } - - private void checkDistributionSetSoftwareModulesIsAllowedToModify(final DistributionSet distributionSet) { - if (actionRepository.countByDistributionSet(distributionSet) > 0) { - throw new EntityLockedException( - String.format("distribution set %s:%s is already assigned to targets and cannot be changed", - distributionSet.getName(), distributionSet.getVersion())); - } - } - - private static Boolean isDSWithNoTagSelected(final DistributionSetFilter distributionSetFilter) { - if (distributionSetFilter.getSelectDSWithNoTag() != null && distributionSetFilter.getSelectDSWithNoTag()) { - return true; - } - return false; - } - - private static Boolean isTagsSelected(final DistributionSetFilter distributionSetFilter) { - if (distributionSetFilter.getTagNames() != null && !distributionSetFilter.getTagNames().isEmpty()) { - return true; - } - return false; - } - - /** - * executes findAll with the given {@link DistributionSet} - * {@link Specification}s. - * - * @param pageable - * paging parameter - * @param specList - * list of @link {@link Specification} - * @return the page with the found {@link DistributionSet} - */ - private Page findByCriteriaAPI(@NotNull final Pageable pageable, - final List> specList) { - - if (specList == null || specList.isEmpty()) { - return distributionSetRepository.findAll(pageable); - } - - return distributionSetRepository.findAll(SpecificationsBuilder.combineWithAnd(specList), pageable); - } - - private void checkAndThrowAlreadyIfDistributionSetMetadataExists(final DsMetadataCompositeKey metadataId) { - if (distributionSetMetadataRepository.exists(metadataId)) { - throw new EntityAlreadyExistsException( - "Metadata entry with key '" + metadataId.getKey() + "' already exists"); - } - } - - private static void throwMetadataKeyAlreadyExists(final String metadataKey) { - throw new EntityAlreadyExistsException("Metadata entry with key '" + metadataKey + "' already exists"); - } - - /** - * Assign a {@link DistributionSetTag} assignment to given - * {@link DistributionSet}s. - * - * @param dsIds - * to assign for - * @param tag - * to assign - * @return list of assigned ds - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) - public List assignTag(@NotEmpty final Collection dsIds, - @NotNull final DistributionSetTag tag) { - final List allDs = findDistributionSetListWithDetails(dsIds); - - allDs.forEach(ds -> ds.getTags().add(tag)); - final List save = distributionSetRepository.save(allDs); - - afterCommit.afterCommit(() -> { - - final DistributionSetTagAssignmentResult result = new DistributionSetTagAssignmentResult(0, save.size(), 0, - save, Collections.emptyList(), tag); - eventBus.post(new DistributionSetTagAssigmentResultEvent(result)); - }); - - return save; - } - - /** - * Unassign all {@link DistributionSet} from a given - * {@link DistributionSetTag} . - * - * @param tag - * to unassign all ds - * @return list of unassigned ds - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) - public List unAssignAllDistributionSetsByTag(@NotNull final DistributionSetTag tag) { - return unAssignTag(tag.getAssignedToDistributionSet(), tag); - } - - /** - * Unassign a {@link DistributionSetTag} assignment to given - * {@link DistributionSet}. - * - * @param dsId - * to unassign for - * @param distributionSetTag - * to unassign - * @return the unassigned ds or if no ds is unassigned - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) - public DistributionSet unAssignTag(@NotNull final Long dsId, @NotNull final DistributionSetTag distributionSetTag) { - final List allDs = findDistributionSetListWithDetails(Arrays.asList(dsId)); - final List unAssignTag = unAssignTag(allDs, distributionSetTag); - return unAssignTag.isEmpty() ? null : unAssignTag.get(0); - } - - private List unAssignTag(final Collection distributionSets, - final DistributionSetTag tag) { - distributionSets.forEach(ds -> ds.getTags().remove(tag)); - return distributionSetRepository.save(distributionSets); - } -} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareManagement.java deleted file mode 100644 index 88af60c18..000000000 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareManagement.java +++ /dev/null @@ -1,931 +0,0 @@ -/** - * 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 static com.google.common.base.Preconditions.checkNotNull; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -import javax.persistence.Entity; -import javax.persistence.EntityManager; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.ListJoin; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; -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.model.CustomSoftwareModule; -import org.eclipse.hawkbit.repository.model.DistributionSet; -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.SoftwareModuleMetadata_; -import org.eclipse.hawkbit.repository.model.SoftwareModuleType; -import org.eclipse.hawkbit.repository.model.SoftwareModule_; -import org.eclipse.hawkbit.repository.model.SwMetadataCompositeKey; -import org.eclipse.hawkbit.repository.specifications.SoftwareModuleSpecification; -import org.eclipse.hawkbit.repository.specifications.SpecificationsBuilder; -import org.hibernate.validator.constraints.NotEmpty; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.AuditorAware; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Slice; -import org.springframework.data.domain.SliceImpl; -import org.springframework.data.jpa.domain.Specification; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.transaction.annotation.Isolation; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.validation.annotation.Validated; - -import com.google.common.base.Strings; -import com.google.common.collect.Sets; - -/** - * Business facade for managing {@link SoftwareModule}s. - * - */ -@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) -@Validated -public class SoftwareManagement { - - @Autowired - private EntityManager entityManager; - - @Autowired - private DistributionSetRepository distributionSetRepository; - - @Autowired - private DistributionSetTypeRepository distributionSetTypeRepository; - - @Autowired - private SoftwareModuleRepository softwareModuleRepository; - - @Autowired - private SoftwareModuleMetadataRepository softwareModuleMetadataRepository; - - @Autowired - private SoftwareModuleTypeRepository softwareModuleTypeRepository; - - @Autowired - private NoCountPagingRepository criteriaNoCountDao; - - @Autowired - private AuditorAware auditorProvider; - - @Autowired - private ArtifactManagement artifactManagement; - - /** - * 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 null - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public SoftwareModule updateSoftwareModule(@NotNull final SoftwareModule sm) { - checkNotNull(sm.getId()); - - final SoftwareModule module = softwareModuleRepository.findOne(sm.getId()); - - boolean updated = false; - if (null == sm.getDescription() || !sm.getDescription().equals(module.getDescription())) { - module.setDescription(sm.getDescription()); - updated = true; - } - if (null == sm.getVendor() || !sm.getVendor().equals(module.getVendor())) { - module.setVendor(sm.getVendor()); - updated = true; - } - - return updated ? softwareModuleRepository.save(module) : module; - } - - /** - * Updates existing {@link SoftwareModuleType}. Update-able value is - * {@link SoftwareModuleType#getDescription()} and - * {@link SoftwareModuleType#getColour()}. - * - * @param sm - * to update - * @return updated {@link Entity} - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public SoftwareModuleType updateSoftwareModuleType(@NotNull final SoftwareModuleType sm) { - checkNotNull(sm.getId()); - - final SoftwareModuleType type = softwareModuleTypeRepository.findOne(sm.getId()); - - boolean updated = false; - if (sm.getDescription() != null && !sm.getDescription().equals(type.getDescription())) { - type.setDescription(sm.getDescription()); - updated = true; - } - if (sm.getColour() != null && !sm.getColour().equals(type.getColour())) { - type.setColour(sm.getColour()); - updated = true; - } - return updated ? softwareModuleTypeRepository.save(type) : type; - } - - /** - * - * @param swModule - * SoftwareModule to create - * @return SoftwareModule - * @throws EntityAlreadyExistsException - * if a given entity already exists - */ - @Modifying - @Transactional - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - public SoftwareModule createSoftwareModule(@NotNull final SoftwareModule swModule) { - if (null != swModule.getId()) { - throw new EntityAlreadyExistsException(); - } - return softwareModuleRepository.save(swModule); - } - - /** - * Create {@link SoftwareModule}s in the repository. - * - * @param swModules - * {@link SoftwareModule}s to create - * @return SoftwareModule - * @throws EntityAlreadyExistsException - * if a given entity already exists - */ - @Modifying - @Transactional - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - public List createSoftwareModule(@NotNull final Iterable swModules) { - swModules.forEach(swModule -> { - if (null != swModule.getId()) { - throw new EntityAlreadyExistsException(); - } - }); - - return softwareModuleRepository.save(swModules); - - } - - /** - * 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) - public Slice findSoftwareModulesByType(@NotNull final Pageable pageable, - @NotNull final SoftwareModuleType type) { - - final List> specList = new ArrayList<>(); - - Specification spec = SoftwareModuleSpecification.equalType(type); - specList.add(spec); - - spec = SoftwareModuleSpecification.isDeletedFalse(); - specList.add(spec); - - return findSwModuleByCriteriaAPI(pageable, specList); - } - - /** - * 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) - public Long countSoftwareModulesByType(@NotNull final SoftwareModuleType type) { - - final List> specList = new ArrayList<>(); - - Specification spec = SoftwareModuleSpecification.equalType(type); - specList.add(spec); - - spec = SoftwareModuleSpecification.isDeletedFalse(); - specList.add(spec); - - return countSwModuleByCriteriaAPI(specList); - } - - /** - * Finds {@link SoftwareModule} by given id. - * - * @param id - * to search for - * @return the found {@link SoftwareModule}s or null if not - * found. - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR - + SpringEvalExpressions.IS_CONTROLLER) - public SoftwareModule findSoftwareModuleById(@NotNull final Long id) { - return artifactManagement.findSoftwareModuleById(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 null - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public SoftwareModule findSoftwareModuleByNameAndVersion(@NotEmpty final String name, - @NotEmpty final String version, @NotNull final SoftwareModuleType type) { - - return softwareModuleRepository.findOneByNameAndVersionAndType(name, version, type); - } - - /** - * Deletes the given {@link SoftwareModule} {@link Entity}. - * - * @param bsm - * is the {@link SoftwareModule} to be deleted - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) - public void deleteSoftwareModule(@NotNull final SoftwareModule bsm) { - - deleteSoftwareModules(Sets.newHashSet(bsm.getId())); - } - - private boolean isUnassigned(final SoftwareModule bsmMerged) { - return distributionSetRepository.findByModules(bsmMerged).isEmpty(); - } - - private Slice findSwModuleByCriteriaAPI(@NotNull final Pageable pageable, - @NotEmpty final List> specList) { - return criteriaNoCountDao.findAll(SpecificationsBuilder.combineWithAnd(specList), pageable, - SoftwareModule.class); - } - - private Long countSwModuleByCriteriaAPI(@NotEmpty final List> specList) { - return softwareModuleRepository.count(SpecificationsBuilder.combineWithAnd(specList)); - } - - private void deleteGridFsArtifacts(final SoftwareModule swModule) { - for (final LocalArtifact localArtifact : swModule.getLocalArtifacts()) { - artifactManagement.deleteGridFsArtifact(localArtifact); - } - } - - /** - * Deletes {@link SoftwareModule}s which is any if the given ids. - * - * @param ids - * of the Software Modules to be deleted - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) - public void deleteSoftwareModules(@NotNull final Iterable ids) { - final List swModulesToDelete = softwareModuleRepository.findByIdIn(ids); - final Set assignedModuleIds = new HashSet<>(); - swModulesToDelete.forEach(swModule -> { - - // delete binary data of artifacts - deleteGridFsArtifacts(swModule); - - if (isUnassigned(swModule)) { - - softwareModuleRepository.delete(swModule); - - } else { - - assignedModuleIds.add(swModule.getId()); - } - }); - - if (!assignedModuleIds.isEmpty()) { - String currentUser = null; - if (auditorProvider != null) { - currentUser = auditorProvider.getCurrentAuditor(); - } - softwareModuleRepository.deleteSoftwareModule(System.currentTimeMillis(), currentUser, - assignedModuleIds.toArray(new Long[0])); - } - } - - /** - * Retrieves all software modules. Deleted ones are filtered. - * - * @param pageable - * pagination parameter - * @return the found {@link SoftwareModule}s - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public Slice findSoftwareModulesAll(@NotNull final Pageable pageable) { - - final List> specList = new ArrayList<>(); - - Specification spec = SoftwareModuleSpecification.isDeletedFalse(); - specList.add(spec); - - spec = (root, query, cb) -> { - if (!query.getResultType().isAssignableFrom(Long.class)) { - root.fetch(SoftwareModule_.type); - } - return cb.conjunction(); - }; - - specList.add(spec); - - return findSwModuleByCriteriaAPI(pageable, specList); - } - - /** - * 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) - public Long countSoftwareModulesAll() { - - final List> specList = new ArrayList<>(); - - final Specification spec = SoftwareModuleSpecification.isDeletedFalse(); - specList.add(spec); - - return countSwModuleByCriteriaAPI(specList); - } - - /** - * 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) - public SoftwareModule findSoftwareModuleWithDetails(@NotNull final Long id) { - return artifactManagement.findSoftwareModuleWithDetails(id); - } - - /** - * 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 - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public Page findSoftwareModulesByPredicate(@NotNull final Specification spec, - @NotNull final Pageable pageable) { - return softwareModuleRepository.findAll(spec, 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 - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public Page findSoftwareModuleTypesByPredicate( - @NotNull final Specification spec, @NotNull final Pageable pageable) { - return softwareModuleTypeRepository.findAll(spec, 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 - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public List findSoftwareModulesById(@NotEmpty final List ids) { - return softwareModuleRepository.findByIdIn(ids); - } - - /** - * 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) - public Slice findSoftwareModuleByFilters(@NotNull final Pageable pageable, final String searchText, - final SoftwareModuleType type) { - - final List> specList = new ArrayList<>(); - - Specification spec = SoftwareModuleSpecification.isDeletedFalse(); - specList.add(spec); - - if (!Strings.isNullOrEmpty(searchText)) { - spec = SoftwareModuleSpecification.likeNameOrVersion(searchText); - specList.add(spec); - } - - if (null != type) { - spec = SoftwareModuleSpecification.equalType(type); - specList.add(spec); - } - - spec = (root, query, cb) -> { - if (!query.getResultType().isAssignableFrom(Long.class)) { - root.fetch(SoftwareModule_.type); - } - return cb.conjunction(); - }; - - specList.add(spec); - - return findSwModuleByCriteriaAPI(pageable, specList); - } - - /** - * 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) - public Slice findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc( - @NotNull final Pageable pageable, @NotNull final Long orderByDistributionId, final String searchText, - final SoftwareModuleType type) { - - final List resultList = new ArrayList<>(); - final int pageSize = pageable.getPageSize(); - final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); - - // get the assigned software modules - final CriteriaQuery assignedQuery = cb.createQuery(SoftwareModule.class); - final Root assignedRoot = assignedQuery.from(SoftwareModule.class); - assignedQuery.distinct(true); - final ListJoin assignedDsJoin = assignedRoot.join(SoftwareModule_.assignedTo); - // build the specifications and then to predicates necessary by the - // given filters - final Predicate[] specPredicate = specificationsToPredicate(buildSpecificationList(searchText, type), - assignedRoot, assignedQuery, cb, - cb.equal(assignedDsJoin.get(DistributionSet_.id), orderByDistributionId)); - // if we have some predicates then add it to the where clause of the - // multi select - assignedQuery.where(specPredicate); - assignedQuery.orderBy(cb.asc(assignedRoot.get(SoftwareModule_.name)), - cb.asc(assignedRoot.get(SoftwareModule_.version))); - // don't page the assigned query on database, we need all assigned - // software modules to filter - // them out in the unassigned query - final List assignedSoftwareModules = entityManager.createQuery(assignedQuery).getResultList(); - // map result - if (pageable.getOffset() < assignedSoftwareModules.size()) { - assignedSoftwareModules - .subList(pageable.getOffset(), Math.min(assignedSoftwareModules.size(), pageable.getPageSize())) - .forEach(sw -> resultList.add(new CustomSoftwareModule(sw, true))); - } - - if (assignedSoftwareModules.size() >= pageSize) { - return new SliceImpl<>(resultList); - } - - // get the unassigned software modules - final CriteriaQuery unassignedQuery = cb.createQuery(SoftwareModule.class); - unassignedQuery.distinct(true); - final Root unassignedRoot = unassignedQuery.from(SoftwareModule.class); - - Predicate[] unassignedSpec; - if (!assignedSoftwareModules.isEmpty()) { - unassignedSpec = specificationsToPredicate(buildSpecificationList(searchText, type), unassignedRoot, - unassignedQuery, cb, cb.not(unassignedRoot.get(SoftwareModule_.id) - .in(assignedSoftwareModules.stream().map(sw -> sw.getId()).collect(Collectors.toList())))); - } else { - unassignedSpec = specificationsToPredicate(buildSpecificationList(searchText, type), unassignedRoot, - unassignedQuery, cb); - } - - unassignedQuery.where(unassignedSpec); - unassignedQuery.orderBy(cb.asc(unassignedRoot.get(SoftwareModule_.name)), - cb.asc(unassignedRoot.get(SoftwareModule_.version))); - final List unassignedSoftwareModules = entityManager.createQuery(unassignedQuery) - .setFirstResult(Math.max(0, pageable.getOffset() - assignedSoftwareModules.size())) - .setMaxResults(pageSize).getResultList(); - // map result - unassignedSoftwareModules.forEach(sw -> resultList.add(new CustomSoftwareModule(sw, false))); - - return new SliceImpl<>(resultList); - } - - private static List> buildSpecificationList(final String searchText, - final SoftwareModuleType type) { - final List> specList = new ArrayList<>(); - if (!Strings.isNullOrEmpty(searchText)) { - specList.add(SoftwareModuleSpecification.likeNameOrVersion(searchText)); - } - if (type != null) { - specList.add(SoftwareModuleSpecification.equalType(type)); - } - specList.add(SoftwareModuleSpecification.isDeletedFalse()); - return specList; - } - - /** - * @param specifications - */ - private Predicate[] specificationsToPredicate(final List> specifications, - final Root root, final CriteriaQuery query, final CriteriaBuilder cb, - final Predicate... additionalPredicates) { - final List predicates = new ArrayList<>(); - specifications.forEach(spec -> predicates.add(spec.toPredicate(root, query, cb))); - for (final Predicate predicate : additionalPredicates) { - predicates.add(predicate); - } - return predicates.toArray(new Predicate[predicates.size()]); - } - - /** - * 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) - public Long countSoftwareModuleByFilters(final String searchText, final SoftwareModuleType type) { - - final List> specList = new ArrayList<>(); - - Specification spec = SoftwareModuleSpecification.isDeletedFalse(); - specList.add(spec); - - if (!Strings.isNullOrEmpty(searchText)) { - spec = SoftwareModuleSpecification.likeNameOrVersion(searchText); - specList.add(spec); - } - - if (null != type) { - spec = SoftwareModuleSpecification.equalType(type); - specList.add(spec); - } - - return countSwModuleByCriteriaAPI(specList); - } - - /** - * @param pageable - * parameter - * @return all {@link SoftwareModuleType}s in the repository. - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public Page findSoftwareModuleTypesAll(@NotNull final Pageable pageable) { - return softwareModuleTypeRepository.findByDeleted(pageable, false); - } - - /** - * @return number of {@link SoftwareModuleType}s in the repository. - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public Long countSoftwareModuleTypesAll() { - return softwareModuleTypeRepository.countByDeleted(false); - } - - /** - * - * @param key - * to search for - * @return {@link SoftwareModuleType} in the repository with given - * {@link SoftwareModuleType#getKey()} - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public SoftwareModuleType findSoftwareModuleTypeByKey(@NotNull final String key) { - return softwareModuleTypeRepository.findByKey(key); - } - - /** - * - * @param id - * to search for - * @return {@link SoftwareModuleType} in the repository with given - * {@link SoftwareModuleType#getId()} - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public SoftwareModuleType findSoftwareModuleTypeById(@NotNull final Long id) { - return softwareModuleTypeRepository.findOne(id); - } - - /** - * - * @param name - * to search for - * @return all {@link SoftwareModuleType}s in the repository with given - * {@link SoftwareModuleType#getName()} - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public SoftwareModuleType findSoftwareModuleTypeByName(@NotNull final String name) { - return softwareModuleTypeRepository.findByName(name); - } - - /** - * Creates new {@link SoftwareModuleType}. - * - * @param type - * to create - * @return created {@link Entity} - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - public SoftwareModuleType createSoftwareModuleType(@NotNull final SoftwareModuleType type) { - if (type.getId() != null) { - throw new EntityAlreadyExistsException("Given type contains an Id!"); - } - - return softwareModuleTypeRepository.save(type); - } - - /** - * Creates multiple {@link SoftwareModuleType}s. - * - * @param types - * to create - * @return created {@link Entity} - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - public List createSoftwareModuleType(@NotNull final Collection types) { - return types.stream().map(this::createSoftwareModuleType).collect(Collectors.toList()); - } - - /** - * Deletes or markes as delete in case the type is in use. - * - * @param type - * to delete - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) - public void deleteSoftwareModuleType(@NotNull final SoftwareModuleType type) { - - if (softwareModuleRepository.countByType(type) > 0 - || distributionSetTypeRepository.countByElementsSmType(type) > 0) { - final SoftwareModuleType toDelete = entityManager.merge(type); - toDelete.setDeleted(true); - softwareModuleTypeRepository.save(toDelete); - } else { - softwareModuleTypeRepository.delete(type.getId()); - } - } - - /** - * @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) - public Page findSoftwareModuleByAssignedTo(@NotNull final Pageable pageable, - @NotNull final DistributionSet set) { - return softwareModuleRepository.findByAssignedTo(pageable, 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) - public Page findSoftwareModuleByAssignedToAndType(@NotNull final Pageable pageable, - @NotNull final DistributionSet set, @NotNull final SoftwareModuleType type) { - return softwareModuleRepository.findByAssignedToAndType(pageable, set, type); - } - - /** - * 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 - */ - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @Modifying - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public SoftwareModuleMetadata createSoftwareModuleMetadata(@NotNull final SoftwareModuleMetadata metadata) { - if (softwareModuleMetadataRepository.exists(metadata.getId())) { - throwMetadataKeyAlreadyExists(metadata.getId().getKey()); - } - // merge base software module so optLockRevision gets updated and audit - // log written because - // modifying metadata is modifying the base software module itself for - // auditing purposes. - entityManager.merge(metadata.getSoftwareModule()).setLastModifiedAt(-1L); - return softwareModuleMetadataRepository.save(metadata); - } - - /** - * 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 - */ - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @Modifying - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public List createSoftwareModuleMetadata( - @NotEmpty final Collection metadata) { - for (final SoftwareModuleMetadata softwareModuleMetadata : metadata) { - checkAndThrowAlreadyExistsIfSoftwareModuleMetadataExists(softwareModuleMetadata.getId()); - } - metadata.forEach(m -> entityManager.merge(m.getSoftwareModule()).setLastModifiedAt(-1L)); - return softwareModuleMetadataRepository.save(metadata); - } - - /** - * 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 - */ - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @Modifying - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public SoftwareModuleMetadata updateSoftwareModuleMetadata(@NotNull final SoftwareModuleMetadata metadata) { - // check if exists otherwise throw entity not found exception - findSoftwareModuleMetadata(metadata.getId()); - // touch it to update the lock revision because we are modifying the - // software module - // indirectly - entityManager.merge(metadata.getSoftwareModule()).setLastModifiedAt(-1L); - return softwareModuleMetadataRepository.save(metadata); - } - - /** - * deletes a software module meta data entry. - * - * @param id - * the ID of the software module meta data to delete - */ - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @Modifying - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public void deleteSoftwareModuleMetadata(@NotNull final SwMetadataCompositeKey id) { - softwareModuleMetadataRepository.delete(id); - } - - /** - * 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) - public Page findSoftwareModuleMetadataBySoftwareModuleId(@NotNull final Long swId, - @NotNull final Pageable pageable) { - return softwareModuleMetadataRepository.findBySoftwareModuleId(swId, 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 - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public Page findSoftwareModuleMetadataBySoftwareModuleId(final Long softwareModuleId, - @NotNull final Specification spec, @NotNull final Pageable pageable) { - return softwareModuleMetadataRepository - .findAll( - (Specification) (root, query, - cb) -> cb.and( - cb.equal(root.get(SoftwareModuleMetadata_.softwareModule) - .get(SoftwareModule_.id), softwareModuleId), - spec.toPredicate(root, query, cb)), - pageable); - } - - /** - * 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) - public SoftwareModuleMetadata findSoftwareModuleMetadata(@NotNull final SwMetadataCompositeKey id) { - final SoftwareModuleMetadata findOne = softwareModuleMetadataRepository.findOne(id); - if (findOne == null) { - throw new EntityNotFoundException("Metadata with key '" + id.getKey() + "' does not exist"); - } - return findOne; - } - - private void checkAndThrowAlreadyExistsIfSoftwareModuleMetadataExists(final SwMetadataCompositeKey metadataId) { - if (softwareModuleMetadataRepository.exists(metadataId)) { - throw new EntityAlreadyExistsException( - "Metadata entry with key '" + metadataId.getKey() + "' already exists"); - } - } - - private static void throwMetadataKeyAlreadyExists(final String metadataKey) { - throw new EntityAlreadyExistsException("Metadata entry with key '" + metadataKey + "' already exists"); - } - -} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TagManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TagManagement.java deleted file mode 100644 index 59fe75951..000000000 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TagManagement.java +++ /dev/null @@ -1,421 +0,0 @@ -/** - * 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 static com.google.common.base.Preconditions.checkNotNull; - -import java.util.LinkedList; -import java.util.List; - -import javax.validation.constraints.NotNull; - -import org.eclipse.hawkbit.eventbus.event.DistributionSetTagCreatedBulkEvent; -import org.eclipse.hawkbit.eventbus.event.DistributionSetTagDeletedEvent; -import org.eclipse.hawkbit.eventbus.event.DistributionSetTagUpdateEvent; -import org.eclipse.hawkbit.eventbus.event.TargetTagCreatedBulkEvent; -import org.eclipse.hawkbit.eventbus.event.TargetTagDeletedEvent; -import org.eclipse.hawkbit.eventbus.event.TargetTagUpdateEvent; -import org.eclipse.hawkbit.executor.AfterTransactionCommitExecutor; -import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; -import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; -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.eclipse.hawkbit.tenancy.TenantAware; -import org.hibernate.validator.constraints.NotEmpty; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.domain.Specification; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.transaction.annotation.Isolation; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.validation.annotation.Validated; - -import com.google.common.eventbus.EventBus; - -/** - * Management service class for {@link Tag}s. - * - */ -@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) -@Validated -public class TagManagement { - - @Autowired - private TargetTagRepository targetTagRepository; - - @Autowired - private TargetRepository targetRepository; - - @Autowired - private DistributionSetTagRepository distributionSetTagRepository; - - @Autowired - private DistributionSetRepository distributionSetRepository; - - @Autowired - private EventBus eventBus; - - @Autowired - private TenantAware tenantAware; - - @Autowired - private AfterTransactionCommitExecutor afterCommit; - - /** - * Find {@link TargetTag} based on given Name. - * - * @param name - * to look for. - * @return {@link TargetTag} or null if it does not exist - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public TargetTag findTargetTag(@NotEmpty final String name) { - return targetTagRepository.findByNameEquals(name); - } - - /** - * Creates a new {@link TargetTag}. - * - * @param targetTag - * to be created - * - * @return the new created {@link TargetTag} - * - * @throws EntityAlreadyExistsException - * if given object already exists - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET) - public TargetTag createTargetTag(@NotNull final TargetTag targetTag) { - if (null != targetTag.getId()) { - throw new EntityAlreadyExistsException(); - } - - if (findTargetTag(targetTag.getName()) != null) { - throw new EntityAlreadyExistsException(); - } - - final TargetTag save = targetTagRepository.save(targetTag); - - afterCommit - .afterCommit(() -> eventBus.post(new TargetTagCreatedBulkEvent(tenantAware.getCurrentTenant(), save))); - - return save; - } - - /** - * 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. - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET) - public List createTargetTags(@NotNull final Iterable targetTags) { - targetTags.forEach(tag -> { - if (tag.getId() != null) { - throw new EntityAlreadyExistsException(); - } - }); - final List save = targetTagRepository.save(targetTags); - afterCommit - .afterCommit(() -> eventBus.post(new TargetTagCreatedBulkEvent(tenantAware.getCurrentTenant(), save))); - return save; - } - - /** - * Deletes {@link TargetTag} with given name. - * - * @param targetTagName - * tag name of the {@link TargetTag} to be deleted - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_TARGET) - public void deleteTargetTag(@NotEmpty final String targetTagName) { - final TargetTag tag = targetTagRepository.findByNameEquals(targetTagName); - - final List changed = new LinkedList<>(); - for (final Target target : targetRepository.findByTag(tag)) { - target.getTags().remove(tag); - changed.add(target); - } - - // save association delete - targetRepository.save(changed); - - // finally delete the tag itself - targetTagRepository.deleteByName(targetTagName); - - afterCommit.afterCommit(() -> eventBus.post(new TargetTagDeletedEvent(tag))); - - } - - /** - * returns all {@link TargetTag}s. - * - * @return all {@link TargetTag}s - */ - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public List findAllTargetTags() { - return targetTagRepository.findAll(); - } - - /** - * Retrieves all target tags based on the given specification. - * - * @param spec - * the specification for the query - * @param pageable - * pagination parameter - * @return the found {@link Target}s, never {@code null} - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public Page findAllTargetTags(@NotNull final Specification spec, - @NotNull final Pageable pageable) { - return targetTagRepository.findAll(spec, pageable); - } - - /** - * count {@link TargetTag}s. - * - * @return size of {@link TargetTag}s - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public long countTargetTags() { - return targetTagRepository.count(); - } - - /** - * updates the {@link TargetTag}. - * - * @param targetTag - * the {@link TargetTag} - * @return the new {@link TargetTag} - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) - public TargetTag updateTargetTag(@NotNull final TargetTag targetTag) { - checkNotNull(targetTag.getName()); - checkNotNull(targetTag.getId()); - final TargetTag save = targetTagRepository.save(targetTag); - afterCommit.afterCommit(() -> eventBus.post(new TargetTagUpdateEvent(save))); - return save; - } - - /** - * Find {@link DistributionSet} based on given name. - * - * @param name - * to look for. - * @return {@link DistributionSet} or null if it does not exist - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public DistributionSetTag findDistributionSetTag(@NotEmpty final String name) { - return distributionSetTagRepository.findByNameEquals(name); - } - - /** - * Creates a {@link DistributionSet}. - * - * @param distributionSetTag - * to be created. - * @return the new {@link DistributionSet} - * @throws EntityAlreadyExistsException - * if distributionSetTag already exists - * - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - public DistributionSetTag createDistributionSetTag(@NotNull final DistributionSetTag distributionSetTag) { - if (null != distributionSetTag.getId()) { - throw new EntityAlreadyExistsException(); - } - - if (distributionSetTagRepository.findByNameEquals(distributionSetTag.getName()) != null) { - throw new EntityAlreadyExistsException(); - } - - final DistributionSetTag save = distributionSetTagRepository.save(distributionSetTag); - - afterCommit.afterCommit( - () -> eventBus.post(new DistributionSetTagCreatedBulkEvent(tenantAware.getCurrentTenant(), save))); - return save; - } - - /** - * Creates multiple {@link DistributionSetTag}s. - * - * @param distributionSetTags - * to be created - * @return the new {@link DistributionSetTag} - * @throws EntityAlreadyExistsException - * if a given entity already exists - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - public List createDistributionSetTags( - @NotNull final Iterable distributionSetTags) { - for (final DistributionSetTag dsTag : distributionSetTags) { - if (dsTag.getId() != null) { - throw new EntityAlreadyExistsException(); - } - } - final List save = distributionSetTagRepository.save(distributionSetTags); - afterCommit.afterCommit( - () -> eventBus.post(new DistributionSetTagCreatedBulkEvent(tenantAware.getCurrentTenant(), save))); - - return save; - } - - /** - * Deletes {@link DistributionSetTag} by given - * {@link DistributionSetTag#getName()}. - * - * @param tagNames - * to be deleted - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) - public void deleteDistributionSetTag(@NotEmpty final String tagName) { - final DistributionSetTag tag = distributionSetTagRepository.findByNameEquals(tagName); - - final List changed = new LinkedList<>(); - for (final DistributionSet set : distributionSetRepository.findByTag(tag)) { - set.getTags().remove(tag); - changed.add(set); - } - - // save association delete - distributionSetRepository.save(changed); - - distributionSetTagRepository.deleteByName(tagName); - - afterCommit.afterCommit(() -> eventBus.post(new DistributionSetTagDeletedEvent(tag))); - } - - /** - * Updates an existing {@link DistributionSetTag}. - * - * @param distributionSetTag - * to be updated - * @return the updated {@link DistributionSet} - * @throws NullPointerException - * of {@link DistributionSetTag#getName()} is null - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public DistributionSetTag updateDistributionSetTag(@NotNull final DistributionSetTag distributionSetTag) { - checkNotNull(distributionSetTag.getName()); - checkNotNull(distributionSetTag.getId()); - final DistributionSetTag save = distributionSetTagRepository.save(distributionSetTag); - afterCommit.afterCommit(() -> eventBus.post(new DistributionSetTagUpdateEvent(save))); - - return save; - } - - /** - * returns all {@link DistributionTag}s. - * - * @return all {@link DistributionTag}s - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public List findAllDistributionSetTags() { - return distributionSetTagRepository.findAll(); - } - - /** - * Finds {@link TargetTag} by given id. - * - * @param id - * to search for - * @return the found {@link TargetTag}s or null if not found. - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public TargetTag findTargetTagById(@NotNull final Long id) { - return targetTagRepository.findOne(id); - } - - /** - * Finds {@link DistributionSetTag} by given id. - * - * @param id - * to search for - * @return the found {@link DistributionSetTag}s or null if not - * found. - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public DistributionSetTag findDistributionSetTagById(@NotNull final Long id) { - return distributionSetTagRepository.findOne(id); - } - - /** - * returns all {@link TargetTag}s. - * - * @param pageReq - * page parameter - * - * @return all {@link TargetTag}s - */ - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public Page findAllTargetTags(@NotNull final Pageable pageReq) { - return targetTagRepository.findAll(pageReq); - } - - /** - * returns all {@link DistributionSetTag}s. - * - * @param pageReq - * page parameter - * @return all {@link DistributionSetTag}s - */ - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public Page findAllDistributionSetTags(@NotNull final Pageable pageReq) { - return distributionSetTagRepository.findAll(pageReq); - } - - /** - * Retrieves all DistributionSet tags based on the given specification. - * - * @param spec - * the specification for the query - * @param pageable - * pagination parameter - * @return the found {@link DistributionSetTag}s, never {@code null} - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public Page findAllDistributionSetTags(@NotNull final Specification spec, - @NotNull final Pageable pageable) { - return distributionSetTagRepository.findAll(spec, pageable); - } - -} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagement.java deleted file mode 100644 index 270bb3048..000000000 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagement.java +++ /dev/null @@ -1,169 +0,0 @@ -/** - * 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.ArrayList; -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.model.TargetFilterQuery; -import org.eclipse.hawkbit.repository.specifications.SpecificationsBuilder; -import org.eclipse.hawkbit.repository.specifications.TargetFilterQuerySpecification; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.domain.Specification; -import org.springframework.data.jpa.domain.Specifications; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.transaction.annotation.Isolation; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.Assert; -import org.springframework.validation.annotation.Validated; - -import com.google.common.base.Strings; - -/** - * Business service facade for managing {@link TargetFilterQuery}s. - * - */ -@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) -@Validated -public class TargetFilterQueryManagement { - - @Autowired - private TargetFilterQueryRepository targetFilterQueryRepository; - - /** - * creating new {@link TargetFilterQuery}. - * - * @param customTargetFilter - * @return the created {@link TargetFilterQuery} - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET) - public TargetFilterQuery createTargetFilterQuery(@NotNull final TargetFilterQuery customTargetFilter) { - - if (targetFilterQueryRepository.findByName(customTargetFilter.getName()) != null) { - throw new EntityAlreadyExistsException(customTargetFilter.getName()); - } - return targetFilterQueryRepository.save(customTargetFilter); - } - - /** - * Delete target filter query. - * - * @param targetFilterQueryId - * IDs of target filter query to be deleted - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_TARGET) - public void deleteTargetFilterQuery(@NotNull final Long targetFilterQueryId) { - targetFilterQueryRepository.delete(targetFilterQueryId); - } - - /** - * - * Retrieves all target filter query{@link TargetFilterQuery}. - * - * @param pageable - * pagination parameter - * @return the found {@link TargetFilterQuery}s - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public Page findAllTargetFilterQuery(@NotNull final Pageable pageable) { - return targetFilterQueryRepository.findAll(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) - public Page findTargetFilterQueryByFilters(@NotNull final Pageable pageable, final String name) { - final List> specList = new ArrayList<>(); - if (!Strings.isNullOrEmpty(name)) { - specList.add(TargetFilterQuerySpecification.likeName(name)); - } - return findTargetFilterQueryByCriteriaAPI(pageable, specList); - } - - /** - * - * @param pageable - * pagination parameter - * @param specList - * list of @link {@link Specification} - * @return the page with the found {@link TargetFilterQuery} - */ - private Page findTargetFilterQueryByCriteriaAPI(@NotNull final Pageable pageable, - final List> specList) { - if (specList == null || specList.isEmpty()) { - return targetFilterQueryRepository.findAll(pageable); - } - - final Specifications specs = SpecificationsBuilder.combineWithAnd(specList); - return targetFilterQueryRepository.findAll(specs, pageable); - } - - /** - * Find target filter query by name. - * - * @param targetFilterQueryName - * Target filter query name - * @return the found {@link TargetFilterQuery} - * - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public TargetFilterQuery findTargetFilterQueryByName(@NotNull final String targetFilterQueryName) { - return targetFilterQueryRepository.findByName(targetFilterQueryName); - } - - /** - * Find target filter query by id. - * - * @param targetFilterQueryId - * Target filter query id - * @return the found {@link TargetFilterQuery} - * - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public TargetFilterQuery findTargetFilterQueryById(@NotNull final Long targetFilterQueryId) { - return targetFilterQueryRepository.findOne(targetFilterQueryId); - } - - /** - * updates the {@link TargetFilterQuery}. - * - * @param targetFilterQuery - * to be updated - * @return the updated {@link TargetFilterQuery} - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) - public TargetFilterQuery updateTargetFilterQuery(@NotNull final TargetFilterQuery targetFilterQuery) { - Assert.notNull(targetFilterQuery.getId()); - return targetFilterQueryRepository.save(targetFilterQuery); - } - -} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetManagement.java deleted file mode 100644 index 6e96ebf6b..000000000 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetManagement.java +++ /dev/null @@ -1,1108 +0,0 @@ -/** - * 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.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -import javax.annotation.PreDestroy; -import javax.persistence.Entity; -import javax.persistence.EntityManager; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Expression; -import javax.persistence.criteria.Join; -import javax.persistence.criteria.JoinType; -import javax.persistence.criteria.Order; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; -import javax.validation.constraints.NotNull; - -import org.eclipse.hawkbit.Constants; -import org.eclipse.hawkbit.eventbus.event.TargetTagAssigmentResultEvent; -import org.eclipse.hawkbit.executor.AfterTransactionCommitExecutor; -import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; -import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; -import org.eclipse.hawkbit.repository.model.DistributionSet; -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.TargetInfo_; -import org.eclipse.hawkbit.repository.model.TargetTag; -import org.eclipse.hawkbit.repository.model.TargetTagAssignmentResult; -import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; -import org.eclipse.hawkbit.repository.model.Target_; -import org.eclipse.hawkbit.repository.rsql.RSQLUtility; -import org.eclipse.hawkbit.repository.specifications.SpecificationsBuilder; -import org.eclipse.hawkbit.repository.specifications.TargetSpecifications; -import org.hibernate.validator.constraints.NotEmpty; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.annotation.CacheEvict; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Slice; -import org.springframework.data.domain.SliceImpl; -import org.springframework.data.domain.Sort; -import org.springframework.data.domain.Sort.Direction; -import org.springframework.data.jpa.domain.Specification; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.transaction.annotation.Isolation; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.Assert; -import org.springframework.validation.annotation.Validated; - -import com.google.common.base.Strings; -import com.google.common.collect.Lists; -import com.google.common.eventbus.EventBus; - -/** - * Business service facade for managing {@link Target}s. - * - */ -@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) -@Validated -public class TargetManagement { - - @Autowired - private EntityManager entityManager; - - @Autowired - private TargetRepository targetRepository; - - @Autowired - private TargetTagRepository targetTagRepository; - - @Autowired - private TargetInfoRepository targetInfoRepository; - - @Autowired - private NoCountPagingRepository criteriaNoCountDao; - - @Autowired - private EventBus eventBus; - - @Autowired - private AfterTransactionCommitExecutor afterCommit; - - /** - * Find {@link Target} based on given ID returns found Target without - * details, i.e. NO {@link Target#getTags()} and - * {@link Target#getActiveActions()} possible. - * - * @param controllerId - * to look for. - * @return {@link Target} or null if it does not exist - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public Target findTargetByControllerID(@NotEmpty final String controllerId) { - return targetRepository.findByControllerId(controllerId); - } - - /** - * Find {@link Target} based on given ID returns found Target with details, - * i.e. {@link Target#getTags()} and {@link Target#getActiveActions()} are - * possible. - * - * Note: try to use {@link #findTargetByControllerID(String)} as much as - * possible. - * - * @param controllerId - * to look for. - * @return {@link Target} or null if it does not exist - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public Target findTargetByControllerIDWithDetails(@NotEmpty final String controllerId) { - final Target result = targetRepository.findByControllerId(controllerId); - // load lazy relations - if (result != null) { - result.getTargetInfo().getControllerAttributes().size(); - if (result.getTargetInfo() != null && result.getTargetInfo().getInstalledDistributionSet() != null) { - result.getTargetInfo().getInstalledDistributionSet().getName(); - result.getTargetInfo().getInstalledDistributionSet().getModules().size(); - } - if (result.getAssignedDistributionSet() != null) { - result.getAssignedDistributionSet().getName(); - result.getAssignedDistributionSet().getModules().size(); - } - } - return result; - } - - /** - * Find {@link Target} based on given ID returns found Target without - * details, i.e. NO {@link Target#getTags()} and - * {@link Target#getActiveActions()} possible. - * - * @param controllerIDs - * to look for. - * @return List of found{@link Target}s - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public List findTargetByControllerID(@NotEmpty final Collection controllerIDs) { - return targetRepository.findAll(TargetSpecifications.byControllerIdWithStatusAndAssignedInJoin(controllerIDs)); - } - - /** - * Counts all {@link Target}s in the repository. - * - * @return number of targets - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public Long countTargetsAll() { - return targetRepository.count(); - } - - /** - * Retrieves all targets without details, i.e. NO {@link Target#getTags()} - * and {@link Target#getActiveActions()} possible - * - * @param pageable - * pagination parameter - * @return the found {@link Target}s - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public Slice findTargetsAll(@NotNull final Pageable pageable) { - // workarround - no join fetch allowed that is why we need specification - // instead of query for - // count() of Pageable - final Specification spec = (root, query, cb) -> { - if (!query.getResultType().isAssignableFrom(Long.class)) { - root.fetch(Target_.targetInfo); - } - return cb.conjunction(); - }; - return criteriaNoCountDao.findAll(spec, pageable, Target.class); - } - - /** - * Retrieves all targets without details, i.e. NO {@link Target#getTags()} - * and {@link Target#getActiveActions()} possible based on - * {@link TargetFilterQuery#getQuery()} - * - * @param targetFilterQuery - * @param pageable - * @return - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public Slice findTargetsAll(@NotNull final TargetFilterQuery targetFilterQuery, - @NotNull final Pageable pageable) { - return findTargetsAll(RSQLUtility.parse(targetFilterQuery.getQuery(), TargetFields.class), pageable); - } - - /** - * Retrieves all targets without details, i.e. NO {@link Target#getTags()} - * and {@link Target#getActiveActions()} possible based on - * {@link TargetFilterQuery#getQuery()} - * - * @param targetFilterQuery - * @param pageable - * @return - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public Slice findTargetsAll(@NotNull final String targetFilterQuery, @NotNull final Pageable pageable) { - return findTargetsAll(RSQLUtility.parse(targetFilterQuery, TargetFields.class), pageable); - } - - /** - * Retrieves all targets based on the given specification. - * - * @param spec - * the specification for the query - * @param pageable - * pagination parameter - * @return the found {@link Target}s, never {@code null} - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public Page findTargetsAll(@NotNull final Specification spec, @NotNull final Pageable pageable) { - return targetRepository.findAll(spec, pageable); - } - - /** - * 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) - public List findTargetsByControllerIDsWithTags(@NotNull final List controllerIDs) { - final List> partition = Lists.partition(controllerIDs, Constants.MAX_ENTRIES_IN_STATEMENT); - return partition.stream() - .map(ids -> targetRepository.findAll(TargetSpecifications.byControllerIdWithStatusAndTagsInJoin(ids))) - .flatMap(t -> t.stream()).collect(Collectors.toList()); - } - - /** - * updates the {@link Target}. - * - * @param target - * to be updated - * @return the updated {@link Target} - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET + SpringEvalExpressions.HAS_AUTH_OR - + SpringEvalExpressions.IS_CONTROLLER) - public Target updateTarget(@NotNull final Target target) { - Assert.notNull(target.getId()); - target.setNew(false); - return targetRepository.save(target); - } - - /** - * updates multiple {@link Target}s. - * - * @param targets - * to be updated - * @return the updated {@link Target}s - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET + SpringEvalExpressions.HAS_AUTH_OR - + SpringEvalExpressions.IS_CONTROLLER) - public List updateTargets(@NotNull final List targets) { - targets.forEach(target -> target.setNew(false)); - return targetRepository.save(targets); - } - - /** - * Deletes all targets with the given IDs. - * - * @param targetIDs - * the technical IDs of the targets to be deleted - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_TARGET) - public void deleteTargets(@NotEmpty final Long... targetIDs) { - // we need to select the target IDs first to check the if the targetIDs - // belonging to the - // tenant! Delete statement are not automatically enhanced with the - // @FilterDef of the - // hibernate session. - final List targetsForCurrentTenant = targetRepository.findAll(Lists.newArrayList(targetIDs)).stream() - .map(Target::getId).collect(Collectors.toList()); - if (!targetsForCurrentTenant.isEmpty()) { - targetInfoRepository.deleteByTargetIdIn(targetsForCurrentTenant); - targetRepository.deleteByIdIn(targetsForCurrentTenant); - } - } - - /** - * retrieves {@link Target}s by the assigned {@link DistributionSet} without - * details, i.e. NO {@link Target#getTags()} and - * {@link Target#getActiveActions()} possible. - * - * - * @param distributionSetID - * the ID of the {@link DistributionSet} - * @param pageReq - * page parameter - * @return the found {@link Target}s - */ - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_READ_TARGET) - public Page findTargetByAssignedDistributionSet(@NotNull final Long distributionSetID, - @NotNull final Pageable pageReq) { - return targetRepository.findByAssignedDistributionSetId(pageReq, distributionSetID); - } - - /** - * Retrieves {@link Target}s by the assigned {@link DistributionSet} without - * details, i.e. NO {@link Target#getTags()} and - * {@link Target#getActiveActions()} possible including additional filtering - * based on the given {@code spec}. - * - * @param distributionSetID - * the ID of the {@link DistributionSet} - * @param spec - * the specification to filter the result set - * @param pageReq - * page parameter - * @return the found {@link Target}s, never {@code null} - */ - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_READ_TARGET) - public Page findTargetByAssignedDistributionSet(@NotNull final Long distributionSetID, - final Specification spec, @NotNull final Pageable pageReq) { - return targetRepository.findAll((Specification) (root, query, cb) -> cb.and( - TargetSpecifications.hasAssignedDistributionSet(distributionSetID).toPredicate(root, query, cb), - spec.toPredicate(root, query, cb)), pageReq); - } - - /** - * retrieves {@link Target}s by the installed {@link DistributionSet}without - * details, i.e. NO {@link Target#getTags()} and - * {@link Target#getActiveActions()} possible. - * - * @param distributionSetID - * the ID of the {@link DistributionSet} - * @param pageReq - * page parameter - * @return the found {@link Target}s - */ - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_READ_TARGET) - public Page findTargetByInstalledDistributionSet(@NotNull final Long distributionSetID, - @NotNull final Pageable pageReq) { - return targetRepository.findByTargetInfoInstalledDistributionSetId(pageReq, distributionSetID); - } - - /** - * retrieves {@link Target}s by the installed {@link DistributionSet}without - * details, i.e. NO {@link Target#getTags()} and - * {@link Target#getActiveActions()} possible including additional filtering - * based on the given {@code spec}. - * - * @param distributionSetId - * the ID of the {@link DistributionSet} - * @param spec - * the specification to filter the result - * @param pageable - * page parameter - * @return the found {@link Target}s, never {@code null} - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_READ_TARGET) - public Page findTargetByInstalledDistributionSet(final Long distributionSetId, - final Specification spec, final Pageable pageable) { - return targetRepository.findAll((Specification) (root, query, cb) -> cb.and( - TargetSpecifications.hasInstalledDistributionSet(distributionSetId).toPredicate(root, query, cb), - spec.toPredicate(root, query, cb)), pageable); - } - - /** - * Retrieves the {@link Target} which have a certain - * {@link TargetUpdateStatus} without details, i.e. NO - * {@link Target#getTags()} and {@link Target#getActiveActions()} possible. - * - * @param pageable - * page parameter - * @param status - * the {@link TargetUpdateStatus} to be filtered on - * @return the found {@link Target}s - */ - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public Page findTargetByUpdateStatus(@NotNull final Pageable pageable, - @NotNull final TargetUpdateStatus status) { - return targetRepository.findByTargetInfoUpdateStatus(pageable, status); - } - - /** - * 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 - * null in case this is not required. - * @param searchText - * to find targets having the text anywhere in name or - * description. Set null in case this is not - * required. - * @param installedOrAssignedDistributionSetId - * to find targets having the {@link DistributionSet} as - * installed or assigned. Set to null in case this - * is not required. - * @param tagNames - * to find targets which are having any one in this tag names. - * Set null 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) - public Slice findTargetByFilters(@NotNull final Pageable pageable, - final Collection status, final String searchText, - final Long installedOrAssignedDistributionSetId, final Boolean selectTargetWithNoTag, - final String... tagNames) { - final List> specList = buildSpecificationList(status, searchText, - installedOrAssignedDistributionSetId, selectTargetWithNoTag, true, tagNames); - return findByCriteriaAPI(pageable, specList); - } - - /** - * Count {@link Target}s for all the given filter parameters. - * - * @param status - * find targets having on of these {@link TargetUpdateStatus}s. - * Set to null in case this is not required. - * @param searchText - * to find targets having the text anywhere in name or - * description. Set null in case this is not - * required. - * @param installedOrAssignedDistributionSetId - * to find targets having the {@link DistributionSet} as - * installed or assigned. Set to null in case this - * is not required. - * @param tagNames - * to find targets which are having any one in this tag names. - * Set null 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) - public Long countTargetByFilters(final Collection status, final String searchText, - final Long installedOrAssignedDistributionSetId, final Boolean selectTargetWithNoTag, - final String... tagNames) { - final List> specList = buildSpecificationList(status, searchText, - installedOrAssignedDistributionSetId, selectTargetWithNoTag, true, tagNames); - return countByCriteriaAPI(specList); - } - - private static List> buildSpecificationList(final Collection status, - final String searchText, final Long installedOrAssignedDistributionSetId, - final Boolean selectTargetWithNoTag, final boolean fetch, final String... tagNames) { - final List> specList = new ArrayList<>(); - if (status != null && !status.isEmpty()) { - specList.add(TargetSpecifications.hasTargetUpdateStatus(status, fetch)); - } - if (installedOrAssignedDistributionSetId != null) { - specList.add( - TargetSpecifications.hasInstalledOrAssignedDistributionSet(installedOrAssignedDistributionSetId)); - } - if (!Strings.isNullOrEmpty(searchText)) { - specList.add(TargetSpecifications.likeNameOrDescriptionOrIp(searchText)); - } - if (selectTargetWithNoTag != null && (selectTargetWithNoTag || (tagNames != null && tagNames.length > 0))) { - specList.add(TargetSpecifications.hasTags(tagNames, selectTargetWithNoTag)); - } - return specList; - } - - /** - * executes findAll with the given {@link Target} {@link Specification}s. - * - * @param pageable - * paging parameter - * @param specList - * list of @link {@link Specification} - * @return the page with the found {@link Target} - */ - private Slice findByCriteriaAPI(final Pageable pageable, final List> specList) { - if (specList == null || specList.isEmpty()) { - return criteriaNoCountDao.findAll(pageable, Target.class); - } - return criteriaNoCountDao.findAll(SpecificationsBuilder.combineWithAnd(specList), pageable, Target.class); - } - - private Long countByCriteriaAPI(final List> specList) { - if (specList == null || specList.isEmpty()) { - return targetRepository.count(); - } - - return targetRepository.count(SpecificationsBuilder.combineWithAnd(specList)); - } - - /** - * {@link Entity} based method call for - * {@link #toggleTagAssignment(Collection, String)}. - * - * @param targets - * to toggle for - * @param tag - * to toggle - * @return TagAssigmentResult with all metadata of the assignment outcome. - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) - public TargetTagAssignmentResult toggleTagAssignment(@NotEmpty final List targets, - @NotNull final TargetTag tag) { - return toggleTagAssignment( - targets.stream().map(target -> target.getControllerId()).collect(Collectors.toList()), tag.getName()); - } - - /** - * 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 toogle - * @return TagAssigmentResult with all metadata of the assigment outcome. - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) - public TargetTagAssignmentResult toggleTagAssignment(@NotEmpty final Collection targetIds, - @NotNull final String tagName) { - final TargetTag tag = targetTagRepository.findByNameEquals(tagName); - final List alreadyAssignedTargets = targetRepository.findByTagNameAndControllerIdIn(tagName, targetIds); - final List allTargets = targetRepository - .findAll(TargetSpecifications.byControllerIdWithStatusAndTagsInJoin(targetIds)); - - // all are already assigned -> unassign - if (alreadyAssignedTargets.size() == allTargets.size()) { - alreadyAssignedTargets.forEach(target -> target.getTags().remove(tag)); - final TargetTagAssignmentResult result = new TargetTagAssignmentResult(0, 0, alreadyAssignedTargets.size(), - Collections.emptyList(), alreadyAssignedTargets, tag); - - afterCommit.afterCommit(() -> eventBus.post(new TargetTagAssigmentResultEvent(result))); - return result; - } - - allTargets.removeAll(alreadyAssignedTargets); - // some or none are assigned -> assign - allTargets.forEach(target -> target.getTags().add(tag)); - final TargetTagAssignmentResult result = new TargetTagAssignmentResult(alreadyAssignedTargets.size(), - allTargets.size(), 0, targetRepository.save(allTargets), Collections.emptyList(), tag); - - afterCommit.afterCommit(() -> eventBus.post(new TargetTagAssigmentResultEvent(result))); - - // no reason to persist the tag - entityManager.detach(tag); - return result; - } - - /** - * Assign a {@link TargetTag} assignment to given {@link Target}s. - * - * @param targetIds - * to assign for - * @param tagName - * to assign - * @return list of assigned targets - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) - public List assignTag(@NotEmpty final Collection targetIds, @NotNull final TargetTag tag) { - final List allTargets = targetRepository - .findAll(TargetSpecifications.byControllerIdWithStatusAndTagsInJoin(targetIds)); - - allTargets.forEach(target -> target.getTags().add(tag)); - final List save = targetRepository.save(allTargets); - - afterCommit.afterCommit(() -> { - final TargetTagAssignmentResult assigmentResult = new TargetTagAssignmentResult(0, save.size(), 0, save, - Collections.emptyList(), tag); - eventBus.post(new TargetTagAssigmentResultEvent(assigmentResult)); - }); - - return save; - } - - private List unAssignTag(@NotEmpty final Collection targets, @NotNull final TargetTag tag) { - targets.forEach(target -> target.getTags().remove(tag)); - - final List save = targetRepository.save(targets); - afterCommit.afterCommit(() -> { - final TargetTagAssignmentResult assigmentResult = new TargetTagAssignmentResult(0, 0, save.size(), - Collections.emptyList(), save, tag); - eventBus.post(new TargetTagAssigmentResultEvent(assigmentResult)); - }); - return save; - } - - /** - * Unassign all {@link Target} from a given {@link TargetTag} . - * - * @param tag - * to unassign all targets - * @return list of unassigned targets - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) - public List unAssignAllTargetsByTag(@NotNull final TargetTag tag) { - return unAssignTag(tag.getAssignedToTargets(), tag); - } - - /** - * Unassign a {@link TargetTag} assignment to given {@link Target}. - * - * @param controllerID - * to unassign for - * @param targetTag - * to unassign - * @return the unassigned target or if no target is unassigned - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) - public Target unAssignTag(@NotNull final String controllerID, @NotNull final TargetTag targetTag) { - final List allTargets = targetRepository - .findAll(TargetSpecifications.byControllerIdWithStatusAndTagsInJoin(Arrays.asList(controllerID))); - final List unAssignTag = unAssignTag(allTargets, targetTag); - return unAssignTag.isEmpty() ? null : unAssignTag.get(0); - } - - /** - * method retrieves all {@link Target}s from the repo in the following - * order: - *

- * 1) {@link Target}s which have the given {@link DistributionSet} as - * {@link Target#getTargetStatus()} - * {@link TargetStatus#getInstalledDistributionSet()} - *

- * 2) {@link Target}s which have the given {@link DistributionSet} as - * {@link Target#getAssignedDistributionSet()} - *

- * 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 null in case this is not required. - * @param filterByStatus - * find targets having this {@link TargetUpdateStatus}s. Set to - * null in case this is not required. - * @param filterBySearchText - * to find targets having the text anywhere in name or - * description. Set null in case this is not - * required. - * @param installedOrAssignedDistributionSetId - * to find targets having the {@link DistributionSet} as - * installed or assigned. Set to null in case this - * is not required. - * @param filterByTagNames - * to find targets which are having any one in this tag names. - * Set null 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) - public Slice findTargetsAllOrderByLinkedDistributionSet(@NotNull final Pageable pageable, - @NotNull final Long orderByDistributionId, final Long filterByDistributionId, - final Collection filterByStatus, final String filterBySearchText, - final Boolean selectTargetWithNoTag, final String... filterByTagNames) { - final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); - final CriteriaQuery query = cb.createQuery(Target.class); - final Root targetRoot = query.from(Target.class); - - // necessary joins for the select - final Join targetInfo = (Join) targetRoot.fetch(Target_.targetInfo, - JoinType.LEFT); - - // select case expression to retrieve the case value as a column to be - // able to order based on - // this column, installed first,... - final Expression selectCase = cb.selectCase() - .when(cb.equal(targetInfo.get(TargetInfo_.installedDistributionSet).get(DistributionSet_.id), - orderByDistributionId), 1) - .when(cb.equal(targetRoot.get(Target_.assignedDistributionSet).get(DistributionSet_.id), - orderByDistributionId), 2) - .otherwise(100); - // multiselect statement order by the select case and controllerId - query.distinct(true); - // build the specifications and then to predicates necessary by the - // given filters - final Predicate[] specificationsForMultiSelect = specificationsToPredicate( - buildSpecificationList(filterByStatus, filterBySearchText, filterByDistributionId, - selectTargetWithNoTag, true, filterByTagNames), - targetRoot, query, cb); - - // if we have some predicates then add it to the where clause of the - // multiselect - if (specificationsForMultiSelect.length > 0) { - query.where(specificationsForMultiSelect); - } - // add the order to the multi select first based on the selectCase - query.orderBy(cb.asc(selectCase), cb.desc(targetRoot.get(Target_.id))); - // the result is a Object[] due the fact that the selectCase is an extra - // column, so it cannot - // be mapped directly to a Target entity because the selectCase is not a - // attribute of the - // Target entity, the the Object array contains the Target on the first - // index (case of the - // multiselect order) of the array and - // the 2nd contains the selectCase int value. - final int pageSize = pageable.getPageSize(); - final List resultList = entityManager.createQuery(query).setFirstResult(pageable.getOffset()) - .setMaxResults(pageSize + 1).getResultList(); - final boolean hasNext = resultList.size() > pageSize; - return new SliceImpl<>(resultList, pageable, hasNext); - } - - /** - * @param specifications - */ - private static Predicate[] specificationsToPredicate(final List> specifications, - final Root root, final CriteriaQuery query, final CriteriaBuilder cb) { - final Predicate[] predicates = new Predicate[specifications.size()]; - for (int index = 0; index < predicates.length; index++) { - predicates[index] = specifications.get(index).toPredicate(root, query, cb); - } - return predicates; - } - - /** - * 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) - public Long countTargetByAssignedDistributionSet(final Long distId) { - return targetRepository.countByAssignedDistributionSetId(distId); - } - - /** - * Counts number of targets with given - * {@link TargetStatus#getInstalledDistributionSet()}. - * - * @param distId - * to search for - * @return number of found {@link Target}s. - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public Long countTargetByInstalledDistributionSet(final Long distId) { - return targetRepository.countByTargetInfoInstalledDistributionSetId(distId); - } - - /** - * 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) - public List findAllTargetIds() { - final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); - final CriteriaQuery query = cb.createQuery(TargetIdName.class); - final Root targetRoot = query.from(Target.class); - return entityManager.createQuery(query.multiselect(targetRoot.get(Target_.id), - targetRoot.get(Target_.controllerId), targetRoot.get(Target_.name))).getResultList(); - - } - - /** - * 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 - * null in case this is not required. - * @param filterBySearchText - * to find targets having the text anywhere in name or - * description. Set null in case this is not - * required. - * @param installedOrAssignedDistributionSetId - * to find targets having the {@link DistributionSet} as - * installed or assigned. Set to null in case this - * is not required. - * @param filterByTagNames - * to find targets which are having any one in this tag names. - * Set null 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) - public List findAllTargetIdsByFilters(@NotNull final Pageable pageRequest, - final Collection filterByStatus, final String filterBySearchText, - final Long installedOrAssignedDistributionSetId, final Boolean selectTargetWithNoTag, - final String... filterByTagNames) { - final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); - final CriteriaQuery query = cb.createQuery(Object[].class); - final Root targetRoot = query.from(Target.class); - List resultList; - - String sortProperty = Target_.id.getName(); - if (pageRequest.getSort() != null && pageRequest.getSort().iterator().hasNext()) { - sortProperty = pageRequest.getSort().iterator().next().getProperty(); - } - - final CriteriaQuery multiselect = query.multiselect(targetRoot.get(Target_.id), - targetRoot.get(Target_.controllerId), targetRoot.get(Target_.name), targetRoot.get(sortProperty)); - - final Predicate[] specificationsForMultiSelect = specificationsToPredicate( - buildSpecificationList(filterByStatus, filterBySearchText, installedOrAssignedDistributionSetId, - selectTargetWithNoTag, false, filterByTagNames), - targetRoot, multiselect, cb); - - // if we have some predicates then add it to the where clause of the - // multiselect - if (specificationsForMultiSelect.length > 0) { - multiselect.where(specificationsForMultiSelect); - } - - resultList = getTargetIdNameResultSet(pageRequest, cb, targetRoot, multiselect); - return resultList.parallelStream().map(o -> new TargetIdName((long) o[0], o[1].toString(), o[2].toString())) - .collect(Collectors.toList()); - } - - /** - * 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) - public List findAllTargetIdsByTargetFilterQuery(final Pageable pageRequest, - @NotNull final TargetFilterQuery targetFilterQuery) { - final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); - final CriteriaQuery query = cb.createQuery(Object[].class); - final Root targetRoot = query.from(Target.class); - - String sortProperty = Target_.id.getName(); - if (pageRequest.getSort() != null && pageRequest.getSort().iterator().hasNext()) { - sortProperty = pageRequest.getSort().iterator().next().getProperty(); - } - - final CriteriaQuery multiselect = query.multiselect(targetRoot.get(Target_.id), - targetRoot.get(Target_.controllerId), targetRoot.get(Target_.name), targetRoot.get(sortProperty)); - - final Specification spec = RSQLUtility.parse(targetFilterQuery.getQuery(), TargetFields.class); - final List> specList = new ArrayList<>(); - specList.add(spec); - - final Predicate[] specificationsForMultiSelect = specificationsToPredicate(specList, targetRoot, multiselect, - cb); - - // if we have some predicates then add it to the where clause of the - // multiselect - if (specificationsForMultiSelect.length > 0) { - multiselect.where(specificationsForMultiSelect); - } - final List resultList = getTargetIdNameResultSet(pageRequest, cb, targetRoot, multiselect); - return resultList.parallelStream().map(o -> new TargetIdName((long) o[0], o[1].toString(), o[2].toString())) - .collect(Collectors.toList()); - } - - @PreDestroy - void destroy() { - eventBus.unregister(this); - } - - /** - * 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 - * - * @return - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET + SpringEvalExpressions.HAS_AUTH_OR - + SpringEvalExpressions.IS_CONTROLLER) - @CacheEvict(value = { "targetsCreatedOverPeriod" }, allEntries = true) - public Target createTarget(@NotNull final Target target, @NotNull final TargetUpdateStatus status, - final Long lastTargetQuery, final URI address) { - - if (targetRepository.findByControllerId(target.getControllerId()) != null) { - throw new EntityAlreadyExistsException(target.getControllerId()); - } - - target.setNew(true); - final Target savedTarget = targetRepository.save(target); - final TargetInfo targetInfo = savedTarget.getTargetInfo(); - targetInfo.setUpdateStatus(status); - if (lastTargetQuery != null) { - targetInfo.setLastTargetQuery(lastTargetQuery); - } - if (address != null) { - targetInfo.setAddress(address.toString()); - } - targetInfo.setNew(true); - final Target targetToReturn = targetInfoRepository.save(targetInfo).getTarget(); - targetInfo.setNew(false); - return targetToReturn; - - } - - /** - * creating a new {@link Target}. - * - * @param target - * to be created - * @return the created {@link Target} - * - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET + SpringEvalExpressions.HAS_AUTH_OR - + SpringEvalExpressions.IS_CONTROLLER) - @CacheEvict(value = { "targetsCreatedOverPeriod" }, allEntries = true) - public Target createTarget(@NotNull final Target target) { - return createTarget(target, TargetUpdateStatus.UNKNOWN, null, null); - } - - /** - * 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 {@link - * EntityAlreadyExistsException} of one of the given targets - * already exist. - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET) - public List createTargets(@NotNull final List targets) { - if (!targets.isEmpty() && targetRepository.countByControllerIdIn( - targets.stream().map(target -> target.getControllerId()).collect(Collectors.toList())) > 0) { - throw new EntityAlreadyExistsException(); - } - final List savedTargets = new ArrayList<>(); - for (final Target t : targets) { - final Target myTarget = createTarget(t); - savedTargets.add(myTarget); - } - return savedTargets; - } - - /** - * 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 - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET) - public List createTargets(@NotNull final Collection targets, - @NotNull final TargetUpdateStatus status, final long lastTargetQuery, final URI address) { - if (targetRepository.countByControllerIdIn( - targets.stream().map(target -> target.getControllerId()).collect(Collectors.toList())) > 0) { - throw new EntityAlreadyExistsException(); - } - final List savedTargets = new ArrayList<>(); - for (final Target t : targets) { - final Target myTarget = createTarget(t, status, lastTargetQuery, address); - savedTargets.add(myTarget); - } - return savedTargets; - } - - /** - * Find targets by tag name. - * - * @param tagName - * tag name - * @return list of matching targets - */ - @NotNull - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public List findTargetsByTag(@NotNull final String tagName) { - final TargetTag tag = targetTagRepository.findByNameEquals(tagName); - return targetRepository.findByTag(tag); - } - - /** - * 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) - public Long countTargetByTargetFilterQuery(@NotNull final TargetFilterQuery targetFilterQuery) { - final Specification specs = RSQLUtility.parse(targetFilterQuery.getQuery(), TargetFields.class); - return targetRepository.count(specs); - } - - /** - * 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) - public Long countTargetByTargetFilterQuery(@NotNull final String targetFilterQuery) { - final Specification specs = RSQLUtility.parse(targetFilterQuery, TargetFields.class); - return targetRepository.count(specs); - } - - private List getTargetIdNameResultSet(final Pageable pageRequest, final CriteriaBuilder cb, - final Root targetRoot, final CriteriaQuery multiselect) { - List resultList; - if (pageRequest.getSort() != null) { - final List orders = new ArrayList<>(); - final Sort sort = pageRequest.getSort(); - for (final Sort.Order sortOrder : sort) { - if (sortOrder.getDirection() == Direction.ASC) { - orders.add(cb.asc(targetRoot.get(sortOrder.getProperty()))); - } else { - orders.add(cb.desc(targetRoot.get(sortOrder.getProperty()))); - } - } - multiselect.orderBy(orders); - resultList = entityManager.createQuery(multiselect).setFirstResult(pageRequest.getOffset()) - .setMaxResults(pageRequest.getPageSize()).getResultList(); - } else { - resultList = entityManager.createQuery(multiselect).getResultList(); - } - return resultList; - } -} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantConfigurationManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantConfigurationManagement.java deleted file mode 100644 index f8ee6ae8b..000000000 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantConfigurationManagement.java +++ /dev/null @@ -1,269 +0,0 @@ -/** - * 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.beans.factory.annotation.Autowired; -import org.springframework.cache.annotation.CacheEvict; -import org.springframework.cache.annotation.Cacheable; -import org.springframework.context.ApplicationContext; -import org.springframework.context.EnvironmentAware; -import org.springframework.core.convert.ConversionFailedException; -import org.springframework.core.convert.support.ConfigurableConversionService; -import org.springframework.core.convert.support.DefaultConversionService; -import org.springframework.core.env.Environment; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.transaction.annotation.Isolation; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.validation.annotation.Validated; - -/** - * Central tenant configuration management operations of the SP server. - */ -@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) -@Validated -public class TenantConfigurationManagement implements EnvironmentAware { - - @Autowired - private TenantConfigurationRepository tenantConfigurationRepository; - - @Autowired - private ApplicationContext applicationContext; - - private final ConfigurableConversionService conversionService = new DefaultConversionService(); - - private Environment environment; - - /** - * 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 - * 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} - */ - - @Cacheable(value = "tenantConfiguration", key = "#configurationKey.getKeyName()") - @PreAuthorize(value = SpringEvalExpressions.HAS_AUTH_TENANT_CONFIGURATION + SpringEvalExpressions.HAS_AUTH_OR - + SpringEvalExpressions.IS_SYSTEM_CODE) - public TenantConfigurationValue getConfigurationValue(final TenantConfigurationKey configurationKey, - final Class propertyType) { - validateTenantConfigurationDataType(configurationKey, propertyType); - - final TenantConfiguration tenantConfiguration = tenantConfigurationRepository - .findByKey(configurationKey.getKeyName()); - - return buildTenantConfigurationValueByKey(configurationKey, propertyType, tenantConfiguration); - } - - /** - * Validates the data type of the tenant configuration. If it is possible to - * cast to the given data type. - * - * @param configurationKey - * the key - * @param propertyType - * the class - */ - protected void validateTenantConfigurationDataType(final TenantConfigurationKey configurationKey, - final Class propertyType) { - if (!configurationKey.getDataType().isAssignableFrom(propertyType)) { - throw new TenantConfigurationValidatorException( - String.format("Cannot parse the database value of type %s into the type %s.", - configurationKey.getDataType(), propertyType)); - } - } - - /** - * Build the tenant configuration by the given key - * - * @param configurationKey - * the key - * @param propertyType - * the property type - * @param tenantConfiguration - * the configuration - * @return if no default value is set and no database value available - * or returns the tenant configuration value - */ - protected TenantConfigurationValue buildTenantConfigurationValueByKey( - final TenantConfigurationKey configurationKey, final Class propertyType, - final TenantConfiguration tenantConfiguration) { - if (tenantConfiguration != null) { - return TenantConfigurationValue. builder().isGlobal(false).createdBy(tenantConfiguration.getCreatedBy()) - .createdAt(tenantConfiguration.getCreatedAt()) - .lastModifiedAt(tenantConfiguration.getLastModifiedAt()) - .lastModifiedBy(tenantConfiguration.getLastModifiedBy()) - .value(conversionService.convert(tenantConfiguration.getValue(), propertyType)).build(); - - } else if (configurationKey.getDefaultKeyName() != null) { - - return TenantConfigurationValue. builder().isGlobal(true).createdBy(null).createdAt(null) - .lastModifiedAt(null).lastModifiedBy(null) - .value(getGlobalConfigurationValue(configurationKey, propertyType)).build(); - } - return null; - } - - /** - * 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) - public TenantConfigurationValue getConfigurationValue(final TenantConfigurationKey configurationKey) { - return getConfigurationValue(configurationKey, configurationKey.getDataType()); - } - - /** - * returns the global configuration property either defined in the property - * file or an default value otherwise. - * - * @param - * 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) - public T getGlobalConfigurationValue(final TenantConfigurationKey configurationKey, - final Class propertyType) { - - if (!configurationKey.getDataType().isAssignableFrom(propertyType)) { - throw new TenantConfigurationValidatorException( - String.format("Cannot parse the database value of type %s into the type %s.", - configurationKey.getDataType(), propertyType)); - } - - final T valueInProperties = environment.getProperty(configurationKey.getDefaultKeyName(), propertyType); - - if (valueInProperties == null) { - return conversionService.convert(configurationKey.getDefaultValue(), propertyType); - } - - return valueInProperties; - } - - /** - * 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 - */ - @CacheEvict(value = "tenantConfiguration", key = "#configurationKey.getKeyName()") - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @Modifying - @PreAuthorize(value = SpringEvalExpressions.HAS_AUTH_TENANT_CONFIGURATION) - public TenantConfigurationValue addOrUpdateConfiguration(final TenantConfigurationKey configurationKey, - final T value) { - - if (!configurationKey.getDataType().isAssignableFrom(value.getClass())) { - throw new TenantConfigurationValidatorException(String.format( - "Cannot parse the value %s of type %s into the type %s defined by the configuration key.", value, - value.getClass(), configurationKey.getDataType())); - } - - configurationKey.validate(applicationContext, value); - - TenantConfiguration tenantConfiguration = tenantConfigurationRepository - .findByKey(configurationKey.getKeyName()); - - if (tenantConfiguration == null) { - tenantConfiguration = new TenantConfiguration(configurationKey.getKeyName(), value.toString()); - } else { - tenantConfiguration.setValue(value.toString()); - } - - final TenantConfiguration updatedTenantConfiguration = tenantConfigurationRepository.save(tenantConfiguration); - - final Class clazzT = (Class) value.getClass(); - - return TenantConfigurationValue. builder().isGlobal(false) - .createdBy(updatedTenantConfiguration.getCreatedBy()) - .createdAt(updatedTenantConfiguration.getCreatedAt()) - .lastModifiedAt(updatedTenantConfiguration.getLastModifiedAt()) - .lastModifiedBy(updatedTenantConfiguration.getLastModifiedBy()) - .value(conversionService.convert(updatedTenantConfiguration.getValue(), clazzT)).build(); - } - - /** - * 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 - */ - @CacheEvict(value = "tenantConfiguration", key = "#configurationKey.getKeyName()") - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @Modifying - @PreAuthorize(value = SpringEvalExpressions.HAS_AUTH_TENANT_CONFIGURATION) - public void deleteConfiguration(final TenantConfigurationKey configurationKey) { - tenantConfigurationRepository.deleteByKey(configurationKey.getKeyName()); - } - - @Override - public void setEnvironment(final Environment environment) { - this.environment = environment; - } -} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroup.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroup.java deleted file mode 100644 index 5aa30126c..000000000 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroup.java +++ /dev/null @@ -1,479 +0,0 @@ -/** - * 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.model; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.ConstraintMode; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.ForeignKey; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.Table; -import javax.persistence.Transient; -import javax.persistence.UniqueConstraint; - -/** - * JPA entity definition of persisting a group of an rollout. - * - * @author Michael Hirsch - * - */ -@Entity -@Table(name = "sp_rolloutgroup", indexes = { - @Index(name = "sp_idx_rolloutgroup_01", columnList = "tenant,name") }, uniqueConstraints = @UniqueConstraint(columnNames = { - "name", "rollout", "tenant" }, name = "uk_rolloutgroup")) -public class RolloutGroup extends NamedEntity { - - private static final long serialVersionUID = 1L; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "rollout", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_rolloutgroup_rollout")) - private Rollout rollout; - - @Column(name = "status") - private RolloutGroupStatus status = RolloutGroupStatus.READY; - - @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST }) - @JoinColumn(name = "rolloutGroup_Id", insertable = false, updatable = false) - private final List rolloutTargetGroup = new ArrayList<>(); - - @ManyToOne(fetch = FetchType.LAZY) - private RolloutGroup parent; - - @Column(name = "success_condition", nullable = false) - private RolloutGroupSuccessCondition successCondition = RolloutGroupSuccessCondition.THRESHOLD; - - @Column(name = "success_condition_exp", length = 512, nullable = false) - private String successConditionExp = null; - - @Column(name = "success_action", nullable = false) - private RolloutGroupSuccessAction successAction = RolloutGroupSuccessAction.NEXTGROUP; - - @Column(name = "success_action_exp", length = 512, nullable = false) - private String successActionExp = null; - - @Column(name = "error_condition") - private RolloutGroupErrorCondition errorCondition = null; - - @Column(name = "error_condition_exp", length = 512) - private String errorConditionExp = null; - - @Column(name = "error_action") - private RolloutGroupErrorAction errorAction = null; - - @Column(name = "error_action_exp", length = 512) - private String errorActionExp = null; - - @Column(name = "total_targets") - private long totalTargets; - - @Transient - private transient TotalTargetCountStatus totalTargetCountStatus; - - public Rollout getRollout() { - return rollout; - } - - public void setRollout(final Rollout rollout) { - this.rollout = rollout; - } - - public RolloutGroupStatus getStatus() { - return status; - } - - public void setStatus(final RolloutGroupStatus status) { - this.status = status; - } - - public List getRolloutTargetGroup() { - return rolloutTargetGroup; - } - - public RolloutGroup getParent() { - return parent; - } - - public void setParent(final RolloutGroup parent) { - this.parent = parent; - } - - public RolloutGroupSuccessCondition getSuccessCondition() { - return successCondition; - } - - public void setSuccessCondition(final RolloutGroupSuccessCondition finishCondition) { - successCondition = finishCondition; - } - - public String getSuccessConditionExp() { - return successConditionExp; - } - - public void setSuccessConditionExp(final String finishExp) { - successConditionExp = finishExp; - } - - public RolloutGroupErrorCondition getErrorCondition() { - return errorCondition; - } - - public void setErrorCondition(final RolloutGroupErrorCondition errorCondition) { - this.errorCondition = errorCondition; - } - - public String getErrorConditionExp() { - return errorConditionExp; - } - - public void setErrorConditionExp(final String errorExp) { - errorConditionExp = errorExp; - } - - public RolloutGroupErrorAction getErrorAction() { - return errorAction; - } - - public void setErrorAction(final RolloutGroupErrorAction errorAction) { - this.errorAction = errorAction; - } - - public String getErrorActionExp() { - return errorActionExp; - } - - public void setErrorActionExp(final String errorActionExp) { - this.errorActionExp = errorActionExp; - } - - public RolloutGroupSuccessAction getSuccessAction() { - return successAction; - } - - public String getSuccessActionExp() { - return successActionExp; - } - - public long getTotalTargets() { - return totalTargets; - } - - public void setTotalTargets(final long totalTargets) { - this.totalTargets = totalTargets; - } - - public void setSuccessAction(final RolloutGroupSuccessAction successAction) { - this.successAction = successAction; - } - - public void setSuccessActionExp(final String successActionExp) { - this.successActionExp = successActionExp; - } - - /** - * @return the totalTargetCountStatus - */ - public TotalTargetCountStatus getTotalTargetCountStatus() { - if (totalTargetCountStatus == null) { - totalTargetCountStatus = new TotalTargetCountStatus(totalTargets); - } - return totalTargetCountStatus; - } - - /** - * @param totalTargetCountStatus - * the totalTargetCountStatus to set - */ - public void setTotalTargetCountStatus(final TotalTargetCountStatus totalTargetCountStatus) { - this.totalTargetCountStatus = totalTargetCountStatus; - } - - @Override - public String toString() { - return "RolloutGroup [rollout=" + rollout + ", status=" + status + ", rolloutTargetGroup=" + rolloutTargetGroup - + ", parent=" + parent + ", finishCondition=" + successCondition + ", finishExp=" + successConditionExp - + ", errorCondition=" + errorCondition + ", errorExp=" + errorConditionExp + ", getName()=" + getName() - + ", getId()=" + getId() + "]"; - } - - /** - * Rollout goup state machine. - * - */ - public enum RolloutGroupStatus { - - /** - * Ready to start the group. - */ - READY, - - /** - * Group is scheduled and started sometime, e.g. trigger of group - * before. - */ - SCHEDULED, - - /** - * Group is finished. - */ - FINISHED, - - /** - * Group is finished and has errors. - */ - ERROR, - - /** - * Group is running. - */ - RUNNING; - } - - /** - * The condition to evaluate if an group is success state. - */ - public enum RolloutGroupSuccessCondition { - THRESHOLD("thresholdRolloutGroupSuccessCondition"); - - private final String beanName; - - private RolloutGroupSuccessCondition(final String beanName) { - this.beanName = beanName; - } - - /** - * @return the beanName - */ - public String getBeanName() { - return beanName; - } - } - - /** - * The condition to evaluate if an group is in error state. - */ - public enum RolloutGroupErrorCondition { - THRESHOLD("thresholdRolloutGroupErrorCondition"); - - private final String beanName; - - private RolloutGroupErrorCondition(final String beanName) { - this.beanName = beanName; - } - - /** - * @return the beanName - */ - public String getBeanName() { - return beanName; - } - } - - /** - * The actions executed when the {@link RolloutGroup#errorCondition} is hit. - */ - public enum RolloutGroupErrorAction { - PAUSE("pauseRolloutGroupAction"); - - private final String beanName; - - private RolloutGroupErrorAction(final String beanName) { - this.beanName = beanName; - } - - /** - * @return the beanName - */ - public String getBeanName() { - return beanName; - } - } - - /** - * The actions executed when the {@link RolloutGroup#successCondition} is - * hit. - */ - public enum RolloutGroupSuccessAction { - NEXTGROUP("startNextRolloutGroupAction"); - - private final String beanName; - - private RolloutGroupSuccessAction(final String beanName) { - this.beanName = beanName; - } - - /** - * @return the beanName - */ - public String getBeanName() { - return beanName; - } - } - - /** - * Object which holds all {@link RolloutGroup} conditions together which can - * easily built. - */ - public static class RolloutGroupConditions { - private RolloutGroupSuccessCondition successCondition = null; - private String successConditionExp = null; - private RolloutGroupSuccessAction successAction = null; - private String successActionExp = null; - private RolloutGroupErrorCondition errorCondition = null; - private String errorConditionExp = null; - private RolloutGroupErrorAction errorAction = null; - private String errorActionExp = null; - - public RolloutGroupSuccessCondition getSuccessCondition() { - return successCondition; - } - - public void setSuccessCondition(final RolloutGroupSuccessCondition finishCondition) { - successCondition = finishCondition; - } - - public String getSuccessConditionExp() { - return successConditionExp; - } - - public void setSuccessConditionExp(final String finishConditionExp) { - successConditionExp = finishConditionExp; - } - - public RolloutGroupSuccessAction getSuccessAction() { - return successAction; - } - - public void setSuccessAction(final RolloutGroupSuccessAction successAction) { - this.successAction = successAction; - } - - public String getSuccessActionExp() { - return successActionExp; - } - - public void setSuccessActionExp(final String successActionExp) { - this.successActionExp = successActionExp; - } - - public RolloutGroupErrorCondition getErrorCondition() { - return errorCondition; - } - - public void setErrorCondition(final RolloutGroupErrorCondition errorCondition) { - this.errorCondition = errorCondition; - } - - public String getErrorConditionExp() { - return errorConditionExp; - } - - public void setErrorConditionExp(final String errorConditionExp) { - this.errorConditionExp = errorConditionExp; - } - - public RolloutGroupErrorAction getErrorAction() { - return errorAction; - } - - public void setErrorAction(final RolloutGroupErrorAction errorAction) { - this.errorAction = errorAction; - } - - public String getErrorActionExp() { - return errorActionExp; - } - - public void setErrorActionExp(final String errorActionExp) { - this.errorActionExp = errorActionExp; - } - } - - /** - * Builder to build easily the {@link RolloutGroupConditions}. - * - */ - public static class RolloutGroupConditionBuilder { - private final RolloutGroupConditions conditions = new RolloutGroupConditions(); - - public RolloutGroupConditions build() { - return conditions; - } - - /** - * Sets the finish condition and expression on the builder. - * - * @param condition - * the finish condition - * @param expression - * the finish expression - * @return the builder itself - */ - public RolloutGroupConditionBuilder successCondition(final RolloutGroupSuccessCondition condition, - final String expression) { - conditions.setSuccessCondition(condition); - conditions.setSuccessConditionExp(expression); - return this; - } - - /** - * Sets the success action and expression on the builder. - * - * @param action - * the success action - * @param expression - * the error expression - * @return the builder itself - */ - public RolloutGroupConditionBuilder successAction(final RolloutGroupSuccessAction action, - final String expression) { - conditions.setSuccessAction(action); - conditions.setSuccessActionExp(expression); - return this; - } - - /** - * Sets the error condition and expression on the builder. - * - * @param condition - * the error condition - * @param expression - * the error expression - * @return the builder itself - */ - public RolloutGroupConditionBuilder errorCondition(final RolloutGroupErrorCondition condition, - final String expression) { - conditions.setErrorCondition(condition); - conditions.setErrorConditionExp(expression); - return this; - } - - /** - * Sets the error action and expression on the builder. - * - * @param action - * the error action - * @param expression - * the error expression - * @return the builder itself - */ - public RolloutGroupConditionBuilder errorAction(final RolloutGroupErrorAction action, final String expression) { - conditions.setErrorAction(action); - conditions.setErrorActionExp(expression); - return this; - } - } -} diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/LocalH2TestDatabase.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/LocalH2TestDatabase.java deleted file mode 100644 index a32c481fc..000000000 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/LocalH2TestDatabase.java +++ /dev/null @@ -1,118 +0,0 @@ -/** - * 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; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.UUID; - -import org.h2.tools.Server; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * - */ -public class LocalH2TestDatabase implements Testdatabase { - - private final static Logger LOG = LoggerFactory.getLogger(LocalH2TestDatabase.class); - private final int port; - private Server h2server; - private boolean dbStarted; - private String uri; - - public LocalH2TestDatabase(final int port) { - super(); - this.port = port; - createUri(); - initSystemProperties(); - } - - private final void initSystemProperties() { - System.setProperty("spring.datasource.driverClassName", getDriverClassName()); - System.setProperty("spring.datasource.username", ""); - System.setProperty("spring.datasource.password", ""); - System.setProperty("hawkbit.server.database", "H2"); - } - - private void dropAllObjects() { - try (Connection connection = DriverManager.getConnection(uri)) { - connection.prepareCall("DROP ALL OBJECTS;").execute(); - } catch (final SQLException e) { - e.printStackTrace(); - } - } - - @Override - public void before() { - try { - startDatabase(); - } catch (ClassNotFoundException | SQLException | IOException e) { - e.printStackTrace(); - } - } - - @Override - public void after() { - try { - stopDatabase(); - } catch (ClassNotFoundException | SQLException | IOException e) { - e.printStackTrace(); - } - } - - private void startDatabase() throws SQLException, ClassNotFoundException, IOException { - if (dbStarted) { - return; - } - - // Start H2 database for OpenFire - h2server = Server - .createTcpServer( - new String[] { "-tcpPort", String.valueOf(port), "-tcpAllowOthers", "-tcpShutdownForce" }) - .start(); - dbStarted = true; - LOG.info("H2 Database started on port {} and uri {}", port, uri); - dropAllObjects(); - } - - private final void createUri() { - this.uri = "jdbc:h2:tcp://localhost:" + port + "/mem:SP" + UUID.randomUUID().toString() + ";MVCC=TRUE;" - + "DB_CLOSE_DELAY=-1"; - System.setProperty("spring.datasource.url", uri); - } - - private void stopDatabase() throws SQLException, ClassNotFoundException, IOException { - if (!dbStarted) { - return; - } - - h2server.stop(); - h2server = null; - dbStarted = false; - try { - Thread.sleep(1000); - } catch (final InterruptedException e) { - } - } - - @Override - public String getDriverClassName() { - return "org.h2.Driver"; - } - - @Override - public String getUri() { - return uri; - } - -} diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestDataUtil.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestDataUtil.java deleted file mode 100644 index 7ce8283dc..000000000 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestDataUtil.java +++ /dev/null @@ -1,425 +0,0 @@ -/** - * 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; - -import static org.fest.assertions.api.Assertions.assertThat; - -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Random; -import java.util.UUID; - -import org.apache.commons.io.IOUtils; -import org.eclipse.hawkbit.repository.ActionRepository; -import org.eclipse.hawkbit.repository.ArtifactManagement; -import org.eclipse.hawkbit.repository.ControllerManagement; -import org.eclipse.hawkbit.repository.DistributionSetManagement; -import org.eclipse.hawkbit.repository.SoftwareManagement; -import org.eclipse.hawkbit.repository.TargetManagement; -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.DistributionSetTag; -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.Target; -import org.eclipse.hawkbit.repository.model.TargetTag; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; - -import com.google.common.base.Strings; -import com.google.common.collect.Lists; - -import net._01001111.text.LoremIpsum; - -/** - * Data generator utility for tests. - * - * - * - */ -public class TestDataUtil { - private static final LoremIpsum LOREM = new LoremIpsum(); - - public static DistributionSet createTestDistributionSet(final SoftwareManagement softwareManagement, - final DistributionSetManagement distributionSetManagement) { - final Pageable pageReq = new PageRequest(0, 400); - DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement, - distributionSetManagement); - set.setVersion("anotherVersion"); - set = distributionSetManagement.updateDistributionSet(set); - - set.getModules().forEach(module -> { - module.setDescription("updated description"); - softwareManagement.updateSoftwareModule(module); - }); - - // load also lazy stuff - set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()); - - assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1); - return set; - } - - public static List sendUpdateActionStatusToTargets(final ControllerManagement controllerManagament, - final TargetManagement targetManagement, final ActionRepository actionRepository, final DistributionSet dsA, - final Iterable targs, final Status status, final String... msgs) { - final List result = new ArrayList(); - for (final Target t : targs) { - final List findByTarget = actionRepository.findByTarget(t); - for (final Action action : findByTarget) { - result.add(sendUpdateActionStatusToTarget(controllerManagament, targetManagement, status, action, t, - msgs)); - } - } - return result; - } - - private static Target sendUpdateActionStatusToTarget(final ControllerManagement controllerManagament, - final TargetManagement targetManagement, final Status status, final Action updActA, final Target t, - final String... msgs) { - updActA.setStatus(status); - - final ActionStatus statusMessages = new ActionStatus(); - statusMessages.setAction(updActA); - statusMessages.setOccurredAt(System.currentTimeMillis()); - statusMessages.setStatus(status); - for (final String msg : msgs) { - statusMessages.addMessage(msg); - } - controllerManagament.addUpdateActionStatus(statusMessages, updActA); - return targetManagement.findTargetByControllerID(t.getControllerId()); - } - - public static List generateDistributionSets(final String suffix, final int number, - final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement) { - - final List sets = new ArrayList(); - for (int i = 0; i < number; i++) { - sets.add(generateDistributionSet(suffix, "v1." + i, softwareManagement, distributionSetManagement, false)); - } - - return sets; - } - - public static DistributionSet generateDistributionSetWithNoSoftwareModules(final String name, final String version, - final DistributionSetManagement distributionSetManagement) { - - final DistributionSet dis = new DistributionSet(); - dis.setName(name); - dis.setVersion(version); - dis.setDescription("Test describtion for " + name); - return distributionSetManagement.createDistributionSet(dis); - } - - public static List generateDistributionSets(final int number, - final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement) { - - return generateDistributionSets("", number, softwareManagement, distributionSetManagement); - } - - public static DistributionSet generateDistributionSet(final String suffix, final String version, - final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement, - final boolean isRequiredMigrationStep) { - - final SoftwareModule ah = softwareManagement.createSoftwareModule(new SoftwareModule( - findOrCreateSoftwareModuleType(softwareManagement, "application"), suffix + "application", - version + "." + new Random().nextInt(100), LOREM.words(20), suffix + " vendor Limited, California")); - final SoftwareModule jvm = softwareManagement - .createSoftwareModule(new SoftwareModule(findOrCreateSoftwareModuleType(softwareManagement, "runtime"), - suffix + "app runtime", version + "." + new Random().nextInt(100), LOREM.words(20), - suffix + " vendor GmbH, Stuttgart, Germany")); - final SoftwareModule os = softwareManagement - .createSoftwareModule(new SoftwareModule(findOrCreateSoftwareModuleType(softwareManagement, "os"), - suffix + " Firmware", version + "." + new Random().nextInt(100), LOREM.words(20), - suffix + " vendor Limited Inc, California")); - - final List mand = new ArrayList<>(); - mand.add(findOrCreateSoftwareModuleType(softwareManagement, "os")); - - final List opt = new ArrayList<>(); - opt.add(findOrCreateSoftwareModuleType(softwareManagement, "application")); - opt.add(findOrCreateSoftwareModuleType(softwareManagement, "runtime")); - - return distributionSetManagement.createDistributionSet( - buildDistributionSet(suffix != null && suffix.length() > 0 ? suffix : "DS", version, - findOrCreateDistributionSetType(distributionSetManagement, "ecl_os_app_jvm", - "OS mandatory App/JVM optional", mand, opt), - os, jvm, ah).setRequiredMigrationStep(isRequiredMigrationStep)); - } - - public static DistributionSet generateDistributionSet(final String suffix, final String version, - final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement, - final Collection tags) { - - final DistributionSet set = generateDistributionSet(suffix, version, softwareManagement, - distributionSetManagement, false); - - final List sets = new ArrayList(); - sets.add(set); - - tags.forEach(tag -> distributionSetManagement.toggleTagAssignment(sets, tag)); - - return distributionSetManagement.findDistributionSetById(set.getId()); - - } - - public static List generateTargets(final int number) { - return generateTargets(0, number, "Test target "); - } - - public static List generateTargets(final int number, final String prefix) { - return generateTargets(0, number, prefix); - } - - public static List generateTargets(final int start, final int number, final String prefix) { - final List targets = new ArrayList<>(); - for (int i = start; i < start + number; i++) { - targets.add(new Target(prefix + i)); - } - - return targets; - } - - public static List generateTargetTags(final int number) { - final List result = new ArrayList<>(); - - for (int i = 0; i < number; i++) { - result.add(new TargetTag("tag" + i, "tagdesc" + i, "" + i)); - } - - return result; - } - - public static List generateDistributionSetTags(final int number) { - final List result = new ArrayList<>(); - - for (int i = 0; i < number; i++) { - result.add(new DistributionSetTag("tag" + i, "tagdesc" + i, "" + i)); - } - - return result; - } - - public static DistributionSet generateDistributionSet(final String suffix, - final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement, - final boolean isRequiredMigrationStep) { - return generateDistributionSet(suffix, "v1.0", softwareManagement, distributionSetManagement, - isRequiredMigrationStep); - } - - public static DistributionSet generateDistributionSet(final String suffix, - final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement) { - return generateDistributionSet(suffix, "v1.0", softwareManagement, distributionSetManagement, false); - } - - public static List generateArtifacts( - final ArtifactManagement artifactManagement, final Long moduleId) { - final List artifacts = new ArrayList<>(); - for (int i = 0; i < 3; i++) { - final InputStream stubInputStream = IOUtils.toInputStream("some test data" + i); - artifacts.add(artifactManagement.createLocalArtifact(stubInputStream, moduleId, "filename" + i, false)); - - } - - return artifacts; - } - - public static Target createTarget(final TargetManagement targetManagement) { - final String targetExist = "targetExist"; - final Target target = new Target(targetExist); - targetManagement.createTarget(target); - return target; - } - - public static DistributionSet generateDistributionSet(final String suffix, - final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement, - final Collection tags) { - return generateDistributionSet(suffix, "v1.0", softwareManagement, distributionSetManagement, tags); - } - - public static SoftwareModuleType findOrCreateSoftwareModuleType(final SoftwareManagement softwareManagement, - final String softwareModuleType) { - final SoftwareModuleType findSoftwareModuleTypeByKey = softwareManagement - .findSoftwareModuleTypeByKey(softwareModuleType); - if (findSoftwareModuleTypeByKey != null) { - return findSoftwareModuleTypeByKey; - } - return softwareManagement.createSoftwareModuleType(new SoftwareModuleType(softwareModuleType, - softwareModuleType, "Standard type " + softwareManagement, 1)); - } - - public static DistributionSetType findOrCreateDistributionSetType( - final DistributionSetManagement distributionSetManagement, final String dsTypeKey, final String dsTypeName, - final Collection mandatory, final Collection optional) { - final DistributionSetType findDistributionSetTypeByname = distributionSetManagement - .findDistributionSetTypeByKey(dsTypeKey); - - if (findDistributionSetTypeByname != null) { - return findDistributionSetTypeByname; - } - - final DistributionSetType type = new DistributionSetType(dsTypeKey, dsTypeName, "Standard type" + dsTypeName); - mandatory.forEach(entry -> type.addMandatoryModuleType(entry)); - optional.forEach(entry -> type.addOptionalModuleType(entry)); - - return distributionSetManagement.createDistributionSetType(type); - } - - /** - * builds a set of {@link Target} fixtures from the given parameters. - * - * @param noOfTgts - * number of targets to create - * @param ctlrIDPrefix - * prefix used for the controller ID - * @param descriptionPrefix - * prefix used for the description - * @return set of {@link Target} - */ - public static List buildTargetFixtures(final int noOfTgts, final String ctlrIDPrefix, - final String descriptionPrefix) { - return buildTargetFixtures(noOfTgts, ctlrIDPrefix, descriptionPrefix, null); - } - - /** - * method creates set of targets by by generating the controller ID and the - * description like: prefix + no of target. - * - * @param noOfTgts - * number of targets which should be created - * @param ctlrIDPrefix - * prefix of the controllerID which is concatenated with the - * number of the target - * @param descriptionPrefix - * prefix of the target description which is concatenated with - * the number of the target - * @param tags - * tags which should be added to the created {@link Target}s - * @return set of created targets - */ - public static List buildTargetFixtures(final int noOfTgts, final String ctlrIDPrefix, - final String descriptionPrefix, final TargetTag[] tags) { - final List list = new ArrayList(); - for (int i = 0; i < noOfTgts; i++) { - String ctrlID = ctlrIDPrefix; - if (Strings.isNullOrEmpty(ctrlID)) { - ctrlID = UUID.randomUUID().toString(); - } - ctrlID = String.format("%s-%05d", ctrlID, i); - - final String description = String.format("the description of ProvisioningTarget: [%s]", ctrlID); - - final Target target = buildTargetFixture(ctrlID, description, tags); - list.add(target); - - } - return list; - } - - /** - * builds a single {@link Target} fixture from the given parameters. - * - * @param ctrlID - * controllerID - * @param description - * the description of the target - * @param tags - * assigned {@link TargetTag}s - * @return the created {@link Target} - */ - public static Target buildTargetFixture(final String ctrlID, final String description, final TargetTag[] tags) { - final Target target = new Target(ctrlID); - target.setName("Prov.Target ".concat(ctrlID)); - target.setDescription(description); - if (tags != null && tags.length > 0) { - for (final TargetTag t : tags) { - target.getTags().add(t); - } - } - return target; - } - - /** - * builder method for creating a single target object. - * - * @param ctrlID - * the ID of the target - * @param description - * of the target - * @return the created target object - */ - public static Target buildTargetFixture(final String ctrlID, final String description) { - return buildTargetFixture(ctrlID, description, null); - } - - /** - * builder method for creating a {@link DistributionSet}. - * - * @param name - * of the DS - * @param version - * of the DS - * @param os - * operating system of the DS - * @param jvm - * java virtual machine of the DS - * @param agentHub - * of the DS - * @return the created {@link DistributionSet} - */ - public static DistributionSet buildDistributionSet(final String name, final String version, - final DistributionSetType type, final SoftwareModule os, final SoftwareModule jvm, - final SoftwareModule agentHub) { - final DistributionSet distributionSet = new DistributionSet(name, version, null, type, - Lists.newArrayList(os, jvm, agentHub)); - distributionSet.setDescription( - String.format("description of DistributionSet; name = '%s', version = '%s'", name, version)); - return distributionSet; - } - - /** - * builder method for creating a set of {@link TargetTag}. - * - * @param noOfTags - * number of {@link TargetTag}. to be created - * @param tagPrefix - * prefix for the {@link TargetTag.getName()} - * @return the created set of {@link TargetTag}s - */ - public static List buildTargetTagFixtures(final int noOfTags, final String tagPrefix) { - final List list = new ArrayList<>(); - for (int i = 0; i < noOfTags; i++) { - String tagName = "myTag"; - if (!Strings.isNullOrEmpty(tagPrefix)) { - tagName = tagPrefix; - } - tagName = String.format("%s-%05d", tagName, i); - - final TargetTag targetTag = buildTargetTagFixture(tagName); - list.add(targetTag); - } - return list; - } - - /** - * builder method for creating a simple {@link TargetTag}. - * - * @param tagName - * name of the Tag - * @return the {@link TargetTag} - */ - public static TargetTag buildTargetTagFixture(final String tagName) { - return new TargetTag(tagName); - } -} diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/utils/RepositoryDataGenerator.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/utils/RepositoryDataGenerator.java deleted file mode 100644 index a1c74e791..000000000 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/utils/RepositoryDataGenerator.java +++ /dev/null @@ -1,480 +0,0 @@ -/** - * 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.utils; - -import java.net.URI; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.List; -import java.util.Random; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.IntStream; - -import javax.persistence.EntityManager; -import javax.persistence.Query; -import javax.transaction.Transactional; - -import org.eclipse.hawkbit.TestDataUtil; -import org.eclipse.hawkbit.im.authentication.SpPermission; -import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; -import org.eclipse.hawkbit.im.authentication.TenantAwareAuthenticationDetails; -import org.eclipse.hawkbit.repository.ControllerManagement; -import org.eclipse.hawkbit.repository.DeploymentManagement; -import org.eclipse.hawkbit.repository.DistributionSetAssignmentResult; -import org.eclipse.hawkbit.repository.DistributionSetManagement; -import org.eclipse.hawkbit.repository.SoftwareManagement; -import org.eclipse.hawkbit.repository.TagManagement; -import org.eclipse.hawkbit.repository.TargetManagement; -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.DistributionSetTag; -import org.eclipse.hawkbit.repository.model.SoftwareModule; -import org.eclipse.hawkbit.repository.model.SoftwareModuleType; -import org.eclipse.hawkbit.repository.model.Target; -import org.eclipse.hawkbit.repository.model.TargetTag; -import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; -import org.eclipse.hawkbit.util.IpUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.data.auditing.AuditingHandler; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.security.authentication.TestingAuthenticationToken; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.context.SecurityContextImpl; - -import net._01001111.text.LoremIpsum; - -/** - * Generates test data for setting up the repository for test or demonstration - * purpose. - * - * - * - */ -public final class RepositoryDataGenerator { - private static final Logger LOG = LoggerFactory.getLogger(RepositoryDataGenerator.class); - - public static void initDemoRepo(final ConfigurableApplicationContext context) { - final PersistentInitDemoDataBuilder initDemoDataBuilder = new PersistentInitDemoDataBuilder(context); - initDemoDataBuilder.initDemoRepo(20, 0); - } - - public static void initLoadRepo(final ConfigurableApplicationContext context) { - final PersistentInitDemoDataBuilder initDemoDataBuilder = new PersistentInitDemoDataBuilder(context); - initDemoDataBuilder.initDemoRepo(200, 200); - } - - /** - * builder which build initial demo data and stores it to the repos. - * - */ - private static final class PersistentInitDemoDataBuilder { - - private final SoftwareManagement softwareManagement; - private final TargetManagement targetManagement; - private final DeploymentManagement deploymentManagement; - private final TagManagement tagManagement; - private final ControllerManagement controllerManagement; - private final DistributionSetManagement distributionSetManagement; - - private final DatabaseCleanupUtil dbCleanupUtil; - - private final AuditingHandler auditingHandler; - - final LoremIpsum jlorem = new LoremIpsum(); - - PersistentInitDemoDataBuilder(final ConfigurableApplicationContext context) { - softwareManagement = context.getBean(SoftwareManagement.class); - targetManagement = context.getBean(TargetManagement.class); - tagManagement = context.getBean(TagManagement.class); - deploymentManagement = context.getBean(DeploymentManagement.class); - controllerManagement = context.getBean(ControllerManagement.class); - distributionSetManagement = context.getBean(DistributionSetManagement.class); - - dbCleanupUtil = context.getBean(DatabaseCleanupUtil.class); - - auditingHandler = context.getBean(AuditingHandler.class); - } - - private void runAsAllAuthorityContext(final Runnable runnable) { - final SecurityContext oldContext = SecurityContextHolder.getContext(); - try { - final SecurityContextImpl securityContextImpl = new SecurityContextImpl(); - final TestingAuthenticationToken authentication = new TestingAuthenticationToken("repogenator", - "repogenator", SpPermission.CREATE_REPOSITORY, SpPermission.CREATE_TARGET, - SpPermission.DELETE_REPOSITORY, SpPermission.DELETE_TARGET, SpPermission.READ_REPOSITORY, - SpPermission.READ_TARGET, SpPermission.UPDATE_REPOSITORY, SpPermission.UPDATE_TARGET, - SpringEvalExpressions.CONTROLLER_ROLE); - securityContextImpl.setAuthentication(authentication); - authentication.setDetails(new TenantAwareAuthenticationDetails("default", false)); - SecurityContextHolder.setContext(securityContextImpl); - runnable.run(); - } finally { - SecurityContextHolder.setContext(oldContext); - } - } - - public void generateTestTagetGroup(final String group, final int sizeMultiplikator) { - final DistributionSetTag dsTag = tagManagement - .createDistributionSetTag(new DistributionSetTag("For " + group + "s")); - - auditingHandler.setDateTimeProvider(() -> { - final Calendar instance = Calendar.getInstance(); - instance.add(Calendar.MONTH, -new Random().nextInt(7)); - - return instance; - }); - - final List targets = createTargetTestGroup(group, 20 * sizeMultiplikator); - - auditingHandler.setDateTimeProvider(() -> { - final Calendar instance = Calendar.getInstance(); - return instance; - }); - - LOG.debug("initDemoRepo - start now real action history for group: {}", group); - - // Old history of succesfully finished operations - IntStream.range(0, 10).forEach(idx -> { - final DistributionSet dsReal = TestDataUtil.generateDistributionSet(group + " Release", "v1." + idx, - softwareManagement, distributionSetManagement, - Arrays.asList(new DistributionSetTag[] { dsTag })); - - final DistributionSetAssignmentResult result = deploymentManagement.assignDistributionSet(dsReal, - targets); - - createSimpleActionStatusHistory(result.getActions()); - }); - - final List> targetGroups = splitIntoGroups(targets); - - IntStream.range(0, targetGroups.size()).forEach(idx -> { - final DistributionSet dsReal = TestDataUtil.generateDistributionSet(group + " Release", "v2." + idx, - softwareManagement, distributionSetManagement, - Arrays.asList(new DistributionSetTag[] { dsTag })); - - final DistributionSetAssignmentResult result = deploymentManagement.assignDistributionSet(dsReal, - targetGroups.get(idx)); - - createActionStatusHistory(result.getActions(), sizeMultiplikator); - }); - - LOG.debug("initDemoRepo - real action history finished for group: {}", group); - } - - private List> splitIntoGroups(final List allTargets) { - - final int elements = allTargets.size(); - - final int group1 = elements * (5 + new Random().nextInt(5)) / 100; - final int group2 = elements * (15 + new Random().nextInt(5)) / 100; - - final List> result = new ArrayList>(); - - result.add(allTargets.subList(0, group1)); - result.add(allTargets.subList(group1, group2)); - result.add(allTargets.subList(group2, elements)); - - return result; - - } - - private void createActionStatusHistory(final List actions, final int sizeMultiplikator) { - final AtomicInteger counter = new AtomicInteger(); - - int index = 0; - for (final Long actionGiven : actions) { - // retrieved - Action action = controllerManagement.registerRetrieved( - deploymentManagement.findActionWithDetails(actionGiven), - "Controller retrieved update action and should start now the download."); - - // download - final ActionStatus download = new ActionStatus(); - download.setAction(action); - download.setStatus(Status.DOWNLOAD); - download.addMessage("Controller started download."); - action = controllerManagement.addUpdateActionStatus(download, action); - - // warning - final ActionStatus warning = new ActionStatus(); - warning.setAction(action); - warning.setStatus(Status.WARNING); - warning.addMessage("Some warning: " + jlorem.words(new Random().nextInt(50))); - action = controllerManagement.addUpdateActionStatus(warning, action); - - // garbage - for (int i = 0; i < new Random().nextInt(10); i++) { - final ActionStatus running = new ActionStatus(); - running.setAction(action); - running.setStatus(Status.RUNNING); - running.addMessage("Still running: " + jlorem.words(new Random().nextInt(50))); - action = controllerManagement.addUpdateActionStatus(running, action); - for (int g = 0; g < new Random().nextInt(5); g++) { - final ActionStatus rand = new ActionStatus(); - rand.setAction(action); - rand.setStatus(Status.RUNNING); - rand.addMessage(jlorem.words(new Random().nextInt(50))); - action = controllerManagement.addUpdateActionStatus(rand, action); - } - } - - // close - final ActionStatus close = new ActionStatus(); - close.setAction(action); - - // with error - final int incrementAndGet = counter.incrementAndGet(); - if (incrementAndGet % 5 == 0) { - close.setStatus(Status.ERROR); - close.addMessage("Controller reported CLOSED with ERROR!"); - action = controllerManagement.addUpdateActionStatus(close, action); - } - // with OK - else { - close.setStatus(Status.FINISHED); - close.addMessage("Controller reported CLOSED with OK!"); - action = controllerManagement.addUpdateActionStatus(close, action); - } - - index++; - } - } - - private void createSimpleActionStatusHistory(final List actions) { - for (final Long actionGiven : actions) { - // retrieved - Action action = controllerManagement.registerRetrieved( - deploymentManagement.findActionWithDetails(actionGiven), - "Controller retrieved update action and should start now the download."); - - // close - final ActionStatus close = new ActionStatus(); - close.setAction(action); - close.setStatus(Status.FINISHED); - close.addMessage("Controller reported CLOSED with OK!"); - action = controllerManagement.addUpdateActionStatus(close, action); - - } - } - - private List createTargetTestGroup(final String group, final int targets) { - LOG.debug("createTargetTestGroup: create group {}", group); - - final TargetTag targTag = tagManagement.createTargetTag(new TargetTag(group)); - - final List targAs = targetManagement.createTargets(buildTargets(targets, group), - TargetUpdateStatus.REGISTERED, System.currentTimeMillis() - new Random().nextInt(50_000_000), - generateIPAddress()); - LOG.debug("createTargetTestGroup: {} created", group); - - LOG.debug("createTargetTestGroup: {} targets status updated including IP", group); - - return targetManagement.toggleTagAssignment(targAs, targTag).getAssignedEntity(); - } - - private List buildTargets(final int noOfTgts, final String descriptionPrefix) { - - final List result = new ArrayList(noOfTgts); - - for (int i = 0; i < noOfTgts; i++) { - final Target target = new Target(UUID.randomUUID().toString()); - - final StringBuilder builder = new StringBuilder(); - builder.append(descriptionPrefix); - builder.append(jlorem.words(5)); - - target.setDescription(builder.toString()); - target.getTargetInfo().getControllerAttributes().put("revision", "1.1"); - target.getTargetInfo().getControllerAttributes().put("capacity", "128M"); - target.getTargetInfo().getControllerAttributes().put("serial", - String.valueOf(System.currentTimeMillis())); - - result.add(target); - - } - - return result; - } - - /** - * method writes initial test/demo data to the repositories. - * - * @param sizeMultiplikator - * the entire scenario - * @param loadtestgroups - * packages of 1_000 targets - */ - private void initDemoRepo(final int sizeMultiplikator, final int loadtestgroups) { - final LoremIpsum jlorem = new LoremIpsum(); - - runAsAllAuthorityContext(() -> { - dbCleanupUtil.cleanupDB(null); - - // generate targets and assign DS - // 5 groups - 100 targets each -> 500 - final String[] targetTestGroups = { "SHC", "CCU", "Vehicle", "Vending machine", "ECU" }; - - final String[] modulesTypes = { "HeadUnit_FW", "EDC17_FW", "OSGi_Bundle" }; - - final DistributionSetTag depTag = tagManagement - .createDistributionSetTag(new DistributionSetTag("deprecated")); - - Arrays.stream(targetTestGroups).forEach(group -> { - generateTestTagetGroup(group, sizeMultiplikator); - }); - - // garbage DS - LOG.debug("initDemoRepo - start now DS garbage"); - TestDataUtil.generateDistributionSets("Generic Software Package", sizeMultiplikator, - softwareManagement, distributionSetManagement); - LOG.debug("initDemoRepo - DS garbage finished"); - - LOG.debug("initDemoRepo - start now Extra Software Modules and types"); - Arrays.stream(modulesTypes).forEach(typeName -> { - final SoftwareModuleType smtype = softwareManagement.createSoftwareModuleType( - new SoftwareModuleType(typeName.toLowerCase().replaceAll("\\s+", ""), typeName, - jlorem.words(5), Integer.MAX_VALUE)); - - for (int i1 = 0; i1 < sizeMultiplikator; i1++) { - softwareManagement.createSoftwareModule(new SoftwareModule(smtype, typeName + i1, "1.0." + i1, - jlorem.words(5), "the " + typeName + " vendor Inc.")); - } - - }); - LOG.debug("initDemoRepo - Extra Software Modules and types finished"); - - LOG.debug("initDemoRepo - start now target garbage"); - - // garbage targets - // unknown - targetManagement - .createTargets(TestDataUtil.generateTargets(targetTestGroups.length * sizeMultiplikator)); - - // registered - targetManagement.createTargets( - TestDataUtil.generateTargets(targetTestGroups.length * sizeMultiplikator, "registered"), - TargetUpdateStatus.REGISTERED, System.currentTimeMillis(), generateIPAddress()); - - // pending - final DistributionSetTag dsTag = tagManagement - .createDistributionSetTag(new DistributionSetTag("OnlyAssignedTag")); - final DistributionSet ds = TestDataUtil.generateDistributionSet("Pending DS", "v1.0", - softwareManagement, distributionSetManagement, - Arrays.asList(new DistributionSetTag[] { dsTag })); - deploymentManagement.assignDistributionSet(ds, targetManagement.createTargets( - TestDataUtil.generateTargets(targetTestGroups.length * sizeMultiplikator, "pending"))); - - // Load test means additional 1_000_000 target - - for (int i2 = 0; i2 < loadtestgroups; i2++) { - targetManagement.createTargets(TestDataUtil.generateTargets(i2 * 1_000, 1_000, "loadtest-")); - } - - LOG.debug("initDemoRepo complete"); - }); - } - /** - * Adding controller attributes for given {@link Target}. - */ - // private Target setControllerAttributes( final String targetId ) { - // final Target target = - // targetManagement.findTargetByControllerIDWithDetails( targetId ); - // target.getTargetStatus().getControllerAttributes().put( "revision", - // "1.1" ); - // target.getTargetStatus().getControllerAttributes().put( "capacity", - // "128M" ); - // target.getTargetStatus().getControllerAttributes().put( "serial", - // String.valueOf( - // System.currentTimeMillis()) ); - // return targetManagement.updateTarget( target ); - // } - } - - /** - * - * Data clean up class. - * - * - * - */ - public static class DatabaseCleanupUtil { - - private static final Logger LOG = LoggerFactory.getLogger(DatabaseCleanupUtil.class); - @Autowired - private EntityManager entityManager; - - private static final String[] CLEAN_UP_SQLS = new String[] { "sp_tenant", "sp_tenant_configuration", - "sp_artifact", "sp_external_artifact", "sp_external_provider", "sp_target_target_tag", - "sp_target_attributes", "sp_target_tag", "sp_action_status_messages", "sp_action_status", "sp_action", - "sp_ds_dstag", "sp_distributionset_tag", "sp_target_info", "sp_target", "sp_sw_metadata", - "sp_ds_metadata", "sp_ds_module", "sp_distribution_set", "sp_base_software_module", - "sp_ds_type_element", "sp_distribution_set_type", "sp_software_module_type" }; - - /** - * delete all entries from the DB tables. - */ - @Transactional - @Modifying - public void cleanupDB(final String database) { - LOG.debug("Data clean up is started..."); - final boolean isMySql = "MYSQL".equals(database); - if (isMySql) { - // disable foreign key check because otherwise mysql cannot - // delete sp_active_actions due - // the self constraint within the table, stupid MySql - entityManager.createNativeQuery("SET FOREIGN_KEY_CHECKS = 0").executeUpdate(); - } - try { - final String[] dbCmds = new String[] { "delete from" }; - for (final String dbCmd : dbCmds) { - for (final String table : CLEAN_UP_SQLS) { - final String sql = String.format("%s %s", dbCmd, table); - final Query query = entityManager.createNativeQuery(sql); - try { - LOG.debug("cleanup table: {}", sql); - LOG.debug("cleaned table: {}; deleted {} records", sql, query.executeUpdate()); - } catch (final Exception ex) { - LOG.error(String.format("error on executing cleanup statement '%s'", sql), ex); - throw ex; - } - } - } - - LOG.debug("Data clean up is finished..."); - } finally { - if (isMySql) { - // enable foreign key check again! - entityManager.createNativeQuery("SET FOREIGN_KEY_CHECKS = 1").executeUpdate(); - } - } - } - } - - /** - * @return a generated IPv4 address string. - */ - private static URI generateIPAddress() { - final Random r = new Random(); - return IpUtil - .createHttpUri(r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256)); - } - - private RepositoryDataGenerator() { - super(); - } - -} diff --git a/hawkbit-rest-core/pom.xml b/hawkbit-rest-core/pom.xml index a4a421f0d..bb511839c 100644 --- a/hawkbit-rest-core/pom.xml +++ b/hawkbit-rest-core/pom.xml @@ -23,7 +23,12 @@ org.eclipse.hawkbit - hawkbit-repository + hawkbit-repository-api + ${project.version} + + + org.eclipse.hawkbit + hawkbit-repository-jpa ${project.version} @@ -32,6 +37,14 @@ ${project.version} + + com.fasterxml.jackson.core + jackson-core + + + com.fasterxml.jackson.core + jackson-databind + javax.servlet javax.servlet-api @@ -44,17 +57,17 @@ + + org.eclipse.hawkbit + hawkbit-repository-test + ${project.version} + test + org.easytesting fest-assert test - - - org.eclipse.hawkbit - hawkbit-repository - ${project.version} - tests - + ru.yandex.qatools.allure allure-junit-adaptor diff --git a/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/RestResourceConversionHelper.java b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/RestResourceConversionHelper.java index 181ccc1f8..875152e0e 100644 --- a/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/RestResourceConversionHelper.java +++ b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/RestResourceConversionHelper.java @@ -22,7 +22,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.hawkbit.artifact.repository.model.DbArtifact; -import org.eclipse.hawkbit.cache.CacheWriteNotify; +import org.eclipse.hawkbit.repository.ControllerManagement; import org.eclipse.hawkbit.repository.model.LocalArtifact; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -84,7 +84,7 @@ public final class RestResourceConversionHelper { * from the client * @param file * to be write to the client response - * @param cacheWriteNotify + * @param controllerManagement * to write progress updates to * @param statusId * of the UpdateActionStatus @@ -95,9 +95,9 @@ public final class RestResourceConversionHelper { */ public static ResponseEntity writeFileResponse(final LocalArtifact artifact, final HttpServletResponse response, final HttpServletRequest request, final DbArtifact file, - final CacheWriteNotify cacheWriteNotify, final Long statusId) { + final ControllerManagement controllerManagement, final Long statusId) { - ResponseEntity result = null; + ResponseEntity result; final String etag = artifact.getSha1Hash(); final Long lastModified = artifact.getLastModifiedAt() != null ? artifact.getLastModifiedAt() @@ -143,19 +143,19 @@ public final class RestResourceConversionHelper { // full request - no range if (ranges.isEmpty() || ranges.get(0).equals(full)) { LOG.debug("filename ({}) results into a full request: ", artifact.getFilename()); - fullfileRequest(artifact, response, file, cacheWriteNotify, statusId, full); + fullfileRequest(artifact, response, file, controllerManagement, statusId, full); result = new ResponseEntity<>(HttpStatus.OK); } // standard range request else if (ranges.size() == 1) { LOG.debug("filename ({}) results into a standard range request: ", artifact.getFilename()); - standardRangeRequest(artifact, response, file, cacheWriteNotify, statusId, ranges); + standardRangeRequest(artifact, response, file, controllerManagement, statusId, ranges); result = new ResponseEntity<>(HttpStatus.PARTIAL_CONTENT); } // multipart range request else { LOG.debug("filename ({}) results into a multipart range request: ", artifact.getFilename()); - multipartRangeRequest(artifact, response, file, cacheWriteNotify, statusId, ranges); + multipartRangeRequest(artifact, response, file, controllerManagement, statusId, ranges); result = new ResponseEntity<>(HttpStatus.PARTIAL_CONTENT); } @@ -164,14 +164,15 @@ public final class RestResourceConversionHelper { } private static void fullfileRequest(final LocalArtifact artifact, final HttpServletResponse response, - final DbArtifact file, final CacheWriteNotify cacheWriteNotify, final Long statusId, final ByteRange full) { + final DbArtifact file, final ControllerManagement controllerManagement, final Long statusId, + final ByteRange full) { final ByteRange r = full; response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes " + r.getStart() + "-" + r.getEnd() + "/" + r.getTotal()); response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(r.getLength())); try { - copyStreams(file.getFileInputStream(), response.getOutputStream(), cacheWriteNotify, statusId, r.getStart(), - r.getLength()); + copyStreams(file.getFileInputStream(), response.getOutputStream(), controllerManagement, statusId, + r.getStart(), r.getLength()); } catch (final IOException e) { LOG.error("fullfileRequest of file ({}) failed!", artifact.getFilename(), e); throw new FileSteamingFailedException(artifact.getFilename()); @@ -231,7 +232,7 @@ public final class RestResourceConversionHelper { } private static void multipartRangeRequest(final LocalArtifact artifact, final HttpServletResponse response, - final DbArtifact file, final CacheWriteNotify cacheWriteNotify, final Long statusId, + final DbArtifact file, final ControllerManagement controllerManagement, final Long statusId, final List ranges) { response.setContentType("multipart/byteranges; boundary=" + ByteRange.MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); @@ -245,7 +246,7 @@ public final class RestResourceConversionHelper { .println("Content-Range: bytes " + r.getStart() + "-" + r.getEnd() + "/" + r.getTotal()); // Copy single part range of multi part range. - copyStreams(file.getFileInputStream(), response.getOutputStream(), cacheWriteNotify, statusId, + copyStreams(file.getFileInputStream(), response.getOutputStream(), controllerManagement, statusId, r.getStart(), r.getLength()); } @@ -259,7 +260,7 @@ public final class RestResourceConversionHelper { } private static void standardRangeRequest(final LocalArtifact artifact, final HttpServletResponse response, - final DbArtifact file, final CacheWriteNotify cacheWriteNotify, final Long statusId, + final DbArtifact file, final ControllerManagement controllerManagement, final Long statusId, final List ranges) { final ByteRange r = ranges.get(0); response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes " + r.getStart() + "-" + r.getEnd() + "/" + r.getTotal()); @@ -267,8 +268,8 @@ public final class RestResourceConversionHelper { response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); try { - copyStreams(file.getFileInputStream(), response.getOutputStream(), cacheWriteNotify, statusId, r.getStart(), - r.getLength()); + copyStreams(file.getFileInputStream(), response.getOutputStream(), controllerManagement, statusId, + r.getStart(), r.getLength()); } catch (final IOException e) { LOG.error("standardRangeRequest of file ({}) failed!", artifact.getFilename(), e); throw new FileSteamingFailedException(artifact.getFilename()); @@ -276,7 +277,7 @@ public final class RestResourceConversionHelper { } private static long copyStreams(final InputStream from, final OutputStream to, - final CacheWriteNotify cacheWriteNotify, final Long statusId, final long start, final long length) + final ControllerManagement controllerManagement, final Long statusId, final long start, final long length) throws IOException { checkNotNull(from); checkNotNull(to); @@ -309,13 +310,13 @@ public final class RestResourceConversionHelper { toContinue = false; } - if (cacheWriteNotify != null) { + if (controllerManagement != null) { final int newPercent = DoubleMath.roundToInt(total * 100.0 / length, RoundingMode.DOWN); // every 10 percent an event if (newPercent == 100 || newPercent > progressPercent + 10) { progressPercent = newPercent; - cacheWriteNotify.downloadProgressPercent(statusId, progressPercent); + controllerManagement.downloadProgressPercent(statusId, progressPercent); } } } diff --git a/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/AbstractRestIntegrationTest.java b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/AbstractRestIntegrationTest.java index 38f36859b..14ba8556e 100644 --- a/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/AbstractRestIntegrationTest.java +++ b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/AbstractRestIntegrationTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.rest; -import org.eclipse.hawkbit.AbstractIntegrationTest; +import org.eclipse.hawkbit.repository.util.AbstractIntegrationTest; import org.eclipse.hawkbit.rest.configuration.RestConfiguration; import org.eclipse.hawkbit.rest.util.FilterHttpResponse; import org.springframework.beans.factory.annotation.Autowired; @@ -18,7 +18,8 @@ import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder; /** * Abstract Test for Rest tests. */ -@SpringApplicationConfiguration(classes = { RestConfiguration.class }) +@SpringApplicationConfiguration(classes = { RestConfiguration.class, + org.eclipse.hawkbit.RepositoryApplicationConfiguration.class }) public abstract class AbstractRestIntegrationTest extends AbstractIntegrationTest { @Autowired @@ -29,5 +30,4 @@ public abstract class AbstractRestIntegrationTest extends AbstractIntegrationTes final DefaultMockMvcBuilder createMvcWebAppContext = super.createMvcWebAppContext(); return createMvcWebAppContext.addFilter(filterHttpResponse); } - } diff --git a/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/AbstractRestIntegrationTestWithMongoDB.java b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/AbstractRestIntegrationTestWithMongoDB.java index 9a25eb631..4d952434d 100644 --- a/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/AbstractRestIntegrationTestWithMongoDB.java +++ b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/AbstractRestIntegrationTestWithMongoDB.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.rest; -import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB; +import org.eclipse.hawkbit.repository.util.AbstractIntegrationTestWithMongoDB; import org.eclipse.hawkbit.rest.configuration.RestConfiguration; import org.eclipse.hawkbit.rest.util.FilterHttpResponse; import org.springframework.beans.factory.annotation.Autowired; @@ -18,7 +18,8 @@ import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder; /** * Abstract Test for Rest tests. */ -@SpringApplicationConfiguration(classes = { RestConfiguration.class }) +@SpringApplicationConfiguration(classes = { RestConfiguration.class, + org.eclipse.hawkbit.RepositoryApplicationConfiguration.class }) public abstract class AbstractRestIntegrationTestWithMongoDB extends AbstractIntegrationTestWithMongoDB { @Autowired @@ -26,7 +27,7 @@ public abstract class AbstractRestIntegrationTestWithMongoDB extends AbstractInt @Override protected DefaultMockMvcBuilder createMvcWebAppContext() { - DefaultMockMvcBuilder createMvcWebAppContext = super.createMvcWebAppContext(); + final DefaultMockMvcBuilder createMvcWebAppContext = super.createMvcWebAppContext(); return createMvcWebAppContext.addFilter(filterHttpResponse); } } diff --git a/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/json/model/ExceptionInfoTest.java b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/json/model/ExceptionInfoTest.java index 263bb75c5..901702795 100644 --- a/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/json/model/ExceptionInfoTest.java +++ b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/json/model/ExceptionInfoTest.java @@ -13,7 +13,6 @@ import static org.fest.assertions.Assertions.assertThat; import java.util.ArrayList; import java.util.List; -import org.eclipse.hawkbit.rest.json.model.ExceptionInfo; import org.junit.Test; import ru.yandex.qatools.allure.annotations.Description; diff --git a/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/JsonBuilder.java b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/JsonBuilder.java index b73320f0e..f67f15815 100644 --- a/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/JsonBuilder.java +++ b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/JsonBuilder.java @@ -16,7 +16,7 @@ import java.util.stream.Collectors; import org.apache.commons.lang3.RandomStringUtils; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetType; -import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupConditions; +import org.eclipse.hawkbit.repository.model.RolloutGroupConditions; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.eclipse.hawkbit.repository.model.Target; diff --git a/hawkbit-security-core/pom.xml b/hawkbit-security-core/pom.xml index a3b262726..a9b2347b6 100644 --- a/hawkbit-security-core/pom.xml +++ b/hawkbit-security-core/pom.xml @@ -21,7 +21,7 @@ - + org.eclipse.hawkbit hawkbit-core ${project.version} diff --git a/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/im/authentication/SpPermission.java b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/im/authentication/SpPermission.java index d15501fda..ce6bc7c40 100644 --- a/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/im/authentication/SpPermission.java +++ b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/im/authentication/SpPermission.java @@ -372,6 +372,15 @@ public final class SpPermission { public static final String HAS_AUTH_ROLLOUT_MANAGEMENT_READ = HAS_AUTH_PREFIX + ROLLOUT_MANAGEMENT + HAS_AUTH_SUFFIX; + /** + * Spring security eval hasAuthority expression to check if spring + * context contains {@link SpPermission#ROLLOUT_MANAGEMENT} and + * {@link SpPermission#READ_TARGET} + */ + public static final String HAS_AUTH_ROLLOUT_MANAGEMENT_READ_AND_TARGET_READ = HAS_AUTH_PREFIX + + ROLLOUT_MANAGEMENT + HAS_AUTH_SUFFIX + HAS_AUTH_AND + HAS_AUTH_PREFIX + READ_TARGET + + HAS_AUTH_SUFFIX;; + /** * Spring security eval hasAuthority expression to check if spring * context contains {@link SpPermission#ROLLOUT_MANAGEMENT} and diff --git a/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/SystemSecurityContext.java b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/SystemSecurityContext.java index f849eb541..78fb5818d 100644 --- a/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/SystemSecurityContext.java +++ b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/SystemSecurityContext.java @@ -64,6 +64,8 @@ public class SystemSecurityContext { * the callable to call within the system security context * @return the return value of the {@link Callable#call()} method. */ + // Exception squid:S2221 - Callable declares Exception + @SuppressWarnings("squid:S2221") public T runAsSystem(final Callable callable) { final SecurityContext oldContext = SecurityContextHolder.getContext(); try { diff --git a/hawkbit-security-integration/pom.xml b/hawkbit-security-integration/pom.xml index c17317b3d..455e3ece1 100644 --- a/hawkbit-security-integration/pom.xml +++ b/hawkbit-security-integration/pom.xml @@ -23,7 +23,7 @@ org.eclipse.hawkbit - hawkbit-repository + hawkbit-repository-api ${project.version} @@ -37,6 +37,12 @@ + + org.eclipse.hawkbit + hawkbit-repository-jpa + ${project.version} + test + junit junit diff --git a/hawkbit-ui/pom.xml b/hawkbit-ui/pom.xml index 6a3f76df6..08d225c62 100644 --- a/hawkbit-ui/pom.xml +++ b/hawkbit-ui/pom.xml @@ -168,7 +168,7 @@ org.eclipse.hawkbit - hawkbit-repository + hawkbit-repository-api ${project.version} @@ -246,6 +246,12 @@ + + org.eclipse.hawkbit + hawkbit-repository-jpa + ${project.version} + test + org.mockito mockito-core @@ -271,5 +277,10 @@ allure-junit-adaptor test + + org.scala-lang + scala-library + 2.10.4 + \ No newline at end of file diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/HawkbitEventProvider.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/HawkbitEventProvider.java index 4358bb734..cca4bdd4c 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/HawkbitEventProvider.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/HawkbitEventProvider.java @@ -11,18 +11,18 @@ package org.eclipse.hawkbit.ui; import java.util.HashSet; import java.util.Set; -import org.eclipse.hawkbit.eventbus.event.DistributionSetTagCreatedBulkEvent; -import org.eclipse.hawkbit.eventbus.event.DistributionSetTagDeletedEvent; -import org.eclipse.hawkbit.eventbus.event.DistributionSetTagUpdateEvent; import org.eclipse.hawkbit.eventbus.event.Event; -import org.eclipse.hawkbit.eventbus.event.RolloutChangeEvent; -import org.eclipse.hawkbit.eventbus.event.RolloutGroupChangeEvent; -import org.eclipse.hawkbit.eventbus.event.TargetCreatedEvent; import org.eclipse.hawkbit.eventbus.event.TargetDeletedEvent; -import org.eclipse.hawkbit.eventbus.event.TargetInfoUpdateEvent; -import org.eclipse.hawkbit.eventbus.event.TargetTagCreatedBulkEvent; -import org.eclipse.hawkbit.eventbus.event.TargetTagDeletedEvent; -import org.eclipse.hawkbit.eventbus.event.TargetTagUpdateEvent; +import org.eclipse.hawkbit.repository.eventbus.event.DistributionSetTagCreatedBulkEvent; +import org.eclipse.hawkbit.repository.eventbus.event.DistributionSetTagDeletedEvent; +import org.eclipse.hawkbit.repository.eventbus.event.DistributionSetTagUpdateEvent; +import org.eclipse.hawkbit.repository.eventbus.event.RolloutChangeEvent; +import org.eclipse.hawkbit.repository.eventbus.event.RolloutGroupChangeEvent; +import org.eclipse.hawkbit.repository.eventbus.event.TargetCreatedEvent; +import org.eclipse.hawkbit.repository.eventbus.event.TargetInfoUpdateEvent; +import org.eclipse.hawkbit.repository.eventbus.event.TargetTagCreatedBulkEvent; +import org.eclipse.hawkbit.repository.eventbus.event.TargetTagDeletedEvent; +import org.eclipse.hawkbit.repository.eventbus.event.TargetTagUpdateEvent; /** * The default hawkbit event provider. diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/details/ArtifactBeanQuery.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/details/ArtifactBeanQuery.java index 2fa3763fd..80e8a2f4f 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/details/ArtifactBeanQuery.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/details/ArtifactBeanQuery.java @@ -12,6 +12,7 @@ import java.util.List; import java.util.Map; import org.eclipse.hawkbit.repository.ArtifactManagement; +import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.model.LocalArtifact; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; @@ -37,6 +38,7 @@ public class ArtifactBeanQuery extends AbstractBeanQuery { private static final long serialVersionUID = -333786310371208962L; private Sort sort = new Sort(Direction.DESC, "filename"); private transient ArtifactManagement artifactManagement = null; + private transient EntityFactory entityFactory; private transient Page firstPagetArtifacts = null; private Long baseSwModuleId = null; @@ -72,7 +74,7 @@ public class ArtifactBeanQuery extends AbstractBeanQuery { @Override protected LocalArtifact constructBean() { - return new LocalArtifact(); + return entityFactory.generateLocalArtifact(); } @Override @@ -115,4 +117,11 @@ public class ArtifactBeanQuery extends AbstractBeanQuery { } return artifactManagement; } + + private EntityFactory getEntityFactory() { + if (entityFactory == null) { + entityFactory = SpringContextHelper.getBean(EntityFactory.class); + } + return entityFactory; + } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadArtifactUIEvent.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadArtifactUIEvent.java index 3d75b67a7..e1fe4e07f 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadArtifactUIEvent.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadArtifactUIEvent.java @@ -15,6 +15,5 @@ package org.eclipse.hawkbit.ui.artifacts.event; * */ public enum UploadArtifactUIEvent { - - SHOW_DROP_HINTS, HIDE_DROP_HINTS, SOFTWARE_DRAG_START, SOFTWARE_TYPE_DRAG_START, UPDATE_UPLOAD_COUNT, ENABLE_PROCESS_BUTTON, HIDE_FILTER_BY_TYPE, SHOW_FILTER_BY_TYPE, DISCARD_DELETE_SOFTWARE, DISCARD_ALL_DELETE_SOFTWARE, DELETED_ALL_SOFWARE, DISABLE_PROCESS_BUTTON, DISCARD_DELETE_SOFTWARE_TYPE, DISCARD_ALL_DELETE_SOFTWARE_TYPE, DELETED_ALL_SOFWARE_TYPE + SHOW_DROP_HINTS, HIDE_DROP_HINTS, SOFTWARE_DRAG_START, SOFTWARE_TYPE_DRAG_START, UPDATE_UPLOAD_COUNT, HIDE_FILTER_BY_TYPE, SHOW_FILTER_BY_TYPE, DISCARD_DELETE_SOFTWARE, DISCARD_ALL_DELETE_SOFTWARE, DELETED_ALL_SOFWARE, DISCARD_DELETE_SOFTWARE_TYPE, DISCARD_ALL_DELETE_SOFTWARE_TYPE, DELETED_ALL_SOFWARE_TYPE, MINIMIZED_STATUS_POPUP, MAXIMIZED_STATUS_POPUP, UPLOAD_IN_PROGESS, ARTIFACT_RESULT_POPUP_CLOSED } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadFileStatus.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadFileStatus.java new file mode 100644 index 000000000..81b096c3e --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadFileStatus.java @@ -0,0 +1,70 @@ +/** + * 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.ui.artifacts.event; + +import java.io.Serializable; + +import org.eclipse.hawkbit.repository.model.SoftwareModule; + +/** + * + * Holds file and upload status details.Meta data sent with upload events. + * + */ +public class UploadFileStatus implements Serializable { + + private static final long serialVersionUID = -3599629192216760811L; + + private String fileName; + + private long contentLength; + + private long bytesRead; + + private String failureReason; + + private SoftwareModule softwareModule; + + public UploadFileStatus(String fileName) { + this.fileName = fileName; + } + + public UploadFileStatus(String fileName, long bytesRead, long contentLength,SoftwareModule softwareModule) { + this.fileName = fileName; + this.contentLength = contentLength; + this.bytesRead = bytesRead; + this.softwareModule = softwareModule; + } + + public UploadFileStatus(String fileName, String failureReason,SoftwareModule selectedSw) { + this.failureReason = failureReason; + this.fileName = fileName; + this.softwareModule = selectedSw; + } + + public String getFileName() { + return fileName; + } + + public long getContentLength() { + return contentLength; + } + + public long getBytesRead() { + return bytesRead; + } + + public String getFailureReason() { + return failureReason; + } + + public SoftwareModule getSoftwareModule() { + return softwareModule; + } +} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadStatusEvent.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadStatusEvent.java new file mode 100644 index 000000000..8a4da9f6d --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadStatusEvent.java @@ -0,0 +1,42 @@ +/** + * 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.ui.artifacts.event; +/** + * + * Holds the upload file status. + * + */ +public class UploadStatusEvent { + + public enum UploadStatusEventType { + UPLOAD_FAILED, UPLOAD_IN_PROGRESS, UPLOAD_STARTED, UPLOAD_FINISHED, UPLOAD_SUCCESSFUL, UPLOAD_STREAMING_FAILED, UPLOAD_STREAMING_FINISHED, ABORT_UPLOAD + } + + private UploadStatusEventType uploadProgressEventType; + + private UploadFileStatus uploadStatus; + + public UploadStatusEvent(UploadStatusEventType eventType, UploadFileStatus entity) { + this.uploadProgressEventType = eventType; + this.uploadStatus = entity; + } + + public UploadFileStatus getUploadStatus() { + return uploadStatus; + } + + public void setUploadStatus(UploadFileStatus uploadStatus) { + this.uploadStatus = uploadStatus; + } + + public UploadStatusEventType getUploadProgressEventType() { + return uploadProgressEventType; + } + +} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/ProxyBaseSoftwareModuleItem.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/ProxyBaseSoftwareModuleItem.java index 6e417435c..1559a9bec 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/ProxyBaseSoftwareModuleItem.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/ProxyBaseSoftwareModuleItem.java @@ -10,8 +10,6 @@ package org.eclipse.hawkbit.ui.artifacts.smtable; import java.security.SecureRandom; -import org.eclipse.hawkbit.repository.model.SoftwareModule; - /** * * Proxy for software module to display details in Software modules table. @@ -19,7 +17,7 @@ import org.eclipse.hawkbit.repository.model.SoftwareModule; * * */ -public class ProxyBaseSoftwareModuleItem extends SoftwareModule { +public class ProxyBaseSoftwareModuleItem { private static final long serialVersionUID = -1555306616599140635L; @@ -39,6 +37,11 @@ public class ProxyBaseSoftwareModuleItem extends SoftwareModule { private String modifiedByUser; + private String name; + private String version; + private String vendor; + private String description; + /** * Default constructor. */ @@ -47,6 +50,38 @@ public class ProxyBaseSoftwareModuleItem extends SoftwareModule { swId = RANDOM_OBJ.nextLong(); } + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public String getVersion() { + return version; + } + + public void setVersion(final String version) { + this.version = version; + } + + public String getVendor() { + return vendor; + } + + public void setVendor(final String vendor) { + this.vendor = vendor; + } + + public String getDescription() { + return description; + } + + public void setDescription(final String description) { + this.description = description; + } + public String getCreatedByUser() { return createdByUser; } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleAddUpdateWindow.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleAddUpdateWindow.java index cada22fce..6b1f23cf9 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleAddUpdateWindow.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleAddUpdateWindow.java @@ -10,6 +10,7 @@ package org.eclipse.hawkbit.ui.artifacts.smtable; import java.io.Serializable; +import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent; @@ -66,6 +67,9 @@ public class SoftwareModuleAddUpdateWindow implements Serializable { @Autowired private transient SoftwareManagement softwareManagement; + @Autowired + private transient EntityFactory entityFactory; + private Label madatoryLabel; private TextField nameTextField; @@ -234,7 +238,7 @@ public class SoftwareModuleAddUpdateWindow implements Serializable { mainLayout.addComponent(hLayout); mainLayout.setComponentAlignment(hLayout, Alignment.MIDDLE_LEFT); mainLayout.addComponents(nameTextField, versionTextField, vendorTextField, descTextArea, buttonsLayout); - + /* add main layout to the window */ window = SPUIComponentProvider.getWindow(i18n.get("upload.caption.add.new.swmodule"), null, SPUIDefinitions.CREATE_UPDATE_WINDOW); @@ -277,8 +281,8 @@ public class SoftwareModuleAddUpdateWindow implements Serializable { uiNotifcation.displayValidationError( i18n.get("message.duplicate.softwaremodule", new Object[] { name, version })); } else { - final SoftwareModule newBaseSoftwareModule = HawkbitCommonUtil.addNewBaseSoftware(name, version, vendor, - softwareManagement.findSoftwareModuleTypeByName(type), description); + final SoftwareModule newBaseSoftwareModule = HawkbitCommonUtil.addNewBaseSoftware(entityFactory, name, + version, vendor, softwareManagement.findSoftwareModuleTypeByName(type), description); if (newBaseSoftwareModule != null) { /* display success message */ uiNotifcation.displaySuccess(i18n.get("message.save.success", new Object[] { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/CreateUpdateSoftwareTypeLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/CreateUpdateSoftwareTypeLayout.java index d061362c5..6cc0f1948 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/CreateUpdateSoftwareTypeLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/CreateUpdateSoftwareTypeLayout.java @@ -13,6 +13,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; @@ -93,6 +94,9 @@ public class CreateUpdateSoftwareTypeLayout extends CustomComponent implements C @Autowired private transient SoftwareManagement swTypeManagementService; + @Autowired + private transient EntityFactory entityFactory; + @Autowired private transient EventBus.SessionEventBus eventBus; @@ -625,8 +629,10 @@ public class CreateUpdateSoftwareTypeLayout extends CustomComponent implements C } if (null != typeNameValue && null != typeKeyValue) { - SoftwareModuleType newSWType = new SoftwareModuleType(typeKeyValue, typeNameValue, typeDescValue, - assignNumber, colorPicked); + SoftwareModuleType newSWType = entityFactory.generateSoftwareModuleType(typeKeyValue, typeNameValue, + typeDescValue, assignNumber); + newSWType.setColour(colorPicked); + if (null != typeDescValue) { newSWType.setDescription(typeDescValue); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/state/ArtifactUploadState.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/state/ArtifactUploadState.java index f82ce9ccf..5399e59c8 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/state/ArtifactUploadState.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/state/ArtifactUploadState.java @@ -9,14 +9,18 @@ package org.eclipse.hawkbit.ui.artifacts.state; import java.io.Serializable; +import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; import org.eclipse.hawkbit.repository.model.SoftwareModule; +import org.eclipse.hawkbit.ui.artifacts.upload.UploadStatusObject; import org.eclipse.hawkbit.ui.common.ManagmentEntityState; import org.springframework.beans.factory.annotation.Autowired; @@ -58,8 +62,61 @@ public class ArtifactUploadState implements ManagmentEntityState, Serializ private final Set selectedDeleteSWModuleTypes = new HashSet<>(); private boolean noDataAvilableSoftwareModule = Boolean.FALSE; + + private boolean isStatusPopupMinimized = Boolean.FALSE; + + private boolean isUploadCompleted = Boolean.FALSE; + + private List uploadedFileStatusList = new ArrayList<>(); + + private final AtomicInteger numberOfFileUploadsExpected = new AtomicInteger(); - /** + private final AtomicInteger numberOfFilesActuallyUpload = new AtomicInteger(); + + private final AtomicInteger numberOfFileUploadsFailed = new AtomicInteger(); + + public AtomicInteger getNumberOfFileUploadsFailed() { + return numberOfFileUploadsFailed; + } + + public AtomicInteger getNumberOfFilesActuallyUpload() { + return numberOfFilesActuallyUpload; + } + + public AtomicInteger getNumberOfFileUploadsExpected() { + return numberOfFileUploadsExpected; + } + + + public List getUploadedFileStatusList() { + return uploadedFileStatusList; + } + + public void setUploadedFileStatusList(List uploadedFileStatusList) { + this.uploadedFileStatusList = uploadedFileStatusList; + } + + public boolean isUploadCompleted() { + return isUploadCompleted; + } + + public void setUploadCompleted(boolean isUploadCompleted) { + this.isUploadCompleted = isUploadCompleted; + } + + + public void setStatusPopupMinimized(boolean isStatusPopupMinimized) { + this.isStatusPopupMinimized = isStatusPopupMinimized; + } + + public boolean isStatusPopupMinimized() { + return isStatusPopupMinimized; + } + + + + + /** * Set software. * * @return diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadConfirmationwindow.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadConfirmationwindow.java index 7e9479d9a..82bdc44c0 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadConfirmationwindow.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadConfirmationwindow.java @@ -544,7 +544,7 @@ public class UploadConfirmationwindow implements Button.ClickListener { if (event.getComponent().getId().equals(SPUIComponentIdProvider.UPLOAD_ARTIFACT_DETAILS_CLOSE)) { uploadConfrimationWindow.close(); } else if (event.getComponent().getId().equals(SPUIComponentIdProvider.UPLOAD_DISCARD_DETAILS_BUTTON)) { - uploadLayout.clearFileList(); + uploadLayout.clearUploadedFileDetails(); uploadConfrimationWindow.close(); } else if (event.getComponent().getId().equals(SPUIComponentIdProvider.UPLOAD_BUTTON)) { processArtifactUpload(); @@ -568,10 +568,10 @@ public class UploadConfirmationwindow implements Button.ClickListener { uploadDetailsTable.removeItem(((Button) event.getComponent()).getData()); uploadLayout.getFileSelected().remove(customFile); - uploadLayout.updateActionCount(); + uploadLayout.updateUploadCounts(); if (uploadDetailsTable.getItemIds().isEmpty()) { - uploadLayout.clearFileList(); uploadConfrimationWindow.close(); + uploadLayout.clearUploadedFileDetails(); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadHandler.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadHandler.java index d5c6759b5..78a6fd9a9 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadHandler.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadHandler.java @@ -11,13 +11,21 @@ package org.eclipse.hawkbit.ui.artifacts.upload; import java.io.IOException; import java.io.OutputStream; +import javax.annotation.PreDestroy; + import org.eclipse.hawkbit.repository.exception.ArtifactUploadFailedException; import org.eclipse.hawkbit.repository.model.SoftwareModule; -import org.eclipse.hawkbit.ui.artifacts.state.CustomFile; +import org.eclipse.hawkbit.ui.artifacts.event.UploadFileStatus; +import org.eclipse.hawkbit.ui.artifacts.event.UploadStatusEvent; +import org.eclipse.hawkbit.ui.artifacts.event.UploadStatusEvent.UploadStatusEventType; +import org.eclipse.hawkbit.ui.artifacts.state.ArtifactUploadState; import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SpringContextHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.vaadin.spring.events.EventBus; +import org.vaadin.spring.events.EventScope; +import org.vaadin.spring.events.annotation.EventBusListenerMethod; import com.vaadin.server.StreamVariable; import com.vaadin.ui.Upload; @@ -49,28 +57,53 @@ public class UploadHandler implements StreamVariable, Receiver, SucceededListene private final long fileSize; private final UploadLayout view; - private final UploadStatusInfoWindow infoWindow; private final long maxSize; private final Upload upload; private volatile String fileName = null; private volatile String mimeType = null; - private volatile boolean interrupted = false; + private volatile boolean streamingInterrupted = false; + private volatile boolean uploadInterrupted = false; + private volatile boolean aborted = false; + private String failureReason; private final I18N i18n; + private transient EventBus.SessionEventBus eventBus; + private final SoftwareModule selectedSw; + private SoftwareModule selectedSwForUpload; + private ArtifactUploadState artifactUploadState; - UploadHandler(final String fileName, final long fileSize, final UploadLayout view, - final UploadStatusInfoWindow infoWindow, final long maxSize, final Upload upload, final String mimeType) { + UploadHandler(final String fileName, final long fileSize, final UploadLayout view, final long maxSize, + final Upload upload, final String mimeType, SoftwareModule selectedSw) { super(); + this.aborted = false; this.fileName = fileName; this.fileSize = fileSize; this.view = view; - this.infoWindow = infoWindow; this.maxSize = maxSize; this.upload = upload; this.mimeType = mimeType; + this.selectedSw = selectedSw; this.i18n = SpringContextHelper.getBean(I18N.class); + this.eventBus = SpringContextHelper.getBean(EventBus.SessionEventBus.class); + this.artifactUploadState = SpringContextHelper.getBean(ArtifactUploadState.class); + eventBus.subscribe(this); + } + @PreDestroy + void destroy() { + /* + * It's good manners to do this, even though vaadin-spring will + * automatically unsubscribe when this UI is garbage collected. + */ + eventBus.unsubscribe(this); + } + + @EventBusListenerMethod(scope = EventScope.SESSION) + void onEvent(final UploadStatusEventType event) { + if (event == UploadStatusEventType.ABORT_UPLOAD) { + aborted = true; + } } /** @@ -81,11 +114,13 @@ public class UploadHandler implements StreamVariable, Receiver, SucceededListene @Override public final OutputStream getOutputStream() { try { - return view.saveUploadedFileDetails(fileName, fileSize, mimeType); + streamingInterrupted = false; + failureReason = null; + return view.saveUploadedFileDetails(fileName, fileSize, mimeType, selectedSw); } catch (final ArtifactUploadFailedException e) { LOG.error("Atifact upload failed {} ", e); failureReason = e.getMessage(); - interrupted = true; + streamingInterrupted = true; return new NullOutputStream(); } } @@ -98,23 +133,22 @@ public class UploadHandler implements StreamVariable, Receiver, SucceededListene */ @Override public OutputStream receiveUpload(final String fileName, final String mimeType) { + aborted = false; + failureReason = null; this.fileName = fileName; this.mimeType = mimeType; // reset has directory flag before upload view.setHasDirectory(false); try { - if (view.checkIfSoftwareModuleIsSelected()) { - if (view.checkForDuplicate(fileName)) { - view.showDuplicateMessage(); - } else { - view.increaseNumberOfFileUploadsExpected(); - return view.saveUploadedFileDetails(fileName, 0, mimeType); - } + if (view.checkIfSoftwareModuleIsSelected() && !view.checkForDuplicate(fileName, selectedSwForUpload)) { + view.increaseNumberOfFileUploadsExpected(); + return view.saveUploadedFileDetails(fileName, 0, mimeType, selectedSwForUpload); } } catch (final ArtifactUploadFailedException e) { LOG.error("Atifact upload failed {} ", e); failureReason = e.getMessage(); upload.interruptUpload(); + uploadInterrupted = true; } // if final validation fails ,final no upload ,return NullOutputStream return new NullOutputStream(); @@ -129,13 +163,8 @@ public class UploadHandler implements StreamVariable, Receiver, SucceededListene @Override public void uploadSucceeded(final SucceededEvent event) { LOG.debug("Streaming finished for file :{}", event.getFilename()); - view.updateFileSize(event.getFilename(), event.getLength()); - - // recorded that we now one more uploaded - view.increaseNumberOfFilesActuallyUpload(); - - // inform upload status window - infoWindow.uploadSucceeded(event.getFilename()); + eventBus.publish(this, new UploadStatusEvent(UploadStatusEventType.UPLOAD_SUCCESSFUL, new UploadFileStatus( + event.getFilename(), 0, event.getLength(), selectedSwForUpload))); } /** @@ -148,20 +177,8 @@ public class UploadHandler implements StreamVariable, Receiver, SucceededListene @Override public void streamingFinished(final StreamingEndEvent event) { LOG.debug("Streaming finished for file :{}", event.getFileName()); - // record that we now one more uploaded - view.increaseNumberOfFilesActuallyUpload(); - - // inform upload status window - infoWindow.uploadSucceeded(event.getFileName()); - - // check if we are finished - if (view.enableProcessBtn()) { - infoWindow.uploadSessionFinished(); - } - view.updateActionCount(); - - // display the duplicate message after streaming all files - view.displayDuplicateValidationMessage(); + eventBus.publish(this, new UploadStatusEvent(UploadStatusEventType.UPLOAD_STREAMING_FINISHED, + new UploadFileStatus(event.getFileName(), 0, event.getContentLength(), selectedSw))); } /** @@ -173,12 +190,8 @@ public class UploadHandler implements StreamVariable, Receiver, SucceededListene @Override public void uploadFinished(final FinishedEvent event) { LOG.debug("Upload finished for file :{}", event.getFilename()); - // check if we are finished - if (view.enableProcessBtn()) { - infoWindow.uploadSessionFinished(); - } - view.updateActionCount(); - + eventBus.publish(this, + new UploadStatusEvent(UploadStatusEventType.UPLOAD_FINISHED, new UploadFileStatus(event.getFilename()))); } /** @@ -189,7 +202,8 @@ public class UploadHandler implements StreamVariable, Receiver, SucceededListene @Override public void streamingStarted(final StreamingStartEvent event) { LOG.debug("Streaming started for file :{}", fileName); - infoWindow.uploadStarted(fileName); + eventBus.publish(this, new UploadStatusEvent(UploadStatusEventType.UPLOAD_STARTED, new UploadFileStatus( + fileName, 0, 0, selectedSw))); } /** @@ -199,14 +213,24 @@ public class UploadHandler implements StreamVariable, Receiver, SucceededListene */ @Override public void uploadStarted(final StartedEvent event) { - // single file session - if (view.isSoftwareModuleSelected() && !view.checkIfFileIsDuplicate(event.getFilename())) { - infoWindow.uploadSessionStarted(); - LOG.debug("Upload started for file :{}", event.getFilename()); - infoWindow.uploadStarted(event.getFilename()); - } else { + uploadInterrupted = false; + selectedSwForUpload = artifactUploadState.getSelectedBaseSoftwareModule().isPresent() ? artifactUploadState + .getSelectedBaseSoftwareModule().get() : null; + + if (view.isSoftwareModuleSelected()) { + // single file session + if (!view.checkIfFileIsDuplicate(event.getFilename(), selectedSwForUpload)) { + LOG.debug("Upload started for file :{}", event.getFilename()); + eventBus.publish(this, new UploadStatusEvent(UploadStatusEventType.UPLOAD_STARTED, + new UploadFileStatus(event.getFilename(), 0, 0, selectedSwForUpload))); + } + } + else { failureReason = i18n.get("message.upload.failed"); upload.interruptUpload(); + // actual interrupt will happen a bit late so setting the below + // flag + uploadInterrupted = true; } } @@ -227,21 +251,25 @@ public class UploadHandler implements StreamVariable, Receiver, SucceededListene */ @Override public void updateProgress(final long readBytes, final long contentLength) { - if (readBytes > maxSize || contentLength > maxSize) { - LOG.error("User tried to upload more than was allowed ({}).", maxSize); - view.decreaseNumberOfFileUploadsExpected(); - final SoftwareModule sw = view.getSoftwareModuleSelected(); - view.getFileSelected().remove(new CustomFile(fileName, sw.getName(), sw.getVersion())); - view.updateActionCount(); - failureReason = i18n.get("message.uploadedfile.size.exceeded", maxSize); - infoWindow.uploadFailed(fileName, failureReason); - upload.interruptUpload(); - interrupted = true; - return; + // Update progress is called event after upload interrupted in + // uploadStarted method + if (!uploadInterrupted) { + if (aborted) { + LOG.info("User aborted file upload for file : {}", fileName); + failureReason = i18n.get("message.uploadedfile.aborted"); + interruptFileUpload(); + return; + } + if (readBytes > maxSize || contentLength > maxSize) { + LOG.error("User tried to upload more than was allowed ({}).", maxSize); + failureReason = i18n.get("message.uploadedfile.size.exceeded", maxSize); + interruptFileUpload(); + return; + } + eventBus.publish(this, new UploadStatusEvent(UploadStatusEventType.UPLOAD_IN_PROGRESS, + new UploadFileStatus(fileName, readBytes, contentLength, selectedSwForUpload))); + LOG.info("Update progress - {} : {}", fileName, (double) readBytes / (double) contentLength); } - - infoWindow.updateProgress(fileName, readBytes, contentLength); - LOG.info("Update progress - {} : {}", fileName, (double) readBytes / (double) contentLength); } /** @@ -251,19 +279,20 @@ public class UploadHandler implements StreamVariable, Receiver, SucceededListene */ @Override public void onProgress(final StreamingProgressEvent event) { - if (event.getBytesReceived() > maxSize || event.getContentLength() > maxSize) { - LOG.error("User tried to upload more than was allowed ({}).", maxSize); - view.decreaseNumberOfFileUploadsExpected(); - final SoftwareModule sw = view.getSoftwareModuleSelected(); - view.getFileSelected().remove(new CustomFile(fileName, sw.getName(), sw.getVersion())); - view.updateActionCount(); - failureReason = i18n.get("message.uploadedfile.size.exceeded", maxSize); - infoWindow.uploadFailed(event.getFileName(), failureReason); - interrupted = true; + if (aborted) { + LOG.info("User aborted the upload for file : {}", event.getFileName()); + failureReason = i18n.get("message.uploadedfile.aborted"); + interruptFileStreaming(); return; } - - infoWindow.updateProgress(event.getFileName(), event.getBytesReceived(), event.getContentLength()); + if (event.getBytesReceived() > maxSize || event.getContentLength() > maxSize) { + LOG.error("User tried to upload more than was allowed ({}).", maxSize); + failureReason = i18n.get("message.uploadedfile.size.exceeded", maxSize); + interruptFileStreaming(); + return; + } + eventBus.publish(this, new UploadStatusEvent(UploadStatusEventType.UPLOAD_IN_PROGRESS, new UploadFileStatus( + fileName, event.getBytesReceived(), event.getContentLength(), selectedSw))); // Logging to solve sonar issue LOG.trace("Streaming in progress for file :{}", event.getFileName()); } @@ -276,19 +305,16 @@ public class UploadHandler implements StreamVariable, Receiver, SucceededListene */ @Override public void streamingFailed(final StreamingErrorEvent event) { - LOG.info("Streaming failed for file :{}", event.getFileName()); - view.decreaseNumberOfFileUploadsExpected(); - final SoftwareModule sw = view.getSoftwareModuleSelected(); - view.getFileSelected().remove(new CustomFile(fileName, sw.getName(), sw.getVersion())); - view.updateActionCount(); - infoWindow.uploadFailed(event.getFileName(), failureReason); - // check if we are finished - if (view.enableProcessBtn()) { - infoWindow.uploadSessionFinished(); + if (failureReason == null) { + failureReason = event.getException().getMessage(); } - view.displayDuplicateValidationMessage(); + eventBus.publish(this, new UploadStatusEvent(UploadStatusEventType.UPLOAD_STREAMING_FAILED, + new UploadFileStatus(fileName, failureReason, selectedSw))); - LOG.info("Streaming failed due to :{}", event.getException()); + if (!aborted) { + LOG.info("Streaming failed for file :{}", event.getFileName()); + LOG.info("Streaming failed due to :{}", event.getException()); + } } /** @@ -298,20 +324,21 @@ public class UploadHandler implements StreamVariable, Receiver, SucceededListene */ @Override public void uploadFailed(final FailedEvent event) { - LOG.info("Upload failed for file :{}", event.getFilename()); - view.decreaseNumberOfFileUploadsExpected(); /** - * If upload interrupted because of duplicate file,do not remove the - * file already in upload list - **/ - if (!view.getDuplicateFileNamesList().isEmpty()) { - final SoftwareModule sw = view.getSoftwareModuleSelected(); - view.getFileSelected().remove(new CustomFile(fileName, sw.getName(), sw.getVersion())); + * If upload failed due to no selected software UPLOAD_FAILED event need + * not be published. + */ + if (selectedSwForUpload != null) { + if (failureReason == null) { + failureReason = event.getReason().getMessage(); + } + eventBus.publish(this, new UploadStatusEvent(UploadStatusEventType.UPLOAD_FAILED, new UploadFileStatus( + fileName, failureReason, selectedSwForUpload))); + if (!aborted) { + LOG.info("Upload failed for file :{}", event.getFilename()); + LOG.info("Upload failed for file :{}", event.getReason()); + } } - view.updateActionCount(); - infoWindow.uploadFailed(event.getFilename(), failureReason); - LOG.info("Upload failed for file :{}", event.getReason()); - } /** @@ -319,7 +346,7 @@ public class UploadHandler implements StreamVariable, Receiver, SucceededListene */ @Override public boolean isInterrupted() { - return interrupted; + return streamingInterrupted; } private static class NullOutputStream extends OutputStream { @@ -365,4 +392,13 @@ public class UploadHandler implements StreamVariable, Receiver, SucceededListene return true; } + private void interruptFileStreaming() { + streamingInterrupted = true; + } + + private void interruptFileUpload() { + upload.interruptUpload(); + uploadInterrupted = true; + } + } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadLayout.java index ad406b297..05c175ead 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadLayout.java @@ -16,7 +16,6 @@ import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; @@ -26,6 +25,8 @@ import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent.SoftwareModuleEventType; import org.eclipse.hawkbit.ui.artifacts.event.UploadArtifactUIEvent; +import org.eclipse.hawkbit.ui.artifacts.event.UploadStatusEvent; +import org.eclipse.hawkbit.ui.artifacts.event.UploadStatusEvent.UploadStatusEventType; import org.eclipse.hawkbit.ui.artifacts.state.ArtifactUploadState; import org.eclipse.hawkbit.ui.artifacts.state.CustomFile; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; @@ -97,10 +98,6 @@ public class UploadLayout extends VerticalLayout { @Autowired private transient SPInfo spInfo; - private final AtomicInteger numberOfFileUploadsExpected = new AtomicInteger(); - - private final AtomicInteger numberOfFilesActuallyUpload = new AtomicInteger(); - private final List duplicateFileNamesList = new ArrayList<>(); private Button processBtn; @@ -119,6 +116,8 @@ public class UploadLayout extends VerticalLayout { private Boolean hasDirectory = Boolean.FALSE; + private Button uploadStatusButton; + /** * Initialize the upload layout. */ @@ -126,13 +125,52 @@ public class UploadLayout extends VerticalLayout { void init() { createComponents(); buildLayout(); - updateActionCount(); + restoreState(); eventBus.subscribe(this); ui = UI.getCurrent(); } - private void createComponents() { + @EventBusListenerMethod(scope = EventScope.SESSION) + void onEvent(final UploadArtifactUIEvent event) { + if (event == UploadArtifactUIEvent.DELETED_ALL_SOFWARE) { + ui.access(() -> updateActionCount()); + } else if (event == UploadArtifactUIEvent.MINIMIZED_STATUS_POPUP) { + ui.access(() -> showUploadStatusButton()); + } else if (event == UploadArtifactUIEvent.MAXIMIZED_STATUS_POPUP) { + ui.access(() -> maximizeStatusPopup()); + } else if (event == UploadArtifactUIEvent.ARTIFACT_RESULT_POPUP_CLOSED) { + ui.access(() -> closeUploadStatusPopup()); + } + } + @EventBusListenerMethod(scope = EventScope.SESSION) + void onEvent(final UploadStatusEvent event) { + if (event.getUploadProgressEventType() == UploadStatusEventType.UPLOAD_STARTED) { + ui.access(() -> onStartOfUpload()); + } else if (event.getUploadProgressEventType() == UploadStatusEventType.UPLOAD_FAILED) { + ui.access(() -> onUploadFailure(event)); + } else if (event.getUploadProgressEventType() == UploadStatusEventType.UPLOAD_FINISHED) { + ui.access(() -> onUploadCompletion()); + } else if (event.getUploadProgressEventType() == UploadStatusEventType.UPLOAD_SUCCESSFUL) { + ui.access(() -> onUploadSuccess(event)); + } else if (event.getUploadProgressEventType() == UploadStatusEventType.UPLOAD_STREAMING_FAILED) { + ui.access(() -> onUploadStreamingFailure(event)); + } else if (event.getUploadProgressEventType() == UploadStatusEventType.UPLOAD_STREAMING_FINISHED) { + ui.access(() -> onUploadStreamingSuccess()); + } + } + + @PreDestroy + void destroy() { + /* + * It's good manners to do this, even though vaadin-spring will + * automatically unsubscribe when this UI is garbage collected. + */ + eventBus.unsubscribe(this); + } + + private void createComponents() { + createUploadStatusButton(); createProcessButton(); createDiscardBtn(); } @@ -140,8 +178,8 @@ public class UploadLayout extends VerticalLayout { private void buildLayout() { final Upload upload = new Upload(); - final UploadHandler uploadHandler = new UploadHandler(null, 0, this, uploadInfoWindow, - spInfo.getMaxArtifactFileSize(), upload, null); + final UploadHandler uploadHandler = new UploadHandler(null, 0, this, spInfo.getMaxArtifactFileSize(), upload, + null, null); upload.setButtonCaption(i18n.get("upload.file")); upload.setImmediate(true); upload.setReceiver(uploadHandler); @@ -154,12 +192,15 @@ public class UploadLayout extends VerticalLayout { fileUploadLayout = new HorizontalLayout(); fileUploadLayout.setSpacing(true); + fileUploadLayout.addStyleName(SPUIStyleDefinitions.FOOTER_LAYOUT); fileUploadLayout.addComponent(upload); fileUploadLayout.setComponentAlignment(upload, Alignment.MIDDLE_LEFT); fileUploadLayout.addComponent(processBtn); fileUploadLayout.setComponentAlignment(processBtn, Alignment.MIDDLE_RIGHT); fileUploadLayout.addComponent(discardBtn); fileUploadLayout.setComponentAlignment(discardBtn, Alignment.MIDDLE_RIGHT); + fileUploadLayout.addComponent(uploadStatusButton); + fileUploadLayout.setComponentAlignment(uploadStatusButton, Alignment.MIDDLE_RIGHT); setMargin(false); /* create drag-drop wrapper for drop area */ @@ -167,7 +208,25 @@ public class UploadLayout extends VerticalLayout { dropAreaWrapper.setDropHandler(new DropAreahandler()); setSizeFull(); setSpacing(true); + } + private void restoreState() { + updateActionCount(); + + if (!artifactUploadState.getFileSelected().isEmpty() && artifactUploadState.isUploadCompleted()) { + processBtn.setEnabled(true); + } + if (artifactUploadState.isStatusPopupMinimized()) { + showUploadStatusButton(); + if (artifactUploadState.isUploadCompleted()) { + setUploadStatusButtonIconToFinished(); + } + } + if (artifactUploadState.isUploadCompleted()) { + artifactUploadState.getNumberOfFilesActuallyUpload().set(0); + artifactUploadState.getNumberOfFileUploadsExpected().set(0); + artifactUploadState.getNumberOfFileUploadsFailed().set(0); + } } public DragAndDropWrapper getDropAreaWrapper() { @@ -187,15 +246,16 @@ public class UploadLayout extends VerticalLayout { public void drop(final DragAndDropEvent event) { if (validate(event)) { final Html5File[] files = ((WrapperTransferable) event.getTransferable()).getFiles(); + // selected software module at the time of file drop is + // considered for upload + SoftwareModule selectedSw = artifactUploadState.getSelectedBaseSoftwareModule().get(); // reset the flag hasDirectory = Boolean.FALSE; for (final Html5File file : files) { - processFile(file); + processFile(file, selectedSw); } - if (numberOfFileUploadsExpected.get() > 0) { + if (artifactUploadState.getNumberOfFileUploadsExpected().get() > 0) { processBtn.setEnabled(false); - // reset before we start - uploadInfoWindow.uploadSessionStarted(); } else { // If the upload is not started, it signifies all // dropped files as either duplicate or directory.So @@ -205,20 +265,20 @@ public class UploadLayout extends VerticalLayout { } } - private void processFile(final Html5File file) { + private void processFile(final Html5File file, SoftwareModule selectedSw) { if (!isDirectory(file)) { - if (!checkForDuplicate(file.getFileName())) { - numberOfFileUploadsExpected.incrementAndGet(); - file.setStreamVariable(createStreamVariable(file)); + if (!checkForDuplicate(file.getFileName(), selectedSw)) { + artifactUploadState.getNumberOfFileUploadsExpected().incrementAndGet(); + file.setStreamVariable(createStreamVariable(file, selectedSw)); } } else { hasDirectory = Boolean.TRUE; } } - private StreamVariable createStreamVariable(final Html5File file) { - return new UploadHandler(file.getFileName(), file.getFileSize(), UploadLayout.this, uploadInfoWindow, - spInfo.getMaxArtifactFileSize(), null, file.getType()); + private StreamVariable createStreamVariable(final Html5File file, SoftwareModule selectedSw) { + return new UploadHandler(file.getFileName(), file.getFileSize(), UploadLayout.this, + spInfo.getMaxArtifactFileSize(), null, file.getType(), selectedSw); } private boolean isDirectory(final Html5File file) { @@ -270,9 +330,7 @@ public class UploadLayout extends VerticalLayout { processBtn.addStyleName(SPUIStyleDefinitions.ACTION_BUTTON); processBtn.addClickListener(event -> displayConfirmWindow(event)); processBtn.setHtmlContentAllowed(true); - if (artifactUploadState.getFileSelected().isEmpty()) { - processBtn.setEnabled(false); - } + processBtn.setEnabled(false); } private void createDiscardBtn() { @@ -284,23 +342,14 @@ public class UploadLayout extends VerticalLayout { discardBtn.addClickListener(event -> discardUploadData(event)); } - boolean checkForDuplicate(final String filename) { - final Boolean isDuplicate = checkIfFileIsDuplicate(filename); + boolean checkForDuplicate(final String filename, final SoftwareModule selectedSw) { + final Boolean isDuplicate = checkIfFileIsDuplicate(filename, selectedSw); if (isDuplicate) { getDuplicateFileNamesList().add(filename); } return isDuplicate; } - @EventBusListenerMethod(scope = EventScope.SESSION) - void toggleProcessButton(final UploadArtifactUIEvent event) { - if (event == UploadArtifactUIEvent.ENABLE_PROCESS_BUTTON) { - processBtn.setEnabled(true); - } else if (event == UploadArtifactUIEvent.DISABLE_PROCESS_BUTTON) { - processBtn.setEnabled(false); - } - } - /** * Save uploaded file details. * @@ -312,29 +361,29 @@ public class UploadLayout extends VerticalLayout { * file size * @param mimeType * the mimeType of the file + * @param selectedSw * @throws IOException * in case of upload errors */ - OutputStream saveUploadedFileDetails(final String name, final long size, final String mimeType) { + OutputStream saveUploadedFileDetails(final String name, final long size, final String mimeType, + SoftwareModule selectedSw) { File tempFile = null; try { tempFile = File.createTempFile("spUiArtifactUpload", null); final OutputStream out = new FileOutputStream(tempFile); - final SoftwareModule selectedSoftwareModule = artifactUploadState.getSelectedBaseSoftwareModule().get(); + final String currentBaseSoftwareModuleKey = HawkbitCommonUtil.getFormattedNameVersion(selectedSw.getName(), + selectedSw.getVersion()); - final String currentBaseSoftwareModuleKey = HawkbitCommonUtil - .getFormattedNameVersion(selectedSoftwareModule.getName(), selectedSoftwareModule.getVersion()); - - final CustomFile customFile = new CustomFile(name, size, tempFile.getAbsolutePath(), - selectedSoftwareModule.getName(), selectedSoftwareModule.getVersion(), mimeType); + final CustomFile customFile = new CustomFile(name, size, tempFile.getAbsolutePath(), selectedSw.getName(), + selectedSw.getVersion(), mimeType); artifactUploadState.getFileSelected().add(customFile); processBtn.setEnabled(false); if (!artifactUploadState.getBaseSwModuleList().keySet().contains(currentBaseSoftwareModuleKey)) { - artifactUploadState.getBaseSwModuleList().put(currentBaseSoftwareModuleKey, selectedSoftwareModule); + artifactUploadState.getBaseSwModuleList().put(currentBaseSoftwareModuleKey, selectedSw); } return out; } catch (final FileNotFoundException e) { @@ -344,6 +393,7 @@ public class UploadLayout extends VerticalLayout { LOG.error("Upload failed {}", e); throw new ArtifactUploadFailedException(i18n.get("message.upload.failed")); } + } Boolean validate(final DragAndDropEvent event) { @@ -378,13 +428,6 @@ public class UploadLayout extends VerticalLayout { return true; } - SoftwareModule getSoftwareModuleSelected() { - if (artifactUploadState.getSelectedBaseSoftwareModule().isPresent()) { - return artifactUploadState.getSelectedBaseSoftwareModule().get(); - } - return null; - } - Boolean isSoftwareModuleSelected() { if (!artifactUploadState.getSelectedBaseSwModuleId().isPresent()) { return false; @@ -400,11 +443,10 @@ public class UploadLayout extends VerticalLayout { * file name * @return Boolean */ - public Boolean checkIfFileIsDuplicate(final String name) { + public Boolean checkIfFileIsDuplicate(final String name, final SoftwareModule selectedSoftwareModule) { Boolean isDuplicate = false; - final SoftwareModule selectedSoftwareModule = artifactUploadState.getSelectedBaseSoftwareModule().get(); - final String currentBaseSoftwareModuleKey = HawkbitCommonUtil - .getFormattedNameVersion(selectedSoftwareModule.getName(), selectedSoftwareModule.getVersion()); + final String currentBaseSoftwareModuleKey = HawkbitCommonUtil.getFormattedNameVersion( + selectedSoftwareModule.getName(), selectedSoftwareModule.getVersion()); for (final CustomFile customFile : artifactUploadState.getFileSelected()) { final String fileSoftwareModuleKey = HawkbitCommonUtil.getFormattedNameVersion( @@ -418,7 +460,7 @@ public class UploadLayout extends VerticalLayout { } void decreaseNumberOfFileUploadsExpected() { - numberOfFileUploadsExpected.decrementAndGet(); + artifactUploadState.getNumberOfFileUploadsExpected().decrementAndGet(); } List getDuplicateFileNamesList() { @@ -439,8 +481,10 @@ public class UploadLayout extends VerticalLayout { void displayDuplicateValidationMessage() { // check if streaming of all dropped files are completed - if (numberOfFilesActuallyUpload.intValue() == numberOfFileUploadsExpected.intValue()) { + if (artifactUploadState.getNumberOfFilesActuallyUpload().intValue() == artifactUploadState + .getNumberOfFileUploadsExpected().intValue()) { displayCompositeMessage(); + duplicateFileNamesList.clear(); } } @@ -454,7 +498,6 @@ public class UploadLayout extends VerticalLayout { } else if (duplicateFileNamesList.size() > 1) { message.append(i18n.get("message.no.duplicateFiles")); } - duplicateFileNamesList.clear(); } return message.toString(); } @@ -464,13 +507,12 @@ public class UploadLayout extends VerticalLayout { } void increaseNumberOfFileUploadsExpected() { - numberOfFileUploadsExpected.incrementAndGet(); + artifactUploadState.getNumberOfFileUploadsExpected().incrementAndGet(); } - void updateFileSize(final String name, final long size) { - final SoftwareModule selectedSoftwareModule = artifactUploadState.getSelectedBaseSoftwareModule().get(); - final String currentBaseSoftwareModuleKey = HawkbitCommonUtil - .getFormattedNameVersion(selectedSoftwareModule.getName(), selectedSoftwareModule.getVersion()); + void updateFileSize(final String name, final long size, SoftwareModule selectedSoftwareModule) { + final String currentBaseSoftwareModuleKey = HawkbitCommonUtil.getFormattedNameVersion( + selectedSoftwareModule.getName(), selectedSoftwareModule.getVersion()); for (final CustomFile customFile : artifactUploadState.getFileSelected()) { final String fileSoftwareModuleKey = HawkbitCommonUtil.getFormattedNameVersion( @@ -483,17 +525,22 @@ public class UploadLayout extends VerticalLayout { } void increaseNumberOfFilesActuallyUpload() { - numberOfFilesActuallyUpload.incrementAndGet(); + artifactUploadState.getNumberOfFilesActuallyUpload().incrementAndGet(); + } + + void increaseNumberOfFileUploadsFailed() { + artifactUploadState.getNumberOfFileUploadsFailed().incrementAndGet(); } /** * Enable process button once upload is completed. */ boolean enableProcessBtn() { - if (numberOfFilesActuallyUpload.intValue() >= numberOfFileUploadsExpected.intValue()) { + if (artifactUploadState.getNumberOfFilesActuallyUpload().intValue() >= artifactUploadState + .getNumberOfFileUploadsExpected().intValue() && !getFileSelected().isEmpty()) { processBtn.setEnabled(true); - numberOfFileUploadsExpected.set(0); - numberOfFilesActuallyUpload.set(0); + artifactUploadState.getNumberOfFilesActuallyUpload().set(0); + artifactUploadState.getNumberOfFileUploadsExpected().set(0); return true; } return false; @@ -507,13 +554,23 @@ public class UploadLayout extends VerticalLayout { if (event.getButton().equals(discardBtn)) { if (artifactUploadState.getFileSelected().isEmpty()) { uiNotification.displayValidationError(i18n.get("message.error.noFileSelected")); - } else { - clearFileList(); + clearUploadedFileDetails(); } } } + protected void clearUploadedFileDetails() { + clearFileList(); + closeUploadStatusPopup(); + } + + private void closeUploadStatusPopup() { + uploadInfoWindow.clearWindow(); + hideUploadStatusButton(); + artifactUploadState.setStatusPopupMinimized(false); + } + /** * Clear details. */ @@ -529,19 +586,20 @@ public class UploadLayout extends VerticalLayout { processBtn.setCaption(SPUILabelDefinitions.PROCESS); /* disable when there is no files to upload. */ processBtn.setEnabled(false); - numberOfFileUploadsExpected.set(0); - numberOfFilesActuallyUpload.set(0); + artifactUploadState.getNumberOfFilesActuallyUpload().set(0); + artifactUploadState.getNumberOfFileUploadsExpected().set(0); + artifactUploadState.getNumberOfFileUploadsFailed().set(0); duplicateFileNamesList.clear(); } private void setConfirmationPopupHeightWidth(final float newWidth, final float newHeight) { if (currentUploadConfirmationwindow != null) { - currentUploadConfirmationwindow.getUploadArtifactDetails().setWidth(HawkbitCommonUtil - .getArtifactUploadPopupWidth(newWidth, SPUIDefinitions.MIN_UPLOAD_CONFIRMATION_POPUP_WIDTH), - Unit.PIXELS); - currentUploadConfirmationwindow.getUploadDetailsTable().setHeight(HawkbitCommonUtil - .getArtifactUploadPopupHeight(newHeight, SPUIDefinitions.MIN_UPLOAD_CONFIRMATION_POPUP_HEIGHT), - Unit.PIXELS); + currentUploadConfirmationwindow.getUploadArtifactDetails().setWidth( + HawkbitCommonUtil.getArtifactUploadPopupWidth(newWidth, + SPUIDefinitions.MIN_UPLOAD_CONFIRMATION_POPUP_WIDTH), Unit.PIXELS); + currentUploadConfirmationwindow.getUploadDetailsTable().setHeight( + HawkbitCommonUtil.getArtifactUploadPopupHeight(newHeight, + SPUIDefinitions.MIN_UPLOAD_CONFIRMATION_POPUP_HEIGHT), Unit.PIXELS); } } @@ -558,10 +616,12 @@ public class UploadLayout extends VerticalLayout { && currentUploadConfirmationwindow.getCurrentUploadResultWindow() != null) { final UploadResultWindow uploadResultWindow = currentUploadConfirmationwindow .getCurrentUploadResultWindow(); - uploadResultWindow.getUploadResultsWindow().setWidth(HawkbitCommonUtil.getArtifactUploadPopupWidth(newWidth, - SPUIDefinitions.MIN_UPLOAD_CONFIRMATION_POPUP_WIDTH), Unit.PIXELS); - uploadResultWindow.getUploadResultTable().setHeight(HawkbitCommonUtil.getArtifactUploadPopupHeight( - newHeight, SPUIDefinitions.MIN_UPLOAD_CONFIRMATION_POPUP_HEIGHT), Unit.PIXELS); + uploadResultWindow.getUploadResultsWindow().setWidth( + HawkbitCommonUtil.getArtifactUploadPopupWidth(newWidth, + SPUIDefinitions.MIN_UPLOAD_CONFIRMATION_POPUP_WIDTH), Unit.PIXELS); + uploadResultWindow.getUploadResultTable().setHeight( + HawkbitCommonUtil.getArtifactUploadPopupHeight(newHeight, + SPUIDefinitions.MIN_UPLOAD_CONFIRMATION_POPUP_HEIGHT), Unit.PIXELS); } } @@ -572,8 +632,8 @@ public class UploadLayout extends VerticalLayout { } else { currentUploadConfirmationwindow = new UploadConfirmationwindow(this, artifactUploadState); UI.getCurrent().addWindow(currentUploadConfirmationwindow.getUploadConfrimationWindow()); - setConfirmationPopupHeightWidth(Page.getCurrent().getBrowserWindowWidth(), - Page.getCurrent().getBrowserWindowHeight()); + setConfirmationPopupHeightWidth(Page.getCurrent().getBrowserWindowWidth(), Page.getCurrent() + .getBrowserWindowHeight()); } } } @@ -599,25 +659,101 @@ public class UploadLayout extends VerticalLayout { /** * @return */ - VerticalLayout getDropAreaLayout() { return dropAreaLayout; } - @EventBusListenerMethod(scope = EventScope.SESSION) - void onEvent(final UploadArtifactUIEvent event) { - if (event == UploadArtifactUIEvent.DELETED_ALL_SOFWARE) { - ui.access(() -> updateActionCount()); + private void onStartOfUpload() { + setUploadStatusButtonIconToInProgress(); + if (artifactUploadState.isStatusPopupMinimized()) { + updateStatusButtonCount(); } } - @PreDestroy - void destroy() { - /* - * It's good manners to do this, even though vaadin-spring will - * automatically unsubscribe when this UI is garbage collected. - */ - eventBus.unsubscribe(this); + private void onUploadStreamingSuccess() { + increaseNumberOfFilesActuallyUpload(); + updateUploadCounts(); + enableProcessBtn(); + if (isUploadComplete()) { + uploadInfoWindow.uploadSessionFinished(); + setUploadStatusButtonIconToFinished(); + } + // display the duplicate message after streaming all files + displayDuplicateValidationMessage(); + } + + private void onUploadStreamingFailure(UploadStatusEvent event) { + /** + * If upload interrupted because of duplicate file,do not remove the + * file already in upload list + **/ + if (getDuplicateFileNamesList().isEmpty() + || !getDuplicateFileNamesList().contains(event.getUploadStatus().getFileName())) { + final SoftwareModule sw = event.getUploadStatus().getSoftwareModule(); + if (sw != null) { + getFileSelected().remove( + new CustomFile(event.getUploadStatus().getFileName(), sw.getName(), sw.getVersion())); + } + // failed reason to be updated only if there is error other than + // duplicate file error + uploadInfoWindow.uploadFailed(event.getUploadStatus().getFileName(), event.getUploadStatus() + .getFailureReason(), event.getUploadStatus().getSoftwareModule()); + increaseNumberOfFileUploadsFailed(); + } + decreaseNumberOfFileUploadsExpected(); + updateUploadCounts(); + enableProcessBtn(); + // check if we are finished + if (isUploadComplete()) { + uploadInfoWindow.uploadSessionFinished(); + setUploadStatusButtonIconToFinished(); + } + displayDuplicateValidationMessage(); + } + + private void onUploadSuccess(UploadStatusEvent event) { + updateFileSize(event.getUploadStatus().getFileName(), event.getUploadStatus().getContentLength(), event + .getUploadStatus().getSoftwareModule()); + // recorded that we now one more uploaded + increaseNumberOfFilesActuallyUpload(); + } + + private void onUploadCompletion() { + // check if we are finished + if (isUploadComplete()) { + uploadInfoWindow.uploadSessionFinished(); + setUploadStatusButtonIconToFinished(); + displayDuplicateValidationMessage(); + } + updateUploadCounts(); + enableProcessBtn(); + } + + private boolean isUploadComplete() { + int uploadedCount = artifactUploadState.getNumberOfFilesActuallyUpload().intValue(); + int expectedUploadsCount = artifactUploadState.getNumberOfFileUploadsExpected().intValue(); + return uploadedCount == expectedUploadsCount; + } + + private void onUploadFailure(final UploadStatusEvent event) { + /** + * If upload interrupted because of duplicate file,do not remove the + * file already in upload list + **/ + if (getDuplicateFileNamesList().isEmpty() + || !getDuplicateFileNamesList().contains(event.getUploadStatus().getFileName())) { + final SoftwareModule sw = event.getUploadStatus().getSoftwareModule(); + if (sw != null) { + getFileSelected().remove( + new CustomFile(event.getUploadStatus().getFileName(), sw.getName(), sw.getVersion())); + } + // failed reason to be updated only if there is error other than + // duplicate file error + uploadInfoWindow.uploadFailed(event.getUploadStatus().getFileName(), event.getUploadStatus() + .getFailureReason(), event.getUploadStatus().getSoftwareModule()); + increaseNumberOfFileUploadsFailed(); + decreaseNumberOfFileUploadsExpected(); + } } /** @@ -637,8 +773,8 @@ public class UploadLayout extends VerticalLayout { * @param selectedBaseSoftwareModule */ public void refreshArtifactDetailsLayout(final SoftwareModule selectedBaseSoftwareModule) { - eventBus.publish(this, - new SoftwareModuleEvent(SoftwareModuleEventType.ARTIFACTS_CHANGED, selectedBaseSoftwareModule)); + eventBus.publish(this, new SoftwareModuleEvent(SoftwareModuleEventType.ARTIFACTS_CHANGED, + selectedBaseSoftwareModule)); } /** @@ -655,4 +791,79 @@ public class UploadLayout extends VerticalLayout { public void setHasDirectory(final Boolean hasDirectory) { this.hasDirectory = hasDirectory; } + + private void createUploadStatusButton() { + uploadStatusButton = SPUIComponentProvider.getButton(SPUIComponentIdProvider.UPLOAD_STATUS_BUTTON, "", "", "", + false, null, SPUIButtonStyleSmall.class); + uploadStatusButton.setStyleName(SPUIStyleDefinitions.ACTION_BUTTON); + uploadStatusButton.addStyleName(SPUIStyleDefinitions.UPLOAD_PROGRESS_INDICATOR_STYLE); + uploadStatusButton.setWidth("100px"); + uploadStatusButton.setHtmlContentAllowed(true); + uploadStatusButton.addClickListener(event -> onClickOfUploadStatusButton()); + uploadStatusButton.setVisible(false); + } + + void updateStatusButtonCount() { + int uploadsPending = artifactUploadState.getNumberOfFileUploadsExpected().get() + - artifactUploadState.getNumberOfFilesActuallyUpload().get(); + int uploadsFailed = artifactUploadState.getNumberOfFileUploadsFailed().get(); + StringBuilder builder = new StringBuilder(""); + if (uploadsFailed != 0) { + if (uploadsPending != 0) { + builder.append("
" + uploadsFailed + "
"); + } else { + builder.append("
" + uploadsFailed + "
"); + } + } + if (uploadsPending != 0) { + builder.append("
" + uploadsPending + "
"); + } + uploadStatusButton.setCaption(builder.toString()); + } + + private void onClickOfUploadStatusButton() { + artifactUploadState.setStatusPopupMinimized(false); + eventBus.publish(this, UploadArtifactUIEvent.MAXIMIZED_STATUS_POPUP); + } + + private void showUploadStatusButton() { + if (uploadStatusButton == null) { + return; + } + uploadStatusButton.setVisible(true); + updateStatusButtonCount(); + } + + protected void hideUploadStatusButton() { + if (uploadStatusButton == null) { + return; + } + uploadStatusButton.setVisible(false); + } + + private void maximizeStatusPopup() { + hideUploadStatusButton(); + uploadInfoWindow.maximizeStatusPopup(); + } + + private void setUploadStatusButtonIconToFinished() { + if (uploadStatusButton == null) { + return; + } + uploadStatusButton.removeStyleName(SPUIStyleDefinitions.UPLOAD_PROGRESS_INDICATOR_STYLE); + uploadStatusButton.setIcon(FontAwesome.UPLOAD); + } + + private void setUploadStatusButtonIconToInProgress() { + if (uploadStatusButton == null) { + return; + } + uploadStatusButton.addStyleName(SPUIStyleDefinitions.UPLOAD_PROGRESS_INDICATOR_STYLE); + uploadStatusButton.setIcon(null); + } + + protected void updateUploadCounts() { + updateActionCount(); + updateStatusButtonCount(); + } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadResultWindow.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadResultWindow.java index c29548b82..f495c59aa 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadResultWindow.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadResultWindow.java @@ -11,6 +11,7 @@ package org.eclipse.hawkbit.ui.artifacts.upload; import java.util.ArrayList; import java.util.List; +import org.eclipse.hawkbit.ui.artifacts.event.UploadArtifactUIEvent; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleTiny; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; @@ -19,6 +20,8 @@ import org.eclipse.hawkbit.ui.utils.SPUIComponentIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; +import org.eclipse.hawkbit.ui.utils.SpringContextHelper; +import org.vaadin.spring.events.EventBus; import com.vaadin.data.Item; import com.vaadin.data.util.IndexedContainer; @@ -63,6 +66,9 @@ public class UploadResultWindow implements Button.ClickListener { private static final String UPLOAD_RESULT = "uploadResult"; private static final String REASON = "reason"; + + private transient EventBus.SessionEventBus eventBus; + /** * Initialize upload status popup. @@ -75,6 +81,7 @@ public class UploadResultWindow implements Button.ClickListener { public UploadResultWindow(final List uploadResultList, final I18N i18n) { this.uploadResultList = uploadResultList; this.i18n = i18n; + eventBus = SpringContextHelper.getBean( EventBus.SessionEventBus.class); createComponents(); createLayout(); } @@ -183,6 +190,8 @@ public class UploadResultWindow implements Button.ClickListener { if (event.getComponent().getId().equals(SPUIComponentIdProvider.UPLOAD_ARTIFACT_RESULT_CLOSE) || event.getComponent().getId().equals(SPUIComponentIdProvider.UPLOAD_ARTIFACT_RESULT_POPUP_CLOSE)) { uploadResultsWindow.close(); + //close upload status popup if open + eventBus.publish(this, UploadArtifactUIEvent.ARTIFACT_RESULT_POPUP_CLOSED); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadStatusInfoWindow.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadStatusInfoWindow.java index 8b36ef39e..a58c6ea14 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadStatusInfoWindow.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadStatusInfoWindow.java @@ -8,20 +8,49 @@ */ package org.eclipse.hawkbit.ui.artifacts.upload; -import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +import org.eclipse.hawkbit.repository.model.SoftwareModule; +import org.eclipse.hawkbit.ui.artifacts.event.UploadArtifactUIEvent; +import org.eclipse.hawkbit.ui.artifacts.event.UploadStatusEvent; +import org.eclipse.hawkbit.ui.artifacts.event.UploadStatusEvent.UploadStatusEventType; +import org.eclipse.hawkbit.ui.artifacts.state.ArtifactUploadState; +import org.eclipse.hawkbit.ui.common.ConfirmationDialog; +import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; +import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmallNoBorder; +import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; +import org.eclipse.hawkbit.ui.utils.I18N; +import org.eclipse.hawkbit.ui.utils.SPUIComponentIdProvider; +import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; +import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; +import org.springframework.beans.factory.annotation.Autowired; +import org.vaadin.spring.events.EventBus; +import org.vaadin.spring.events.EventScope; +import org.vaadin.spring.events.annotation.EventBusListenerMethod; + +import com.vaadin.data.Container.Indexed; import com.vaadin.data.Item; import com.vaadin.data.util.IndexedContainer; import com.vaadin.server.FontAwesome; import com.vaadin.shared.ui.window.WindowMode; import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.ViewScope; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Grid; import com.vaadin.ui.Grid.SelectionMode; +import com.vaadin.ui.HorizontalLayout; +import com.vaadin.ui.Label; import com.vaadin.ui.UI; +import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.Window; import com.vaadin.ui.renderers.HtmlRenderer; import com.vaadin.ui.renderers.ProgressBarRenderer; +import com.vaadin.ui.themes.ValoTheme; import elemental.json.JsonValue; @@ -34,7 +63,16 @@ import elemental.json.JsonValue; @ViewScope @SpringComponent -public class UploadStatusInfoWindow extends Window implements Window.CloseListener, Window.WindowModeChangeListener { +public class UploadStatusInfoWindow extends Window { + + @Autowired + private transient EventBus.SessionEventBus eventBus; + + @Autowired + private ArtifactUploadState artifactUploadState; + + @Autowired + private I18N i18n; private static final String PROGRESS = "Progress"; @@ -46,52 +84,173 @@ public class UploadStatusInfoWindow extends Window implements Window.CloseListen private static final long serialVersionUID = 1L; - private final Grid grid; + private Grid grid; - private final IndexedContainer uploads; + private IndexedContainer uploads; private volatile boolean errorOccured = false; + private volatile boolean uploadAborted = false; + + private Button minimizeButton; + + private VerticalLayout mainLayout; + + private Label windowCaption; + + private Button closeButton; + + private Button resizeButton; + + private UI ui; + + private ConfirmationDialog confirmDialog; + /** * Default Constructor. */ - UploadStatusInfoWindow() { - super("Upload Status"); + @PostConstruct + void init() { - addStyleName(SPUIStyleDefinitions.UPLOAD_INFO); - center(); - setImmediate(true); - setResizable(true); - setDraggable(true); - setClosable(true); - uploads = new IndexedContainer(); - uploads.addContainerProperty(STATUS, String.class, "Active"); - uploads.addContainerProperty(FILE_NAME, String.class, null); - uploads.addContainerProperty(PROGRESS, Double.class, 0D); - uploads.addContainerProperty(REASON, String.class, ""); + setPopupProperties(); + createStatusPopupHeaderComponents(); - grid = new Grid(uploads); - grid.addStyleName(SPUIStyleDefinitions.UPLOAD_STATUS_GRID); - grid.setSelectionMode(SelectionMode.NONE); - grid.getColumn(STATUS).setRenderer(new StatusRenderer()); - grid.getColumn(PROGRESS).setRenderer(new ProgressBarRenderer()); - setColumnWidth(); - grid.setFrozenColumnCount(4); - grid.setColumnOrder(STATUS, PROGRESS, FILE_NAME, REASON); - grid.setHeaderVisible(true); - grid.setImmediate(true); + mainLayout = new VerticalLayout(); + mainLayout.setSpacing(Boolean.TRUE); + mainLayout.setSizeUndefined(); setPopupSizeInMinMode(); - setContent(grid); - addCloseListener(this); - addWindowModeChangeListener(this); + uploads = getGridContainer(); + grid = createGrid(); + setGridColumnProperties(); + + mainLayout.addComponents(getCaptionLayout(), grid); + mainLayout.setExpandRatio(grid, 1.0F); + setContent(mainLayout); + eventBus.subscribe(this); + ui = UI.getCurrent(); + + createConfirmDialog(); + } + + @EventBusListenerMethod(scope = EventScope.SESSION) + void onEvent(final UploadStatusEvent event) { + if (event.getUploadProgressEventType() == UploadStatusEventType.UPLOAD_IN_PROGRESS) { + UI.getCurrent().access( + () -> updateProgress(event.getUploadStatus().getFileName(), event.getUploadStatus().getBytesRead(), + event.getUploadStatus().getContentLength(), event.getUploadStatus().getSoftwareModule())); + } else if (event.getUploadProgressEventType() == UploadStatusEventType.UPLOAD_STARTED) { + UI.getCurrent().access(() -> onStartOfUpload(event)); + } else if (event.getUploadProgressEventType() == UploadStatusEventType.UPLOAD_STREAMING_FAILED) { + ui.access(() -> uploadFailed(event.getUploadStatus().getFileName(), event.getUploadStatus() + .getFailureReason(), event.getUploadStatus().getSoftwareModule())); + } else if (event.getUploadProgressEventType() == UploadStatusEventType.UPLOAD_SUCCESSFUL) { + UI.getCurrent().access( + () -> uploadSucceeded(event.getUploadStatus().getFileName(), event.getUploadStatus() + .getSoftwareModule())); + } else if (event.getUploadProgressEventType() == UploadStatusEventType.UPLOAD_STREAMING_FINISHED) { + ui.access(() -> uploadSucceeded(event.getUploadStatus().getFileName(), event.getUploadStatus() + .getSoftwareModule())); + } + } + + private void onStartOfUpload(UploadStatusEvent event) { + uploadSessionStarted(); + uploadStarted(event.getUploadStatus().getFileName(), event.getUploadStatus().getSoftwareModule()); + } + + @PreDestroy + void destroy() { + /* + * It's good manners to do this, even though vaadin-spring will + * automatically unsubscribe when this UI is garbage collected. + */ + eventBus.unsubscribe(this); + } + + private void restoreState() { + Indexed container = grid.getContainerDataSource(); + if (container.getItemIds().isEmpty()) { + container.removeAllItems(); + for (UploadStatusObject statusObject : artifactUploadState.getUploadedFileStatusList()) { + Item item = container.addItem(getItemid(statusObject.getFilename(), + statusObject.getSelectedSoftwareModule())); + item.getItemProperty(REASON).setValue(statusObject.getReason() != null ? statusObject.getReason() : ""); + item.getItemProperty(STATUS).setValue(statusObject.getStatus()); + item.getItemProperty(PROGRESS).setValue(statusObject.getProgress()); + item.getItemProperty(FILE_NAME).setValue(statusObject.getFilename()); + SoftwareModule sw = statusObject.getSelectedSoftwareModule(); + item.getItemProperty(SPUILabelDefinitions.NAME_VERSION).setValue( + HawkbitCommonUtil.getFormattedNameVersion(sw.getName(), sw.getVersion())); + } + if (artifactUploadState.isUploadCompleted()) { + minimizeButton.setEnabled(false); + } + } + } + + private void setPopupProperties() { + setId(SPUIComponentIdProvider.UPLOAD_STATUS_POPUP_ID); + addStyleName(SPUIStyleDefinitions.UPLOAD_INFO); + setImmediate(true); + setResizable(false); + setDraggable(true); + setClosable(false); + setModal(true); + } + + private void setGridColumnProperties() { + grid.getColumn(STATUS).setRenderer(new StatusRenderer()); + grid.getColumn(PROGRESS).setRenderer(new ProgressBarRenderer()); + grid.setColumnOrder(STATUS, PROGRESS, FILE_NAME, SPUILabelDefinitions.NAME_VERSION, REASON); + setColumnWidth(); + grid.getColumn(SPUILabelDefinitions.NAME_VERSION).setHeaderCaption(i18n.get("upload.swModuleTable.header")); + grid.setFrozenColumnCount(5); + } + + private Grid createGrid() { + Grid statusGrid = new Grid(uploads); + statusGrid.addStyleName(SPUIStyleDefinitions.UPLOAD_STATUS_GRID); + statusGrid.setSelectionMode(SelectionMode.NONE); + statusGrid.setHeaderVisible(true); + statusGrid.setImmediate(true); + statusGrid.setSizeFull(); + return statusGrid; + } + + private IndexedContainer getGridContainer() { + IndexedContainer uploadContainer = new IndexedContainer(); + uploadContainer.addContainerProperty(STATUS, String.class, "Active"); + uploadContainer.addContainerProperty(FILE_NAME, String.class, null); + uploadContainer.addContainerProperty(PROGRESS, Double.class, 0D); + uploadContainer.addContainerProperty(REASON, String.class, ""); + uploadContainer.addContainerProperty(SPUILabelDefinitions.NAME_VERSION, String.class, ""); + return uploadContainer; + } + + private HorizontalLayout getCaptionLayout() { + final HorizontalLayout captionLayout = new HorizontalLayout(); + captionLayout.setSizeFull(); + captionLayout.setHeight("36px"); + captionLayout.addComponents(windowCaption, minimizeButton, resizeButton, closeButton); + captionLayout.setExpandRatio(windowCaption, 1.0F); + captionLayout.addStyleName("v-window-header"); + return captionLayout; + } + + private void createStatusPopupHeaderComponents() { + minimizeButton = getMinimizeButton(); + windowCaption = new Label("Upload status"); + closeButton = getCloseButton(); + resizeButton = getResizeButton(); } private void setColumnWidth() { - grid.getColumn(STATUS).setWidth(70); + grid.getColumn(STATUS).setWidth(60); grid.getColumn(PROGRESS).setWidth(150); - grid.getColumn(FILE_NAME).setWidth(280); - grid.getColumn(REASON).setWidth(300); + grid.getColumn(FILE_NAME).setWidth(200); + grid.getColumn(REASON).setWidth(290); + grid.getColumn(SPUILabelDefinitions.NAME_VERSION).setWidth(200); } private void resetColumnWidth() { @@ -99,15 +258,16 @@ public class UploadStatusInfoWindow extends Window implements Window.CloseListen grid.getColumn(PROGRESS).setWidthUndefined(); grid.getColumn(FILE_NAME).setWidthUndefined(); grid.getColumn(REASON).setWidthUndefined(); - + grid.getColumn(SPUILabelDefinitions.NAME_VERSION).setWidthUndefined(); } private static class StatusRenderer extends HtmlRenderer { + private static final long serialVersionUID = -5365795450234970943L; + @Override public JsonValue encode(final String value) { - - String result = ""; + String result; switch (value) { case "Finished": result = "
" + FontAwesome.CHECK_CIRCLE.getHtml() + "
"; @@ -127,30 +287,66 @@ public class UploadStatusInfoWindow extends Window implements Window.CloseListen * Automatically close if not error has occured. */ void uploadSessionFinished() { - if (!errorOccured) { - close(); + uploadAborted = false; + if (!errorOccured && !artifactUploadState.isStatusPopupMinimized()) { + clearWindow(); } - + artifactUploadState.setUploadCompleted(true); + minimizeButton.setEnabled(false); + closeButton.setEnabled(true); + confirmDialog.getWindow().close(); + UI.getCurrent().removeWindow(confirmDialog.getWindow()); } void uploadSessionStarted() { - close(); + if (artifactUploadState.getNumberOfFilesActuallyUpload().intValue() == 0 + && artifactUploadState.getNumberOfFileUploadsFailed().intValue() == 0 + && !artifactUploadState.isStatusPopupMinimized()) { + openWindow(); + } + if (!uploadAborted) { + minimizeButton.setEnabled(true); + closeButton.setEnabled(true); + artifactUploadState.setUploadCompleted(false); + } + } + + void openWindow() { UI.getCurrent().addWindow(this); center(); } - void uploadStarted(final String filename) { - final Item item = uploads.addItem(filename); - item.getItemProperty(FILE_NAME).setValue(filename); - grid.scrollToEnd(); - + void maximizeStatusPopup() { + openWindow(); + restoreState(); } - void updateProgress(final String filename, final long readBytes, final long contentLength) { - final Item item = uploads.getItem(filename); + void uploadStarted(final String filename, final SoftwareModule softwareModule) { + final Item item = uploads.addItem(getItemid(filename, softwareModule)); if (item != null) { - item.getItemProperty(PROGRESS).setValue((double) readBytes / (double) contentLength); + item.getItemProperty(FILE_NAME).setValue(filename); + item.getItemProperty(SPUILabelDefinitions.NAME_VERSION).setValue( + HawkbitCommonUtil.getFormattedNameVersion(softwareModule.getName(), softwareModule.getVersion())); + } + grid.scrollToEnd(); + UploadStatusObject uploadStatus = new UploadStatusObject(filename, softwareModule); + uploadStatus.setStatus("Active"); + artifactUploadState.getUploadedFileStatusList().add(uploadStatus); + } + void updateProgress(final String filename, final long readBytes, final long contentLength, + final SoftwareModule softwareModule) { + final Item item = uploads.getItem(getItemid(filename, softwareModule)); + double progress = (double) readBytes / (double) contentLength; + if (item != null) { + item.getItemProperty(PROGRESS).setValue(progress); + } + List uploadStatusObjectList = (List) artifactUploadState + .getUploadedFileStatusList().stream().filter(e -> e.getFilename().equals(filename)) + .collect(Collectors.toList()); + if (!uploadStatusObjectList.isEmpty()) { + UploadStatusObject uploadStatusObject = uploadStatusObjectList.get(0); + uploadStatusObject.setProgress(progress); } } @@ -159,67 +355,142 @@ public class UploadStatusInfoWindow extends Window implements Window.CloseListen * * @param filename * of the uploaded file. + * @param softwareModule + * selected software module */ - public void uploadSucceeded(final String filename) { - final Item item = uploads.getItem(filename); + public void uploadSucceeded(final String filename, SoftwareModule softwareModule) { + final Item item = uploads.getItem(getItemid(filename, softwareModule)); + String status = "Finished"; if (item != null) { - item.getItemProperty(STATUS).setValue("Finished"); - + item.getItemProperty(STATUS).setValue(status); + } + List uploadStatusObjectList = (List) artifactUploadState + .getUploadedFileStatusList().stream().filter(e -> e.getFilename().equals(filename)) + .collect(Collectors.toList()); + if (!uploadStatusObjectList.isEmpty()) { + UploadStatusObject uploadStatusObject = uploadStatusObjectList.get(0); + uploadStatusObject.setStatus(status); + uploadStatusObject.setProgress(1d); } } - void uploadFailed(final String filename, final String errorReason) { - final Item item = uploads.getItem(filename); + void uploadFailed(final String filename, final String errorReason, SoftwareModule softwareModule) { + errorOccured = true; + String status = "Failed"; + final Item item = uploads.getItem(getItemid(filename, softwareModule)); if (item != null) { - if (!errorOccured) { - errorOccured = true; - } item.getItemProperty(REASON).setValue(errorReason); - item.getItemProperty(STATUS).setValue("Failed"); - + item.getItemProperty(STATUS).setValue(status); + } + List uploadStatusObjectList = (List) artifactUploadState + .getUploadedFileStatusList().stream().filter(e -> e.getFilename().equals(filename)) + .collect(Collectors.toList()); + if (!uploadStatusObjectList.isEmpty()) { + UploadStatusObject uploadStatusObject = uploadStatusObjectList.get(0); + uploadStatusObject.setStatus(status); + uploadStatusObject.setReason(errorReason); } } - /* - * (non-Javadoc) - * - * @see com.vaadin.ui.Window.CloseListener#windowClose(com.vaadin.ui.Window. - * CloseEvent) - */ - @Override - public void windowClose(final CloseEvent e) { - clearWindow(); - } - - private void clearWindow() { + protected void clearWindow() { errorOccured = false; uploads.removeAllItems(); setWindowMode(WindowMode.NORMAL); + setColumnWidth(); + setPopupSizeInMinMode(); + resizeButton.setIcon(FontAwesome.EXPAND); + this.close(); + artifactUploadState.getUploadedFileStatusList().clear(); + artifactUploadState.getNumberOfFileUploadsFailed().set(0); } - /* - * (non-Javadoc) - * - * @see com.vaadin.ui.Window.WindowModeChangeListener#windowModeChanged(com. - * vaadin.ui.Window. WindowModeChangeEvent) - */ - @Override - public void windowModeChanged(final WindowModeChangeEvent event) { - if (event.getWindow().getWindowMode() == WindowMode.MAXIMIZED) { + private void setPopupSizeInMinMode() { + mainLayout.setWidth(900, Unit.PIXELS); + mainLayout.setHeight(510, Unit.PIXELS); + } + + private Button getMinimizeButton() { + final Button minimizeBtn = SPUIComponentProvider.getButton( + SPUIComponentIdProvider.UPLOAD_STATUS_POPUP_MINIMIZE_BUTTON_ID, "", "", "", true, FontAwesome.MINUS, + SPUIButtonStyleSmallNoBorder.class); + minimizeBtn.addStyleName(ValoTheme.BUTTON_BORDERLESS); + minimizeBtn.addClickListener(event -> minimizeWindow()); + minimizeBtn.setEnabled(true); + return minimizeBtn; + } + + private Button getResizeButton() { + final Button resizeBtn = SPUIComponentProvider.getButton( + SPUIComponentIdProvider.UPLOAD_STATUS_POPUP_RESIZE_BUTTON_ID, "", "", "", true, FontAwesome.EXPAND, + SPUIButtonStyleSmallNoBorder.class); + resizeBtn.addStyleName(ValoTheme.BUTTON_BORDERLESS); + resizeBtn.addClickListener(event -> resizeWindow(event)); + return resizeBtn; + } + + private void resizeWindow(ClickEvent event) { + if (event.getButton().getIcon() == FontAwesome.EXPAND) { + event.getButton().setIcon(FontAwesome.COMPRESS); + setWindowMode(WindowMode.MAXIMIZED); resetColumnWidth(); grid.getColumn(STATUS).setExpandRatio(0); grid.getColumn(PROGRESS).setExpandRatio(1); grid.getColumn(FILE_NAME).setExpandRatio(2); grid.getColumn(REASON).setExpandRatio(3); - grid.setSizeFull(); + grid.getColumn(SPUILabelDefinitions.NAME_VERSION).setExpandRatio(4); + mainLayout.setSizeFull(); } else { + event.getButton().setIcon(FontAwesome.EXPAND); + setWindowMode(WindowMode.NORMAL); setColumnWidth(); setPopupSizeInMinMode(); } } - private void setPopupSizeInMinMode() { - grid.setWidth(800, Unit.PIXELS); - grid.setHeight(510, Unit.PIXELS); + private void minimizeWindow() { + this.close(); + artifactUploadState.setStatusPopupMinimized(true); + eventBus.publish(this, UploadArtifactUIEvent.MINIMIZED_STATUS_POPUP); + } + + private Button getCloseButton() { + final Button closeBtn = SPUIComponentProvider.getButton( + SPUIComponentIdProvider.UPLOAD_STATUS_POPUP_CLOSE_BUTTON_ID, "", "", "", true, FontAwesome.TIMES, + SPUIButtonStyleSmallNoBorder.class); + closeBtn.addStyleName(ValoTheme.BUTTON_BORDERLESS); + closeBtn.addClickListener(event -> onClose()); + return closeBtn; + } + + private void onClose() { + if (!artifactUploadState.isUploadCompleted()) { + confirmAbortAction(); + } else { + clearWindow(); + } + } + + private void confirmAbortAction() { + UI.getCurrent().addWindow(confirmDialog.getWindow()); + confirmDialog.getWindow().bringToFront(); + } + + private void createConfirmDialog() { + confirmDialog = new ConfirmationDialog(i18n.get("caption.confirm.abort.action"), + i18n.get("message.abort.upload"), i18n.get("button.ok"), i18n.get("button.cancel"), ok -> { + if (ok) { + eventBus.publish(this, UploadStatusEventType.ABORT_UPLOAD); + uploadAborted = true; + errorOccured = true; + minimizeButton.setEnabled(false); + closeButton.setEnabled(false); + } + }); + } + + private String getItemid(final String filename, final SoftwareModule softwareModule) { + return new StringBuilder(filename).append( + HawkbitCommonUtil.getFormattedNameVersion(softwareModule.getName(), softwareModule.getVersion())) + .toString(); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadStatusObject.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadStatusObject.java new file mode 100644 index 000000000..4ea82d7dd --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadStatusObject.java @@ -0,0 +1,86 @@ +/** + * 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.ui.artifacts.upload; + +import org.eclipse.hawkbit.repository.model.SoftwareModule; + +/** + * + * Holds uploaded file status.Used to display the details in upload status + * popup. + * + */ +public class UploadStatusObject { + private String status; + private Double progress; + private String filename; + private String reason; + private SoftwareModule selectedSoftwareModule; + + public UploadStatusObject(final String status, final Double progress, final String fileName, final String reason, + final SoftwareModule selectedSoftwareModule) { + this(fileName,selectedSoftwareModule); + this.status = status; + this.progress = progress; + this.reason = reason; + } + + public UploadStatusObject(String fileName, SoftwareModule selectedSoftwareModule) { + this.filename = fileName; + this.selectedSoftwareModule = selectedSoftwareModule; + } + + public SoftwareModule getSelectedSoftwareModule() { + return selectedSoftwareModule; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public Double getProgress() { + return progress; + } + + public void setProgress(Double progress) { + this.progress = progress; + } + + public String getFilename() { + return filename; + } + + public void setFilename(String filename) { + this.filename = filename; + } + + public String getReason() { + return reason; + } + + public void setReason(String reason) { + this.reason = reason; + } + + @Override + public boolean equals(Object obj) { + if (this == null || obj == null) { + return false; + } + if (obj instanceof UploadStatusObject && this.getFilename() == ((UploadStatusObject) obj).getFilename()) { + return true; + } + return false; + } + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetIdName.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/DistributionSetIdName.java similarity index 80% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetIdName.java rename to hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/DistributionSetIdName.java index f8662567a..66101fbd4 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetIdName.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/DistributionSetIdName.java @@ -6,10 +6,12 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.repository.model; +package org.eclipse.hawkbit.ui.common; import java.io.Serializable; +import org.eclipse.hawkbit.repository.model.DistributionSet; + /** * * @@ -20,6 +22,17 @@ public class DistributionSetIdName implements Serializable { private final Long id; private final String name; private final String version; + + public static DistributionSetIdName generate(final DistributionSet distributionSet) { + return new DistributionSetIdName(distributionSet.getId(), distributionSet.getName(), + distributionSet.getVersion()); + + } + + public static DistributionSetIdName generate(final Long id, final String name, final String version) { + return new DistributionSetIdName(id, name, version); + + } /** * @param id diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/DistributionSetTypeBeanQuery.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/DistributionSetTypeBeanQuery.java index b09255bc7..ded26b254 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/DistributionSetTypeBeanQuery.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/DistributionSetTypeBeanQuery.java @@ -13,6 +13,7 @@ import java.util.List; import java.util.Map; import org.eclipse.hawkbit.repository.DistributionSetManagement; +import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; @@ -41,6 +42,7 @@ public class DistributionSetTypeBeanQuery extends AbstractBeanQuery firstPageDistSetType = null; private transient DistributionSetManagement distributionSetManagement; + private transient EntityFactory entityFactory; /** * Parametric constructor. @@ -57,8 +59,9 @@ public class DistributionSetTypeBeanQuery extends AbstractBeanQuery loadBeans(final int startIndex, final int count) { Page typeBeans; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/SoftwareModuleTypeBeanQuery.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/SoftwareModuleTypeBeanQuery.java index 6fd382084..8705f7aa9 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/SoftwareModuleTypeBeanQuery.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/SoftwareModuleTypeBeanQuery.java @@ -11,6 +11,7 @@ package org.eclipse.hawkbit.ui.common; import java.util.List; import java.util.Map; +import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; @@ -31,6 +32,7 @@ public class SoftwareModuleTypeBeanQuery extends AbstractBeanQuery firstPageSwModuleType = null; private transient SoftwareManagement softwareManagement; + private transient EntityFactory entityFactory; /** * Parametric constructor. @@ -47,7 +49,14 @@ public class SoftwareModuleTypeBeanQuery extends AbstractBeanQuery onClickBulkUploadNotificationButton()); @@ -199,7 +199,7 @@ public abstract class AbstractDeleteActionsLayout extends VerticalLayout impleme if (bulkUploadStatusButton == null) { return; } - bulkUploadStatusButton.removeStyleName(SPUIStyleDefinitions.BULK_UPLOAD_PROGRESS_INDICATOR_STYLE); + bulkUploadStatusButton.removeStyleName(SPUIStyleDefinitions.UPLOAD_PROGRESS_INDICATOR_STYLE); bulkUploadStatusButton.setIcon(FontAwesome.UPLOAD); } @@ -207,7 +207,7 @@ public abstract class AbstractDeleteActionsLayout extends VerticalLayout impleme if (bulkUploadStatusButton == null) { return; } - bulkUploadStatusButton.addStyleName(SPUIStyleDefinitions.BULK_UPLOAD_PROGRESS_INDICATOR_STYLE); + bulkUploadStatusButton.addStyleName(SPUIStyleDefinitions.UPLOAD_PROGRESS_INDICATOR_STYLE); bulkUploadStatusButton.setIcon(null); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/grid/AbstractGridLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/grid/AbstractGridLayout.java index 997dbdd96..b07b927f0 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/grid/AbstractGridLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/grid/AbstractGridLayout.java @@ -9,6 +9,7 @@ package org.eclipse.hawkbit.ui.common.grid; import org.eclipse.hawkbit.ui.utils.SPUIComponentIdProvider; +import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; import com.vaadin.ui.Alignment; import com.vaadin.ui.HorizontalLayout; @@ -72,7 +73,7 @@ public abstract class AbstractGridLayout extends VerticalLayout { final Label countMessageLabel = getCountMessageLabel(); countMessageLabel.setId(SPUIComponentIdProvider.ROLLOUT_GROUP_TARGET_LABEL); rolloutGroupTargetsCountLayout.addComponent(getCountMessageLabel()); - rolloutGroupTargetsCountLayout.setStyleName("footer-layout"); + rolloutGroupTargetsCountLayout.setStyleName(SPUIStyleDefinitions.FOOTER_LAYOUT); rolloutGroupTargetsCountLayout.setWidth("100%"); return rolloutGroupTargetsCountLayout; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/AbstractTargetTagToken.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/AbstractTargetTagToken.java index ce9f101f3..e74a331af 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/AbstractTargetTagToken.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/AbstractTargetTagToken.java @@ -8,9 +8,9 @@ */ package org.eclipse.hawkbit.ui.common.tagdetails; -import org.eclipse.hawkbit.eventbus.event.TargetTagCreatedBulkEvent; -import org.eclipse.hawkbit.eventbus.event.TargetTagDeletedEvent; import org.eclipse.hawkbit.repository.TagManagement; +import org.eclipse.hawkbit.repository.eventbus.event.TargetTagCreatedBulkEvent; +import org.eclipse.hawkbit.repository.eventbus.event.TargetTagDeletedEvent; import org.eclipse.hawkbit.repository.model.BaseEntity; import org.eclipse.hawkbit.repository.model.TargetTag; import org.springframework.beans.factory.annotation.Autowired; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/DistributionTagToken.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/DistributionTagToken.java index 178610c23..88467d838 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/DistributionTagToken.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/DistributionTagToken.java @@ -14,12 +14,12 @@ import java.util.List; import java.util.Set; import java.util.stream.Collectors; -import org.eclipse.hawkbit.eventbus.event.DistributionSetTagAssigmentResultEvent; -import org.eclipse.hawkbit.eventbus.event.DistributionSetTagCreatedBulkEvent; -import org.eclipse.hawkbit.eventbus.event.DistributionSetTagDeletedEvent; -import org.eclipse.hawkbit.eventbus.event.DistributionSetTagUpdateEvent; import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.TagManagement; +import org.eclipse.hawkbit.repository.eventbus.event.DistributionSetTagAssigmentResultEvent; +import org.eclipse.hawkbit.repository.eventbus.event.DistributionSetTagCreatedBulkEvent; +import org.eclipse.hawkbit.repository.eventbus.event.DistributionSetTagDeletedEvent; +import org.eclipse.hawkbit.repository.eventbus.event.DistributionSetTagUpdateEvent; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/TargetTagToken.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/TargetTagToken.java index 6f03c5860..2cd4ec978 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/TargetTagToken.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/TargetTagToken.java @@ -14,9 +14,9 @@ import java.util.List; import java.util.Set; import java.util.stream.Collectors; -import org.eclipse.hawkbit.eventbus.event.TargetTagAssigmentResultEvent; -import org.eclipse.hawkbit.eventbus.event.TargetTagUpdateEvent; import org.eclipse.hawkbit.repository.TargetManagement; +import org.eclipse.hawkbit.repository.eventbus.event.TargetTagAssigmentResultEvent; +import org.eclipse.hawkbit.repository.eventbus.event.TargetTagUpdateEvent; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetTag; import org.eclipse.hawkbit.repository.model.TargetTagAssignmentResult; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/ProxyDistribution.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/ProxyDistribution.java index 64473706e..0420f9e4b 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/ProxyDistribution.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/ProxyDistribution.java @@ -9,13 +9,14 @@ package org.eclipse.hawkbit.ui.components; import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.ui.common.DistributionSetIdName; /** * Proxy for {@link DistributionSet}. * * */ -public class ProxyDistribution extends DistributionSet { +public class ProxyDistribution { private static final long serialVersionUID = -8891449133620645310L; @@ -33,6 +34,11 @@ public class ProxyDistribution extends DistributionSet { private String nameVersion; + private Long id; + private String name; + private String version; + private String description; + /** * @return the nameVersion */ @@ -40,6 +46,10 @@ public class ProxyDistribution extends DistributionSet { return nameVersion; } + public DistributionSetIdName getDistributionSetIdName() { + return DistributionSetIdName.generate(id, name, version); + } + /** * @param nameVersion * the nameVersion to set @@ -96,4 +106,36 @@ public class ProxyDistribution extends DistributionSet { this.modifiedByUser = modifiedByUser; } + public Long getId() { + return id; + } + + public void setId(final Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public String getVersion() { + return version; + } + + public void setVersion(final String version) { + this.version = version; + } + + public String getDescription() { + return description; + } + + public void setDescription(final String description) { + this.description = description; + } + } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/ProxyTarget.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/ProxyTarget.java index 9ac39616d..3441198d9 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/ProxyTarget.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/ProxyTarget.java @@ -8,30 +8,33 @@ */ package org.eclipse.hawkbit.ui.components; +import java.io.Serializable; import java.net.URI; import java.security.SecureRandom; import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.DistributionSet; -import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetIdName; +import org.eclipse.hawkbit.repository.model.TargetInfo; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; /** * Proxy for {@link Target}. * - * - * - * + */ +/** + * @author kaizimmerm * */ -public class ProxyTarget extends Target { +public class ProxyTarget implements Serializable { private static final long serialVersionUID = -8891449133620645310L; private String controllerId; private URI address = null; private Long lastTargetQuery = null; private Long installationDate; + private Long id; + private TargetUpdateStatus updateStatus = TargetUpdateStatus.UNKNOWN; private DistributionSet installedDistributionSet; @@ -56,11 +59,58 @@ public class ProxyTarget extends Target { private Status status; + private String name; + + private String description; + + private Long createdAt; + + private TargetInfo targetInfo; + + public Long getId() { + return id; + } + + public void setId(final Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(final String description) { + this.description = description; + } + + public Long getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(final Long createdAt) { + this.createdAt = createdAt; + } + + public TargetInfo getTargetInfo() { + return targetInfo; + } + + public void setTargetInfo(final TargetInfo targetInfo) { + this.targetInfo = targetInfo; + } + /** * @param controllerId */ public ProxyTarget() { - super(null); final Integer generatedId = new SecureRandom().nextInt(Integer.MAX_VALUE) - Integer.MAX_VALUE; targetIdName = new TargetIdName(generatedId, generatedId.toString(), generatedId.toString()); } @@ -160,7 +210,6 @@ public class ProxyTarget extends Target { * * @return String as ID. */ - @Override public String getControllerId() { return controllerId; } @@ -171,7 +220,6 @@ public class ProxyTarget extends Target { * @param controllerId * as ID */ - @Override public void setControllerId(final String controllerId) { this.controllerId = controllerId; } @@ -262,18 +310,14 @@ public class ProxyTarget extends Target { * @param assignedDistributionSet * the assignedDistributionSet to set */ - public void setAssignedDistributionSet(DistributionSet assignedDistributionSet) { + public void setAssignedDistributionSet(final DistributionSet assignedDistributionSet) { this.assignedDistributionSet = assignedDistributionSet; } /** * @return the targetIdName */ - @Override public TargetIdName getTargetIdName() { - if (this.targetIdName == null) { - return super.getTargetIdName(); - } return this.targetIdName; } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/ProxyTargetFilter.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/ProxyTargetFilter.java index b894bc983..9faf501e0 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/ProxyTargetFilter.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/ProxyTargetFilter.java @@ -8,14 +8,12 @@ */ package org.eclipse.hawkbit.ui.components; -import org.eclipse.hawkbit.repository.model.TargetFilterQuery; - /** * * * */ -public class ProxyTargetFilter extends TargetFilterQuery { +public class ProxyTargetFilter { private static final long serialVersionUID = 6622060929679084419L; @@ -23,6 +21,12 @@ public class ProxyTargetFilter extends TargetFilterQuery { private String modifiedDate; + private String name; + private Long id; + private String createdBy; + private String lastModifiedBy; + private String query; + public String getCreatedDate() { return createdDate; } @@ -46,4 +50,44 @@ public class ProxyTargetFilter extends TargetFilterQuery { this.modifiedDate = modifiedDate; } + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(final Long id) { + this.id = id; + } + + public String getLastModifiedBy() { + return lastModifiedBy; + } + + public void setLastModifiedBy(final String lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + public String getQuery() { + return query; + } + + public void setQuery(final String query) { + this.query = query; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(final String createdBy) { + this.createdBy = createdBy; + } + } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/CreateUpdateDistSetTypeLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/CreateUpdateDistSetTypeLayout.java index e9bc49675..afd98c5c1 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/CreateUpdateDistSetTypeLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/CreateUpdateDistSetTypeLayout.java @@ -14,7 +14,7 @@ import java.util.List; import java.util.Set; import org.eclipse.hawkbit.repository.DistributionSetManagement; -import org.eclipse.hawkbit.repository.DistributionSetRepository; +import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.model.DistributionSetType; @@ -114,7 +114,7 @@ public class CreateUpdateDistSetTypeLayout extends CustomComponent implements Co private transient DistributionSetManagement distributionSetManagement; @Autowired - private transient DistributionSetRepository distributionSetRepository; + private transient EntityFactory entityFactory; /** * Instance of ColorPickerPreview. @@ -284,7 +284,7 @@ public class CreateUpdateDistSetTypeLayout extends CustomComponent implements Co mainLayout.addComponent(fieldLayout); mainLayout.addComponent(twinTableLayout); - + colorLayout = new HorizontalLayout(); sliderLayout = new VerticalLayout(); final HorizontalLayout chooseColorLayout = new HorizontalLayout(); @@ -654,7 +654,8 @@ public class CreateUpdateDistSetTypeLayout extends CustomComponent implements Co final String typeDescValue = HawkbitCommonUtil.trimAndNullIfEmpty(typeDesc.getValue()); final List itemIds = (List) selectedTable.getItemIds(); if (null != typeNameValue && null != typeKeyValue && null != itemIds && !itemIds.isEmpty()) { - DistributionSetType newDistType = new DistributionSetType(typeKeyValue, typeNameValue, typeDescValue); + DistributionSetType newDistType = entityFactory.generateDistributionSetType(typeKeyValue, typeNameValue, + typeDescValue); for (final Long id : itemIds) { final Item item = selectedTable.getItem(id); final String distTypeName = (String) item.getItemProperty(DIST_TYPE_NAME).getValue(); @@ -704,7 +705,8 @@ public class CreateUpdateDistSetTypeLayout extends CustomComponent implements Co updateDistSetType.setKey(typeKeyValue); updateDistSetType.setDescription(null != typeDescValue ? typeDescValue : null); - if (distributionSetRepository.countByType(existingType) <= 0 && null != itemIds && !itemIds.isEmpty()) { + if (distributionSetManagement.countDistributionSetsByType(existingType) <= 0 && null != itemIds + && !itemIds.isEmpty()) { for (final Long id : itemIds) { final Item item = selectedTable.getItem(id); final CheckBox mandatoryCheckBox = (CheckBox) item.getItemProperty(DIST_TYPE_MANDATORY).getValue(); @@ -1040,7 +1042,7 @@ public class CreateUpdateDistSetTypeLayout extends CustomComponent implements Co typeDesc.setValue(selectedTypeTag.getDescription()); typeKey.setValue(selectedTypeTag.getKey()); - if (distributionSetRepository.countByType(selectedTypeTag) <= 0) { + if (distributionSetManagement.countDistributionSetsByType(selectedTypeTag) <= 0) { distTypeSelectLayout.setEnabled(true); selectedTable.setEnabled(true); saveDistSetType.setEnabled(true); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetDetails.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetDetails.java index edb2122fb..75f7071ea 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetDetails.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetDetails.java @@ -16,11 +16,11 @@ import java.util.Set; import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.model.DistributionSet; -import org.eclipse.hawkbit.repository.model.DistributionSetIdName; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleIdName; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent.SoftwareModuleEventType; +import org.eclipse.hawkbit.ui.common.DistributionSetIdName; import org.eclipse.hawkbit.ui.common.detailslayout.AbstractNamedVersionedEntityTableDetailsLayout; import org.eclipse.hawkbit.ui.common.detailslayout.SoftwareModuleDetailsTable; import org.eclipse.hawkbit.ui.common.tagdetails.DistributionTagToken; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetTable.java index 216919047..0b895179b 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetTable.java @@ -21,13 +21,12 @@ import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.TargetManagement; -import org.eclipse.hawkbit.repository.exception.EntityLockedException; import org.eclipse.hawkbit.repository.model.DistributionSet; -import org.eclipse.hawkbit.repository.model.DistributionSetIdName; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleIdName; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent.SoftwareModuleEventType; +import org.eclipse.hawkbit.ui.common.DistributionSetIdName; import org.eclipse.hawkbit.ui.common.table.AbstractNamedVersionTable; import org.eclipse.hawkbit.ui.common.table.AbstractTable; import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; @@ -322,11 +321,11 @@ public class DistributionSetTable extends AbstractNamedVersionTable { distBeans = firstPageDistributionSets; } else if (Strings.isNullOrEmpty(searchText)) { // if no search filters available - distBeans = getDistributionSetManagement() - .findDistributionSetsAll(new OffsetBasedPageRequest(startIndex, count, sort), false, null); + distBeans = getDistributionSetManagement().findDistributionSetsByDeletedAndOrCompleted( + new OffsetBasedPageRequest(startIndex, count, sort), false, null); } else { final DistributionSetFilter distributionSetFilter = new DistributionSetFilterBuilder().setIsDeleted(false) .setSearchText(searchText).setSelectDSWithNoTag(Boolean.FALSE).setType(distributionSetType).build(); @@ -113,7 +113,6 @@ public class ManageDistBeanQuery extends AbstractBeanQuery { proxyDistribution.setVersion(distributionSet.getVersion()); proxyDistribution.setCreatedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getCreatedAt())); proxyDistribution.setLastModifiedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getLastModifiedAt())); - proxyDistribution.setDescription(distributionSet.getDescription()); proxyDistribution.setCreatedByUser(UserDetailsFormatter.loadAndFormatCreatedBy(distributionSet)); proxyDistribution.setModifiedByUser(UserDetailsFormatter.loadAndFormatLastModifiedBy(distributionSet)); proxyDistribution.setIsComplete(distributionSet.isComplete()); @@ -132,8 +131,8 @@ public class ManageDistBeanQuery extends AbstractBeanQuery { public int size() { if (Strings.isNullOrEmpty(searchText) && null == distributionSetType) { // if no search filters available - firstPageDistributionSets = getDistributionSetManagement() - .findDistributionSetsAll(new PageRequest(0, SPUIDefinitions.PAGE_SIZE, sort), false, null); + firstPageDistributionSets = getDistributionSetManagement().findDistributionSetsByDeletedAndOrCompleted( + new PageRequest(0, SPUIDefinitions.PAGE_SIZE, sort), false, null); } else { final DistributionSetFilter distributionSetFilter = new DistributionSetFilterBuilder().setIsDeleted(false) .setSearchText(searchText).setSelectDSWithNoTag(Boolean.FALSE).setType(distributionSetType).build(); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/event/SoftwareModuleAssignmentDiscardEvent.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/event/SoftwareModuleAssignmentDiscardEvent.java index 16e0869f3..c2365fa07 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/event/SoftwareModuleAssignmentDiscardEvent.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/event/SoftwareModuleAssignmentDiscardEvent.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.ui.distributions.event; -import org.eclipse.hawkbit.repository.model.DistributionSetIdName; +import org.eclipse.hawkbit.ui.common.DistributionSetIdName; /** * Event fired on discard of software module assignment. diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DSDeleteActionsLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DSDeleteActionsLayout.java index fa941675f..128712ce5 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DSDeleteActionsLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DSDeleteActionsLayout.java @@ -16,9 +16,9 @@ import java.util.Map.Entry; import java.util.Set; import org.eclipse.hawkbit.repository.SystemManagement; -import org.eclipse.hawkbit.repository.model.DistributionSetIdName; import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.SoftwareModuleIdName; +import org.eclipse.hawkbit.ui.common.DistributionSetIdName; import org.eclipse.hawkbit.ui.common.footer.AbstractDeleteActionsLayout; import org.eclipse.hawkbit.ui.common.table.AbstractTable; import org.eclipse.hawkbit.ui.distributions.event.DistributionsUIEvent; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DistributionsConfirmationWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DistributionsConfirmationWindowLayout.java index 741cc8ce4..290d2ff54 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DistributionsConfirmationWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DistributionsConfirmationWindowLayout.java @@ -19,9 +19,9 @@ import java.util.stream.Collectors; import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.model.DistributionSet; -import org.eclipse.hawkbit.repository.model.DistributionSetIdName; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleIdName; +import org.eclipse.hawkbit.ui.common.DistributionSetIdName; import org.eclipse.hawkbit.ui.common.confirmwindow.layout.AbstractConfirmationWindowLayout; import org.eclipse.hawkbit.ui.common.confirmwindow.layout.ConfirmationTab; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleBeanQuery.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleBeanQuery.java index 21ce01347..16636e64b 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleBeanQuery.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleBeanQuery.java @@ -14,7 +14,7 @@ import java.util.Map; import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.SoftwareManagement; -import org.eclipse.hawkbit.repository.model.CustomSoftwareModule; +import org.eclipse.hawkbit.repository.model.AssignedSoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; @@ -75,20 +75,20 @@ public class SwModuleBeanQuery extends AbstractBeanQuery @Override protected List loadBeans(final int startIndex, final int count) { - final Slice swModuleBeans; + final Slice swModuleBeans; final List proxyBeans = new ArrayList<>(); swModuleBeans = getSoftwareManagement().findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc( new OffsetBasedPageRequest(startIndex, count), orderByDistId, searchText, type); - for (final CustomSoftwareModule swModule : swModuleBeans) { + for (final AssignedSoftwareModule swModule : swModuleBeans) { proxyBeans.add(getProxyBean(swModule)); } return proxyBeans; } - private ProxyBaseSwModuleItem getProxyBean(final CustomSoftwareModule customSoftwareModule) { + private ProxyBaseSwModuleItem getProxyBean(final AssignedSoftwareModule customSoftwareModule) { final SoftwareModule bean = customSoftwareModule.getSoftwareModule(); final ProxyBaseSwModuleItem proxyItem = new ProxyBaseSwModuleItem(); proxyItem.setSwId(bean.getId()); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageDistUIState.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageDistUIState.java index a68a42e00..45ad7ac89 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageDistUIState.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageDistUIState.java @@ -16,8 +16,8 @@ import java.util.Map; import java.util.Optional; import java.util.Set; -import org.eclipse.hawkbit.repository.model.DistributionSetIdName; import org.eclipse.hawkbit.repository.model.SoftwareModuleIdName; +import org.eclipse.hawkbit.ui.common.DistributionSetIdName; import org.eclipse.hawkbit.ui.common.ManagmentEntityState; import org.springframework.beans.factory.annotation.Autowired; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/CreateOrUpdateFilterHeader.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/CreateOrUpdateFilterHeader.java index 632c16ff6..c5c56994e 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/CreateOrUpdateFilterHeader.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/CreateOrUpdateFilterHeader.java @@ -13,6 +13,7 @@ import java.util.concurrent.Executor; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; +import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.TargetFilterQueryManagement; import org.eclipse.hawkbit.repository.model.TargetFilterQuery; @@ -95,6 +96,9 @@ public class CreateOrUpdateFilterHeader extends VerticalLayout implements Button @Qualifier("uiExecutor") private transient Executor executor; + @Autowired + private transient EntityFactory entityFactory; + private HorizontalLayout breadcrumbLayout; private Button breadcrumbButton; @@ -503,7 +507,7 @@ public class CreateOrUpdateFilterHeader extends VerticalLayout implements Button } private void createTargetFilterQuery() { - final TargetFilterQuery targetFilterQuery = new TargetFilterQuery(); + final TargetFilterQuery targetFilterQuery = entityFactory.generateTargetFilterQuery(); targetFilterQuery.setName(nameTextField.getValue()); targetFilterQuery.setQuery(queryTextField.getValue()); targetFilterQueryManagement.createTargetFilterQuery(targetFilterQuery); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/FilterManagementView.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/FilterManagementView.java index ef759aa5f..40e6306b0 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/FilterManagementView.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/FilterManagementView.java @@ -14,6 +14,7 @@ import org.eclipse.hawkbit.ui.HawkbitUI; import org.eclipse.hawkbit.ui.filtermanagement.event.CustomFilterUIEvent; import org.eclipse.hawkbit.ui.filtermanagement.footer.TargetFilterCountMessageLabel; import org.eclipse.hawkbit.ui.filtermanagement.state.FilterManagementUIState; +import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; import org.springframework.beans.factory.annotation.Autowired; import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; @@ -152,7 +153,7 @@ public class FilterManagementView extends VerticalLayout implements View { private HorizontalLayout addTargetFilterMessageLabel() { final HorizontalLayout messageLabelLayout = new HorizontalLayout(); messageLabelLayout.addComponent(targetFilterCountMessageLabel); - messageLabelLayout.addStyleName("footer-layout"); + messageLabelLayout.addStyleName(SPUIStyleDefinitions.FOOTER_LAYOUT); return messageLabelLayout; } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/FilterQueryValidation.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/FilterQueryValidation.java index 4f528c74a..6d1f1a7ab 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/FilterQueryValidation.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/FilterQueryValidation.java @@ -17,8 +17,8 @@ import java.util.stream.Collectors; import org.eclipse.hawkbit.repository.TargetFields; import org.eclipse.hawkbit.repository.TargetManagement; -import org.eclipse.hawkbit.repository.rsql.RSQLParameterSyntaxException; -import org.eclipse.hawkbit.repository.rsql.RSQLParameterUnsupportedFieldException; +import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException; +import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException; import org.eclipse.hawkbit.ui.utils.SpringContextHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/actionhistory/ActionHistoryTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/actionhistory/ActionHistoryTable.java index 934fff07e..e1581bea2 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/actionhistory/ActionHistoryTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/actionhistory/ActionHistoryTable.java @@ -69,14 +69,15 @@ import com.vaadin.ui.UI; import com.vaadin.ui.themes.ValoTheme; /** - * + * Table for {@link Target#getActions()} history. * */ - @SpringComponent @ViewScope public class ActionHistoryTable extends TreeTable implements Handler { + private static final String BUTTON_CANCEL = "button.cancel"; + private static final String BUTTON_OK = "button.ok"; private static final long serialVersionUID = -1631514704696786653L; @Autowired private I18N i18n; @@ -241,11 +242,14 @@ public class ActionHistoryTable extends TreeTable implements Handler { private void getcontainerData() { hierarchicalContainer.removeAllItems(); - /* service method to create action history for target */ - final List actionHistory = deploymentManagement + + if (target != null) { + /* service method to create action history for target */ + final List actionHistory = deploymentManagement .findActionsWithStatusCountByTargetOrderByIdDesc(target); - - addDetailsToContainer(actionHistory); + + addDetailsToContainer(actionHistory); + } } /** @@ -268,29 +272,29 @@ public class ActionHistoryTable extends TreeTable implements Handler { final Action action = actionWithStatusCount.getAction(); - final Item item = hierarchicalContainer.addItem(actionWithStatusCount.getActionId()); + final Item item = hierarchicalContainer.addItem(actionWithStatusCount.getAction().getId()); item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_STATUS_HIDDEN) - .setValue(actionWithStatusCount.getActionStatus()); + .setValue(actionWithStatusCount.getAction().getStatus()); /* * add action id. */ item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTION_ID) - .setValue(actionWithStatusCount.getActionId().toString()); + .setValue(actionWithStatusCount.getAction().getId().toString()); /* * add active/inactive status to the item which will be used in * Column generator to generate respective icon */ item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTIVE_HIDDEN).setValue( - actionWithStatusCount.isActionActive() ? SPUIDefinitions.ACTIVE : SPUIDefinitions.IN_ACTIVE); + actionWithStatusCount.getAction().isActive() ? SPUIDefinitions.ACTIVE : SPUIDefinitions.IN_ACTIVE); /* * add action Id to the item which will be used for fetching child * items ( previous action status ) during expand */ item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTION_ID_HIDDEN) - .setValue(actionWithStatusCount.getActionId()); + .setValue(actionWithStatusCount.getAction().getId()); /* * add distribution name to the item which will be displayed in the @@ -301,18 +305,18 @@ public class ActionHistoryTable extends TreeTable implements Handler { item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_FORCED).setValue(action); /* Default no child */ - ((Hierarchical) hierarchicalContainer).setChildrenAllowed(actionWithStatusCount.getActionId(), false); + ((Hierarchical) hierarchicalContainer).setChildrenAllowed(actionWithStatusCount.getAction().getId(), false); item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_DATETIME) - .setValue(SPDateTimeUtil.getFormattedDate((actionWithStatusCount.getActionLastModifiedAt() != null) - ? actionWithStatusCount.getActionLastModifiedAt() - : actionWithStatusCount.getActionCreatedAt())); + .setValue(SPDateTimeUtil.getFormattedDate((actionWithStatusCount.getAction().getLastModifiedAt() != null) + ? actionWithStatusCount.getAction().getLastModifiedAt() + : actionWithStatusCount.getAction().getLastModifiedAt())); item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_ROLLOUT_NAME) .setValue(actionWithStatusCount.getRolloutName()); if (actionWithStatusCount.getActionStatusCount() > 0) { - ((Hierarchical) hierarchicalContainer).setChildrenAllowed(actionWithStatusCount.getActionId(), true); + ((Hierarchical) hierarchicalContainer).setChildrenAllowed(actionWithStatusCount.getAction().getId(), true); } } } @@ -422,8 +426,12 @@ public class ActionHistoryTable extends TreeTable implements Handler { .findActionWithDetails(actionId); final Pageable pageReq = new PageRequest(0, 1000, new Sort(Direction.DESC, ActionStatusFields.ID.getFieldName())); - final Page actionStatusList = deploymentManagement.findActionStatusByAction(pageReq, action, - managementUIState.isActionHistoryMaximized()); + final Page actionStatusList; + if (managementUIState.isActionHistoryMaximized()) { + actionStatusList = deploymentManagement.findActionStatusByActionWithMessages(pageReq, action); + } else { + actionStatusList = deploymentManagement.findActionStatusByAction(pageReq, action); + } final List content = actionStatusList.getContent(); /* * Since the recent action status and messages are already @@ -747,7 +755,7 @@ public class ActionHistoryTable extends TreeTable implements Handler { private void confirmAndForceAction(final Long actionId) { /* Display the confirmation */ final ConfirmationDialog confirmDialog = new ConfirmationDialog(i18n.get("caption.force.action.confirmbox"), - i18n.get("message.force.action.confirm"), i18n.get("button.ok"), i18n.get("button.cancel"), ok -> { + i18n.get("message.force.action.confirm"), i18n.get(BUTTON_OK), i18n.get(BUTTON_CANCEL), ok -> { if (ok) { /* cancel the action */ deploymentManagement.forceTargetAction(actionId); @@ -769,7 +777,7 @@ public class ActionHistoryTable extends TreeTable implements Handler { private void confirmAndForceQuitAction(final Long actionId) { /* Display the confirmation */ final ConfirmationDialog confirmDialog = new ConfirmationDialog(i18n.get("caption.forcequit.action.confirmbox"), - i18n.get("message.forcequit.action.confirm"), i18n.get("button.ok"), i18n.get("button.cancel"), ok -> { + i18n.get("message.forcequit.action.confirm"), i18n.get(BUTTON_OK), i18n.get(BUTTON_CANCEL), ok -> { if (ok) { final boolean cancelResult = forceQuitActiveAction(actionId); if (cancelResult) { @@ -797,7 +805,7 @@ public class ActionHistoryTable extends TreeTable implements Handler { */ private void confirmAndCancelAction(final Long actionId) { final ConfirmationDialog confirmDialog = new ConfirmationDialog(i18n.get("caption.cancel.action.confirmbox"), - i18n.get("message.cancel.action.confirm"), i18n.get("button.ok"), i18n.get("button.cancel"), ok -> { + i18n.get("message.cancel.action.confirm"), i18n.get(BUTTON_OK), i18n.get(BUTTON_CANCEL), ok -> { if (ok) { final boolean cancelResult = cancelActiveAction(actionId); if (cancelResult) { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionAddUpdateWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionAddUpdateWindowLayout.java index aaf9ce7db..ceb7f4fd1 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionAddUpdateWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionAddUpdateWindowLayout.java @@ -16,8 +16,8 @@ import java.util.Map; import javax.annotation.PostConstruct; import org.eclipse.hawkbit.repository.DistributionSetManagement; +import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.SystemManagement; -import org.eclipse.hawkbit.repository.TenantMetaDataRepository; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetType; @@ -92,7 +92,7 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout { private transient SystemManagement systemManagement; @Autowired - private transient TenantMetaDataRepository tenantMetaDataRepository; + private transient EntityFactory entityFactory; private Button saveDistributionBtn; private Button discardDistributionBtn; @@ -145,12 +145,12 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout { setSizeUndefined(); addComponents(madatoryLabel, distsetTypeNameComboBox, distNameTextField, distVersionTextField, descTextArea, reqMigStepCheckbox); - + addComponent(buttonsLayout); setComponentAlignment(madatoryLabel, Alignment.MIDDLE_LEFT); distNameTextField.focus(); - - } + + } /** * Create required UI components. @@ -221,8 +221,7 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout { } private DistributionSetType getDefaultDistributionSetType() { - final TenantMetaData tenantMetaData = tenantMetaDataRepository - .findByTenantIgnoreCase(systemManagement.currentTenant()); + final TenantMetaData tenantMetaData = systemManagement.getTenantMetadata(); return tenantMetaData.getDefaultDsType(); } @@ -297,7 +296,7 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout { if (mandatoryCheck(name, version, distSetTypeName) && duplicateCheck(name, version)) { final String desc = HawkbitCommonUtil.trimAndNullIfEmpty(descTextArea.getValue()); final boolean isMigStepReq = reqMigStepCheckbox.getValue(); - DistributionSet newDist = new DistributionSet(); + DistributionSet newDist = entityFactory.generateDistributionSet(); setDistributionValues(newDist, name, version, distSetTypeName, desc, isMigStepReq); newDist = distributionSetManagement.createDistributionSet(newDist); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionBeanQuery.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionBeanQuery.java index 7909a3850..63ed91250 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionBeanQuery.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionBeanQuery.java @@ -13,11 +13,11 @@ import java.util.Collection; import java.util.List; import java.util.Map; -import org.eclipse.hawkbit.repository.DistributionSetFilter; -import org.eclipse.hawkbit.repository.DistributionSetFilter.DistributionSetFilterBuilder; import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.repository.model.DistributionSetFilter; +import org.eclipse.hawkbit.repository.model.DistributionSetFilter.DistributionSetFilterBuilder; import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; import org.eclipse.hawkbit.ui.components.ProxyDistribution; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; @@ -42,11 +42,11 @@ public class DistributionBeanQuery extends AbstractBeanQuery private static final long serialVersionUID = 5862679853949173536L; private Sort sort = new Sort(Direction.ASC, "name", "version"); - private Collection distributionTags = null; - private String searchText = null; - private String pinnedControllerId = null; + private Collection distributionTags; + private String searchText; + private String pinnedControllerId; private transient DistributionSetManagement distributionSetManagement; - private transient Page firstPageDistributionSets = null; + private transient Page firstPageDistributionSets; private Boolean noTagClicked = Boolean.FALSE; /** @@ -110,8 +110,8 @@ public class DistributionBeanQuery extends AbstractBeanQuery pinnedControllerId); } else if (distributionTags.isEmpty() && Strings.isNullOrEmpty(searchText) && !noTagClicked) { // if no search filters available - distBeans = getDistributionSetManagement() - .findDistributionSetsAll(new OffsetBasedPageRequest(startIndex, count, sort), false, true); + distBeans = getDistributionSetManagement().findDistributionSetsByDeletedAndOrCompleted( + new OffsetBasedPageRequest(startIndex, count, sort), false, true); } else { final DistributionSetFilter distributionSetFilter = new DistributionSetFilterBuilder().setIsDeleted(false) .setIsComplete(true).setSearchText(searchText).setSelectDSWithNoTag(noTagClicked) @@ -129,7 +129,6 @@ public class DistributionBeanQuery extends AbstractBeanQuery proxyDistribution.setVersion(distributionSet.getVersion()); proxyDistribution.setCreatedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getCreatedAt())); proxyDistribution.setLastModifiedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getLastModifiedAt())); - proxyDistribution.setDescription(distributionSet.getDescription()); proxyDistribution.setCreatedByUser(UserDetailsFormatter.loadAndFormatCreatedBy(distributionSet)); proxyDistribution.setModifiedByUser(UserDetailsFormatter.loadAndFormatLastModifiedBy(distributionSet)); proxyDistribution.setNameVersion( @@ -152,8 +151,8 @@ public class DistributionBeanQuery extends AbstractBeanQuery pinnedControllerId); } else if (distributionTags.isEmpty() && Strings.isNullOrEmpty(searchText) && !noTagClicked) { // if no search filters available - firstPageDistributionSets = getDistributionSetManagement() - .findDistributionSetsAll(new PageRequest(0, SPUIDefinitions.PAGE_SIZE, sort), false, true); + firstPageDistributionSets = getDistributionSetManagement().findDistributionSetsByDeletedAndOrCompleted( + new PageRequest(0, SPUIDefinitions.PAGE_SIZE, sort), false, true); } else { final DistributionSetFilter distributionSetFilter = new DistributionSetFilterBuilder().setIsDeleted(false) .setIsComplete(true).setSearchText(searchText).setSelectDSWithNoTag(noTagClicked) diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionTable.java index 12af7de02..28e280bff 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionTable.java @@ -21,10 +21,10 @@ import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.model.DistributionSet; -import org.eclipse.hawkbit.repository.model.DistributionSetIdName; import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetIdName; +import org.eclipse.hawkbit.ui.common.DistributionSetIdName; import org.eclipse.hawkbit.ui.common.table.AbstractNamedVersionTable; import org.eclipse.hawkbit.ui.common.table.AbstractTable; import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/CreateUpdateDistributionTagLayoutWindow.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/CreateUpdateDistributionTagLayoutWindow.java index 4d63753fe..e37086e65 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/CreateUpdateDistributionTagLayoutWindow.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/CreateUpdateDistributionTagLayoutWindow.java @@ -11,9 +11,10 @@ package org.eclipse.hawkbit.ui.management.dstag; import java.util.ArrayList; import java.util.List; -import org.eclipse.hawkbit.eventbus.event.DistributionSetTagCreatedBulkEvent; -import org.eclipse.hawkbit.eventbus.event.DistributionSetTagDeletedEvent; -import org.eclipse.hawkbit.eventbus.event.DistributionSetTagUpdateEvent; +import org.eclipse.hawkbit.repository.EntityFactory; +import org.eclipse.hawkbit.repository.eventbus.event.DistributionSetTagCreatedBulkEvent; +import org.eclipse.hawkbit.repository.eventbus.event.DistributionSetTagDeletedEvent; +import org.eclipse.hawkbit.repository.eventbus.event.DistributionSetTagUpdateEvent; import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.management.tag.CreateUpdateTagLayout; @@ -48,6 +49,9 @@ public class CreateUpdateDistributionTagLayoutWindow extends CreateUpdateTagLayo @Autowired private transient UINotification uiNotification; + @Autowired + private transient EntityFactory entityFactory; + private static final String MISSING_TAG_NAME = "message.error.missing.tagname"; private static final String TARGET_TAG_NAME_DYNAMIC_STYLE = "new-target-tag-name"; private static final String MSG_TEXTFIELD_NAME = "textfield.name"; @@ -98,14 +102,13 @@ public class CreateUpdateDistributionTagLayoutWindow extends CreateUpdateTagLayo final String tagDescValue = HawkbitCommonUtil.trimAndNullIfEmpty(tagDesc.getValue()); if (null != tagNameValue) { - DistributionSetTag newDistTag = new DistributionSetTag(tagNameValue); - if (null != tagDescValue) { - newDistTag.setDescription(tagDescValue); - } - newDistTag.setColour(new Color(0, 146, 58).getCSS()); + DistributionSetTag newDistTag = entityFactory.generateDistributionSetTag(tagNameValue, tagDescValue, + new Color(0, 146, 58).getCSS()); + if (colorPicked != null) { newDistTag.setColour(colorPicked); } + newDistTag = tagManagement.createDistributionSetTag(newDistTag); uiNotification.displaySuccess(i18n.get("message.save.success", new Object[] { newDistTag.getName() })); resetDistTagValues(); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/DistributionTagButtons.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/DistributionTagButtons.java index 59ecd09b7..deaace968 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/DistributionTagButtons.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/DistributionTagButtons.java @@ -11,9 +11,10 @@ package org.eclipse.hawkbit.ui.management.dstag; import java.util.HashMap; import java.util.Map; -import org.eclipse.hawkbit.eventbus.event.DistributionSetTagCreatedBulkEvent; -import org.eclipse.hawkbit.eventbus.event.DistributionSetTagDeletedEvent; -import org.eclipse.hawkbit.eventbus.event.DistributionSetTagUpdateEvent; +import org.eclipse.hawkbit.repository.EntityFactory; +import org.eclipse.hawkbit.repository.eventbus.event.DistributionSetTagCreatedBulkEvent; +import org.eclipse.hawkbit.repository.eventbus.event.DistributionSetTagDeletedEvent; +import org.eclipse.hawkbit.repository.eventbus.event.DistributionSetTagUpdateEvent; import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.ui.common.filterlayout.AbstractFilterButtonClickBehaviour; import org.eclipse.hawkbit.ui.common.filterlayout.AbstractFilterButtons; @@ -54,10 +55,13 @@ public class DistributionTagButtons extends AbstractFilterButtons { @Autowired private ManagementUIState managementUIState; + @Autowired + private transient EntityFactory entityFactory; + @Override public void init(final AbstractFilterButtonClickBehaviour filterButtonClickBehaviour) { super.init(filterButtonClickBehaviour); - addNewTag(new DistributionSetTag("NO TAG")); + addNewTag(entityFactory.generateDistributionSetTag("NO TAG")); } @EventBusListenerMethod(scope = EventScope.SESSION) @@ -139,7 +143,7 @@ public class DistributionTagButtons extends AbstractFilterButtons { private void refreshTagTable() { ((LazyQueryContainer) getContainerDataSource()).refresh(); removeGeneratedColumn(FILTER_BUTTON_COLUMN); - addNewTag(new DistributionSetTag("NO TAG")); + addNewTag(entityFactory.generateDistributionSetTag("NO TAG")); addColumn(); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/DistributionTagDropEvent.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/DistributionTagDropEvent.java index 4b32ab407..d2a010ee7 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/DistributionTagDropEvent.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/DistributionTagDropEvent.java @@ -14,8 +14,8 @@ import java.util.stream.Collectors; import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.SpPermissionChecker; -import org.eclipse.hawkbit.repository.model.DistributionSetIdName; import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult; +import org.eclipse.hawkbit.ui.common.DistributionSetIdName; import org.eclipse.hawkbit.ui.common.table.AbstractTable; import org.eclipse.hawkbit.ui.management.state.DistributionTableFilters; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/CountMessageLabel.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/CountMessageLabel.java index a605a831d..ed6d033bd 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/CountMessageLabel.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/CountMessageLabel.java @@ -14,9 +14,9 @@ import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.eclipse.hawkbit.repository.TargetManagement; -import org.eclipse.hawkbit.repository.model.DistributionSetIdName; import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; +import org.eclipse.hawkbit.ui.common.DistributionSetIdName; import org.eclipse.hawkbit.ui.management.event.ManagementUIEvent; import org.eclipse.hawkbit.ui.management.event.PinUnpinEvent; import org.eclipse.hawkbit.ui.management.event.TargetTableEvent; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/DeleteActionsLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/DeleteActionsLayout.java index 2eb64b13f..6c3149109 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/DeleteActionsLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/DeleteActionsLayout.java @@ -11,8 +11,8 @@ package org.eclipse.hawkbit.ui.management.footer; import java.util.Set; import org.eclipse.hawkbit.repository.TagManagement; -import org.eclipse.hawkbit.repository.model.DistributionSetIdName; import org.eclipse.hawkbit.repository.model.TargetIdName; +import org.eclipse.hawkbit.ui.common.DistributionSetIdName; import org.eclipse.hawkbit.ui.common.footer.AbstractDeleteActionsLayout; import org.eclipse.hawkbit.ui.common.table.AbstractTable; import org.eclipse.hawkbit.ui.management.event.BulkUploadPopupEvent; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/ManangementConfirmationWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/ManangementConfirmationWindowLayout.java index 52cca5794..1bb1c8b3f 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/ManangementConfirmationWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/ManangementConfirmationWindowLayout.java @@ -23,10 +23,10 @@ import org.eclipse.hawkbit.repository.DeploymentManagement; import org.eclipse.hawkbit.repository.DistributionSetAssignmentResult; import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.TargetManagement; -import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.ActionType; -import org.eclipse.hawkbit.repository.model.DistributionSetIdName; +import org.eclipse.hawkbit.repository.model.RepositoryModelConstants; import org.eclipse.hawkbit.repository.model.TargetIdName; +import org.eclipse.hawkbit.ui.common.DistributionSetIdName; import org.eclipse.hawkbit.ui.common.confirmwindow.layout.AbstractConfirmationWindowLayout; import org.eclipse.hawkbit.ui.common.confirmwindow.layout.ConfirmationTab; import org.eclipse.hawkbit.ui.management.event.PinUnpinEvent; @@ -148,7 +148,7 @@ public class ManangementConfirmationWindowLayout extends AbstractConfirmationWin final long forcedTimeStamp = (((ActionTypeOptionGroupLayout.ActionTypeOption) actionTypeOptionGroupLayout .getActionTypeOptionGroup().getValue()) == ActionTypeOption.AUTO_FORCED) ? actionTypeOptionGroupLayout.getForcedTimeDateField().getValue().getTime() - : Action.NO_FORCE_TIME; + : RepositoryModelConstants.NO_FORCE_TIME; final Map> saveAssignedList = new HashMap<>(); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/ManagementUIState.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/ManagementUIState.java index 653075735..e7ecfbfae 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/ManagementUIState.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/ManagementUIState.java @@ -17,8 +17,8 @@ import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; -import org.eclipse.hawkbit.repository.model.DistributionSetIdName; import org.eclipse.hawkbit.repository.model.TargetIdName; +import org.eclipse.hawkbit.ui.common.DistributionSetIdName; import org.eclipse.hawkbit.ui.common.ManagmentEntityState; import org.springframework.beans.factory.annotation.Autowired; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/TargetBulkUpload.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/TargetBulkUpload.java index d69f91b64..4d658516a 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/TargetBulkUpload.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/TargetBulkUpload.java @@ -12,7 +12,7 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.List; -import org.eclipse.hawkbit.repository.model.DistributionSetIdName; +import org.eclipse.hawkbit.ui.common.DistributionSetIdName; /** * Hold details for target bulk upload window. diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/TargetTableFilters.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/TargetTableFilters.java index 6d8297345..289927660 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/TargetTableFilters.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/TargetTableFilters.java @@ -13,9 +13,9 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; -import org.eclipse.hawkbit.repository.model.DistributionSetIdName; import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; +import org.eclipse.hawkbit.ui.common.DistributionSetIdName; import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.VaadinSessionScope; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/BulkUploadHandler.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/BulkUploadHandler.java index 2369893c7..d6a613cf7 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/BulkUploadHandler.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/BulkUploadHandler.java @@ -26,11 +26,12 @@ import java.util.concurrent.Executor; import org.eclipse.hawkbit.repository.DeploymentManagement; import org.eclipse.hawkbit.repository.DistributionSetManagement; +import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.TagManagement; import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.model.Action.ActionType; -import org.eclipse.hawkbit.repository.model.DistributionSetIdName; import org.eclipse.hawkbit.repository.model.Target; +import org.eclipse.hawkbit.ui.common.DistributionSetIdName; import org.eclipse.hawkbit.ui.common.tagdetails.AbstractTagToken.TagData; import org.eclipse.hawkbit.ui.management.event.BulkUploadValidationMessageEvent; import org.eclipse.hawkbit.ui.management.event.TargetTableEvent; @@ -97,6 +98,8 @@ public class BulkUploadHandler extends CustomComponent final TargetBulkUpdateWindowLayout targetBulkUpdateWindowLayout; + private final EntityFactory entityFactory; + /** * * @param targetBulkUpdateWindowLayout @@ -124,6 +127,7 @@ public class BulkUploadHandler extends CustomComponent this.eventBus = targetBulkUpdateWindowLayout.getEventBus(); distributionSetManagement = SpringContextHelper.getBean(DistributionSetManagement.class); tagManagement = SpringContextHelper.getBean(TagManagement.class); + entityFactory = SpringContextHelper.getBean(EntityFactory.class); } /** @@ -380,7 +384,7 @@ public class BulkUploadHandler extends CustomComponent final String newDesc = HawkbitCommonUtil.trimAndNullIfEmpty(descTextArea.getValue()); /* create new target entity */ - final Target newTarget = new Target(newControllerId); + final Target newTarget = entityFactory.generateTarget(newControllerId); setTargetValues(newTarget, newName, newDesc); targetManagement.createTarget(newTarget); managementUIState.getTargetTableFilters().getBulkUpload().getTargetsCreated().add(newControllerId); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetAddUpdateWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetAddUpdateWindowLayout.java index abc0fc10c..846744587 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetAddUpdateWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetAddUpdateWindowLayout.java @@ -11,6 +11,7 @@ package org.eclipse.hawkbit.ui.management.targettable; import java.util.HashSet; import java.util.Set; +import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetIdName; @@ -69,6 +70,9 @@ public class TargetAddUpdateWindowLayout extends CustomComponent { @Autowired private transient UINotification uINotification; + + @Autowired + private transient EntityFactory entityFactory; private TextField controllerIDTextField; private TextField nameTextField; @@ -245,7 +249,7 @@ public class TargetAddUpdateWindowLayout extends CustomComponent { final String newDesc = HawkbitCommonUtil.trimAndNullIfEmpty(descTextArea.getValue()); /* create new target entity */ - Target newTarget = new Target(newControlllerId); + Target newTarget = entityFactory.generateTarget(newControlllerId); /* set values to the new target entity */ setTargetValues(newTarget, newName, newDesc); /* save new target */ diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetBulkUpdateWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetBulkUpdateWindowLayout.java index 69c0b7377..2103f7fde 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetBulkUpdateWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetBulkUpdateWindowLayout.java @@ -17,8 +17,8 @@ import javax.annotation.PreDestroy; import org.eclipse.hawkbit.repository.DeploymentManagement; import org.eclipse.hawkbit.repository.TargetManagement; -import org.eclipse.hawkbit.repository.model.DistributionSetIdName; import org.eclipse.hawkbit.ui.UiProperties; +import org.eclipse.hawkbit.ui.common.DistributionSetIdName; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmallNoBorder; import org.eclipse.hawkbit.ui.management.dstable.DistributionBeanQuery; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTable.java index 697166f5a..af1e3ebbe 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTable.java @@ -18,19 +18,19 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; -import org.eclipse.hawkbit.eventbus.event.TargetCreatedEvent; import org.eclipse.hawkbit.eventbus.event.TargetDeletedEvent; -import org.eclipse.hawkbit.eventbus.event.TargetInfoUpdateEvent; import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.TargetManagement; -import org.eclipse.hawkbit.repository.model.DistributionSetIdName; +import org.eclipse.hawkbit.repository.eventbus.event.TargetCreatedEvent; +import org.eclipse.hawkbit.repository.eventbus.event.TargetInfoUpdateEvent; 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.TargetTagAssignmentResult; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; +import org.eclipse.hawkbit.ui.common.DistributionSetIdName; import org.eclipse.hawkbit.ui.common.ManagmentEntityState; import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; import org.eclipse.hawkbit.ui.common.table.AbstractTable; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTableHeader.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTableHeader.java index 13db548d9..b6379729b 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTableHeader.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTableHeader.java @@ -10,7 +10,7 @@ package org.eclipse.hawkbit.ui.management.targettable; import java.util.Set; -import org.eclipse.hawkbit.repository.model.DistributionSetIdName; +import org.eclipse.hawkbit.ui.common.DistributionSetIdName; import org.eclipse.hawkbit.ui.common.table.AbstractTable; import org.eclipse.hawkbit.ui.common.table.AbstractTableHeader; import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/CreateUpdateTargetTagLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/CreateUpdateTargetTagLayout.java index 79a44c38c..80de83982 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/CreateUpdateTargetTagLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/CreateUpdateTargetTagLayout.java @@ -11,9 +11,10 @@ package org.eclipse.hawkbit.ui.management.targettag; import java.util.ArrayList; import java.util.List; -import org.eclipse.hawkbit.eventbus.event.TargetTagCreatedBulkEvent; -import org.eclipse.hawkbit.eventbus.event.TargetTagDeletedEvent; -import org.eclipse.hawkbit.eventbus.event.TargetTagUpdateEvent; +import org.eclipse.hawkbit.repository.EntityFactory; +import org.eclipse.hawkbit.repository.eventbus.event.TargetTagCreatedBulkEvent; +import org.eclipse.hawkbit.repository.eventbus.event.TargetTagDeletedEvent; +import org.eclipse.hawkbit.repository.eventbus.event.TargetTagUpdateEvent; import org.eclipse.hawkbit.repository.model.TargetTag; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.management.tag.CreateUpdateTagLayout; @@ -49,6 +50,9 @@ public class CreateUpdateTargetTagLayout extends CreateUpdateTagLayout { @Autowired private transient UINotification uiNotification; + @Autowired + private transient EntityFactory entityFactory; + private Window targetTagWindow; @Override @@ -193,7 +197,7 @@ public class CreateUpdateTargetTagLayout extends CreateUpdateTagLayout { final String tagNameValue = HawkbitCommonUtil.trimAndNullIfEmpty(tagName.getValue()); final String tagDescValue = HawkbitCommonUtil.trimAndNullIfEmpty(tagDesc.getValue()); if (null != tagNameValue) { - TargetTag newTargetTag = new TargetTag(tagNameValue); + TargetTag newTargetTag = entityFactory.generateTargetTag(tagNameValue); if (null != tagDescValue) { newTargetTag.setDescription(tagDescValue); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/TargetTagFilterButtons.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/TargetTagFilterButtons.java index 33ed63b45..e9d3f6e1e 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/TargetTagFilterButtons.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/TargetTagFilterButtons.java @@ -12,11 +12,12 @@ import java.util.List; import java.util.Set; import java.util.stream.Collectors; -import org.eclipse.hawkbit.eventbus.event.TargetTagCreatedBulkEvent; -import org.eclipse.hawkbit.eventbus.event.TargetTagDeletedEvent; -import org.eclipse.hawkbit.eventbus.event.TargetTagUpdateEvent; +import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.TargetManagement; +import org.eclipse.hawkbit.repository.eventbus.event.TargetTagCreatedBulkEvent; +import org.eclipse.hawkbit.repository.eventbus.event.TargetTagDeletedEvent; +import org.eclipse.hawkbit.repository.eventbus.event.TargetTagUpdateEvent; import org.eclipse.hawkbit.repository.model.TargetIdName; import org.eclipse.hawkbit.repository.model.TargetTag; import org.eclipse.hawkbit.repository.model.TargetTagAssignmentResult; @@ -75,6 +76,9 @@ public class TargetTagFilterButtons extends AbstractFilterButtons { @Autowired private SpPermissionChecker permChecker; + @Autowired + private transient EntityFactory entityFactory; + @Autowired private transient TargetManagement targetManagement; @@ -90,7 +94,7 @@ public class TargetTagFilterButtons extends AbstractFilterButtons { public void init(final TargetTagFilterButtonClick filterButtonClickBehaviour) { this.filterButtonClickBehaviour = filterButtonClickBehaviour; super.init(filterButtonClickBehaviour); - addNewTargetTag(new TargetTag("NO TAG")); + addNewTargetTag(entityFactory.generateTargetTag("NO TAG")); } @EventBusListenerMethod(scope = EventScope.SESSION) @@ -290,7 +294,7 @@ public class TargetTagFilterButtons extends AbstractFilterButtons { private void refreshContainer() { removeGeneratedColumn(FILTER_BUTTON_COLUMN); ((LazyQueryContainer) getContainerDataSource()).refresh(); - addNewTargetTag(new TargetTag("NO TAG")); + addNewTargetTag(entityFactory.generateTargetTag("NO TAG")); addColumn(); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/AddUpdateRolloutWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/AddUpdateRolloutWindowLayout.java index 8e671f6e6..a796b2912 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/AddUpdateRolloutWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/AddUpdateRolloutWindowLayout.java @@ -13,20 +13,22 @@ import java.util.Date; import java.util.List; import org.eclipse.hawkbit.repository.DistributionSetManagement; +import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.RolloutManagement; import org.eclipse.hawkbit.repository.TargetManagement; -import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.ActionType; -import org.eclipse.hawkbit.repository.model.DistributionSetIdName; +import org.eclipse.hawkbit.repository.model.RepositoryModelConstants; 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.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.ui.UiProperties; +import org.eclipse.hawkbit.ui.common.DistributionSetIdName; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmallNoBorder; import org.eclipse.hawkbit.ui.filtermanagement.TargetFilterBeanQuery; @@ -107,6 +109,9 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { @Autowired private transient UiProperties uiProperties; + @Autowired + private transient EntityFactory entityFactory; + @Autowired private I18N i18n; @@ -460,7 +465,7 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { return (((ActionTypeOptionGroupLayout.ActionTypeOption) actionTypeOptionGroupLayout.getActionTypeOptionGroup() .getValue()) == ActionTypeOption.AUTO_FORCED) ? actionTypeOptionGroupLayout.getForcedTimeDateField().getValue().getTime() - : Action.NO_FORCE_TIME; + : RepositoryModelConstants.NO_FORCE_TIME; } private ActionType getActionType() { @@ -478,12 +483,12 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { } private Rollout saveRollout() { - Rollout rolloutToCreate = new Rollout(); + Rollout rolloutToCreate = entityFactory.generateRollout(); final int amountGroup = Integer.parseInt(noOfGroups.getValue()); final String targetFilter = getTargetFilterQuery(); final int errorThresoldPercent = getErrorThresoldPercentage(amountGroup); - final RolloutGroupConditions conditions = new RolloutGroup.RolloutGroupConditionBuilder() + final RolloutGroupConditions conditions = new RolloutGroupConditionBuilder() .successAction(RolloutGroupSuccessAction.NEXTGROUP, null) .successCondition(RolloutGroupSuccessCondition.THRESHOLD, triggerThreshold.getValue()) .errorCondition(RolloutGroupErrorCondition.THRESHOLD, String.valueOf(errorThresoldPercent)) @@ -751,7 +756,7 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { rolloutForEdit = rolloutManagement.findRolloutById(rolloutId); rolloutName.setValue(rolloutForEdit.getName()); description.setValue(rolloutForEdit.getDescription()); - distributionSet.setValue(rolloutForEdit.getDistributionSet().getDistributionSetIdName()); + distributionSet.setValue(DistributionSetIdName.generate(rolloutForEdit.getDistributionSet())); final List rolloutGroups = rolloutForEdit.getRolloutGroups(); setThresoldValues(rolloutGroups); setActionType(rolloutForEdit); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/DistributionBeanQuery.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/DistributionBeanQuery.java index 75d2741af..0a8ebd25d 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/DistributionBeanQuery.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/DistributionBeanQuery.java @@ -14,10 +14,10 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import org.eclipse.hawkbit.repository.DistributionSetFilter; -import org.eclipse.hawkbit.repository.DistributionSetFilter.DistributionSetFilterBuilder; import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.repository.model.DistributionSetFilter; +import org.eclipse.hawkbit.repository.model.DistributionSetFilter.DistributionSetFilterBuilder; import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; import org.eclipse.hawkbit.ui.components.ProxyDistribution; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; @@ -113,7 +113,6 @@ public class DistributionBeanQuery extends AbstractBeanQuery proxyDistribution.setVersion(distributionSet.getVersion()); proxyDistribution.setCreatedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getCreatedAt())); proxyDistribution.setLastModifiedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getLastModifiedAt())); - proxyDistribution.setDescription(distributionSet.getDescription()); proxyDistribution.setCreatedByUser(UserDetailsFormatter.loadAndFormatCreatedBy(distributionSet)); proxyDistribution.setModifiedByUser(UserDetailsFormatter.loadAndFormatLastModifiedBy(distributionSet)); proxyDistribution.setIsComplete(distributionSet.isComplete()); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/ProxyRollout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/ProxyRollout.java index 04c6659a5..88e7204aa 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/ProxyRollout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/ProxyRollout.java @@ -10,8 +10,10 @@ package org.eclipse.hawkbit.ui.rollout.rollout; import java.util.Set; -import org.eclipse.hawkbit.repository.model.Rollout; +import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.repository.model.Rollout.RolloutStatus; import org.eclipse.hawkbit.repository.model.SoftwareModule; +import org.eclipse.hawkbit.repository.model.TotalTargetCountStatus; import org.eclipse.hawkbit.ui.customrenderers.client.renderers.RolloutRendererData; import com.vaadin.server.FontAwesome; @@ -20,7 +22,7 @@ import com.vaadin.server.FontAwesome; * Proxy rollout with custom properties. * */ -public class ProxyRollout extends Rollout { +public class ProxyRollout { private static final long serialVersionUID = 4539849939617681918L; @@ -46,6 +48,17 @@ public class ProxyRollout extends Rollout { private Set swModules; + private Long id; + private String name; + private String version; + private String description; + private DistributionSet distributionSet; + private String createdBy; + private String lastModifiedBy; + private long forcedTime; + private RolloutStatus status; + private TotalTargetCountStatus totalTargetCountStatus; + /** * @return the isRequiredMigrationStep */ @@ -59,7 +72,7 @@ public class ProxyRollout extends Rollout { * the isRequiredMigrationStep to set */ - public void setIsRequiredMigrationStep(Boolean isRequiredMigrationStep) { + public void setIsRequiredMigrationStep(final Boolean isRequiredMigrationStep) { this.isRequiredMigrationStep = isRequiredMigrationStep; } @@ -76,7 +89,7 @@ public class ProxyRollout extends Rollout { * the discription to set */ - public void setDiscription(String discription) { + public void setDiscription(final String discription) { this.discription = discription; } @@ -92,7 +105,7 @@ public class ProxyRollout extends Rollout { * the type to set */ - public void setType(String type) { + public void setType(final String type) { this.type = type; } @@ -108,7 +121,7 @@ public class ProxyRollout extends Rollout { * @param swModules * Set to set */ - public void setSwModules(Set swModules) { + public void setSwModules(final Set swModules) { this.swModules = swModules; } @@ -116,7 +129,7 @@ public class ProxyRollout extends Rollout { return rolloutRendererData; } - public void setRolloutRendererData(RolloutRendererData rendererData) { + public void setRolloutRendererData(final RolloutRendererData rendererData) { this.rolloutRendererData = rendererData; } @@ -214,4 +227,83 @@ public class ProxyRollout extends Rollout { return FontAwesome.CIRCLE_O.getHtml(); } + public Long getId() { + return id; + } + + public void setId(final Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public String getVersion() { + return version; + } + + public void setVersion(final String version) { + this.version = version; + } + + public String getDescription() { + return description; + } + + public void setDescription(final String description) { + this.description = description; + } + + public DistributionSet getDistributionSet() { + return distributionSet; + } + + public void setDistributionSet(final DistributionSet distributionSet) { + this.distributionSet = distributionSet; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(final String createdBy) { + this.createdBy = createdBy; + } + + public String getLastModifiedBy() { + return lastModifiedBy; + } + + public void setLastModifiedBy(final String lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + public long getForcedTime() { + return forcedTime; + } + + public void setForcedTime(final long forcedTime) { + this.forcedTime = forcedTime; + } + + public RolloutStatus getStatus() { + return status; + } + + public void setStatus(final RolloutStatus status) { + this.status = status; + } + + public TotalTargetCountStatus getTotalTargetCountStatus() { + return totalTargetCountStatus; + } + + public void setTotalTargetCountStatus(final TotalTargetCountStatus totalTargetCountStatus) { + this.totalTargetCountStatus = totalTargetCountStatus; + } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutBeanQuery.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutBeanQuery.java index 8a9675564..0bfa349d0 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutBeanQuery.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutBeanQuery.java @@ -138,8 +138,6 @@ public class RolloutBeanQuery extends AbstractBeanQuery { final TotalTargetCountStatus totalTargetCountActionStatus = rollout.getTotalTargetCountStatus(); proxyRollout.setTotalTargetCountStatus(totalTargetCountActionStatus); proxyRollout.setTotalTargetsCount(String.valueOf(rollout.getTotalTargets())); - - proxyRollout.setDescription(distributionSet.getDescription()); proxyRollout.setType(distributionSet.getType().getName()); proxyRollout.setIsRequiredMigrationStep(distributionSet.isRequiredMigrationStep()); proxyRollout.setSwModules(distributionSet.getModules()); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutListGrid.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutListGrid.java index 20fc14431..ad6ef94d8 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutListGrid.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutListGrid.java @@ -21,9 +21,9 @@ import java.util.Locale; import java.util.Map; import java.util.Set; -import org.eclipse.hawkbit.eventbus.event.RolloutChangeEvent; import org.eclipse.hawkbit.repository.RolloutManagement; import org.eclipse.hawkbit.repository.SpPermissionChecker; +import org.eclipse.hawkbit.repository.eventbus.event.RolloutChangeEvent; import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.Rollout.RolloutStatus; import org.eclipse.hawkbit.repository.model.SoftwareModule; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/ProxyRolloutGroup.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/ProxyRolloutGroup.java index 08f2c0a0b..05a6ec410 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/ProxyRolloutGroup.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/ProxyRolloutGroup.java @@ -8,212 +8,354 @@ */ package org.eclipse.hawkbit.ui.rollout.rolloutgroup; -import org.eclipse.hawkbit.repository.model.RolloutGroup; +import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupErrorAction; +import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupErrorCondition; +import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupStatus; +import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessAction; +import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessCondition; +import org.eclipse.hawkbit.repository.model.TotalTargetCountStatus; import org.eclipse.hawkbit.ui.customrenderers.client.renderers.RolloutRendererData; /** * Proxy rollout group with renderer properties. * */ -public class ProxyRolloutGroup extends RolloutGroup { +public class ProxyRolloutGroup { - private static final long serialVersionUID = -2745056813306692356L; + private static final long serialVersionUID = -2745056813306692356L; - private String createdDate; + private String createdDate; - private String modifiedDate; + private String modifiedDate; - private String finishedPercentage; + private String finishedPercentage; - private Long runningTargetsCount; + private Long runningTargetsCount; - private Long scheduledTargetsCount; + private Long scheduledTargetsCount; - private Long cancelledTargetsCount; + private Long cancelledTargetsCount; - private Long errorTargetsCount; + private Long errorTargetsCount; - private Long finishedTargetsCount; + private Long finishedTargetsCount; - private Long notStartedTargetsCount; + private Long notStartedTargetsCount; - private Boolean isActionRecieved = Boolean.FALSE; + private Boolean isActionRecieved = Boolean.FALSE; - private String totalTargetsCount; + private String totalTargetsCount; - private RolloutRendererData rolloutRendererData; + private Long id; + private String name; + private String description; + private String createdBy; + private String lastModifiedBy; + private RolloutGroupStatus status; + private TotalTargetCountStatus totalTargetCountStatus; - public RolloutRendererData getRolloutRendererData() { - return rolloutRendererData; - } + private RolloutGroupSuccessCondition successCondition; + private String successConditionExp; + private RolloutGroupSuccessAction successAction; + private String successActionExp; + private RolloutGroupErrorCondition errorCondition; + private String errorConditionExp; + private RolloutGroupErrorAction errorAction; + private String errorActionExp; - public void setRolloutRendererData(RolloutRendererData rendererData) { - this.rolloutRendererData = rendererData; - } + private RolloutRendererData rolloutRendererData; - /** - * @return the createdDate - */ - public String getCreatedDate() { - return createdDate; - } + public RolloutRendererData getRolloutRendererData() { + return rolloutRendererData; + } - /** - * @param createdDate - * the createdDate to set - */ - public void setCreatedDate(final String createdDate) { - this.createdDate = createdDate; - } + public void setRolloutRendererData(final RolloutRendererData rendererData) { + this.rolloutRendererData = rendererData; + } - /** - * @return the modifiedDate - */ - public String getModifiedDate() { - return modifiedDate; - } + /** + * @return the createdDate + */ + public String getCreatedDate() { + return createdDate; + } - /** - * @param modifiedDate - * the modifiedDate to set - */ - public void setModifiedDate(final String modifiedDate) { - this.modifiedDate = modifiedDate; - } + /** + * @param createdDate + * the createdDate to set + */ + public void setCreatedDate(final String createdDate) { + this.createdDate = createdDate; + } - /** - * @return the finishedPercentage - */ - public String getFinishedPercentage() { - return finishedPercentage; - } + /** + * @return the modifiedDate + */ + public String getModifiedDate() { + return modifiedDate; + } - /** - * @param finishedPercentage - * the finishedPercentage to set - */ - public void setFinishedPercentage(final String finishedPercentage) { - this.finishedPercentage = finishedPercentage; - } + /** + * @param modifiedDate + * the modifiedDate to set + */ + public void setModifiedDate(final String modifiedDate) { + this.modifiedDate = modifiedDate; + } - /** - * @return the runningTargetsCount - */ - public Long getRunningTargetsCount() { - return runningTargetsCount; - } + /** + * @return the finishedPercentage + */ + public String getFinishedPercentage() { + return finishedPercentage; + } - /** - * @param runningTargetsCount - * the runningTargetsCount to set - */ - public void setRunningTargetsCount(final Long runningTargetsCount) { - this.runningTargetsCount = runningTargetsCount; - } + /** + * @param finishedPercentage + * the finishedPercentage to set + */ + public void setFinishedPercentage(final String finishedPercentage) { + this.finishedPercentage = finishedPercentage; + } - /** - * @return the scheduledTargetsCount - */ - public Long getScheduledTargetsCount() { - return scheduledTargetsCount; - } + /** + * @return the runningTargetsCount + */ + public Long getRunningTargetsCount() { + return runningTargetsCount; + } - /** - * @param scheduledTargetsCount - * the scheduledTargetsCount to set - */ - public void setScheduledTargetsCount(final Long scheduledTargetsCount) { - this.scheduledTargetsCount = scheduledTargetsCount; - } + /** + * @param runningTargetsCount + * the runningTargetsCount to set + */ + public void setRunningTargetsCount(final Long runningTargetsCount) { + this.runningTargetsCount = runningTargetsCount; + } - /** - * @return the cancelledTargetsCount - */ - public Long getCancelledTargetsCount() { - return cancelledTargetsCount; - } + /** + * @return the scheduledTargetsCount + */ + public Long getScheduledTargetsCount() { + return scheduledTargetsCount; + } - /** - * @param cancelledTargetsCount - * the cancelledTargetsCount to set - */ - public void setCancelledTargetsCount(final Long cancelledTargetsCount) { - this.cancelledTargetsCount = cancelledTargetsCount; - } + /** + * @param scheduledTargetsCount + * the scheduledTargetsCount to set + */ + public void setScheduledTargetsCount(final Long scheduledTargetsCount) { + this.scheduledTargetsCount = scheduledTargetsCount; + } - /** - * @return the errorTargetsCount - */ - public Long getErrorTargetsCount() { - return errorTargetsCount; - } + /** + * @return the cancelledTargetsCount + */ + public Long getCancelledTargetsCount() { + return cancelledTargetsCount; + } - /** - * @param errorTargetsCount - * the errorTargetsCount to set - */ - public void setErrorTargetsCount(final Long errorTargetsCount) { - this.errorTargetsCount = errorTargetsCount; - } + /** + * @param cancelledTargetsCount + * the cancelledTargetsCount to set + */ + public void setCancelledTargetsCount(final Long cancelledTargetsCount) { + this.cancelledTargetsCount = cancelledTargetsCount; + } - /** - * @return the finishedTargetsCount - */ - public Long getFinishedTargetsCount() { - return finishedTargetsCount; - } + /** + * @return the errorTargetsCount + */ + public Long getErrorTargetsCount() { + return errorTargetsCount; + } - /** - * @param finishedTargetsCount - * the finishedTargetsCount to set - */ - public void setFinishedTargetsCount(final Long finishedTargetsCount) { - this.finishedTargetsCount = finishedTargetsCount; - } + /** + * @param errorTargetsCount + * the errorTargetsCount to set + */ + public void setErrorTargetsCount(final Long errorTargetsCount) { + this.errorTargetsCount = errorTargetsCount; + } - /** - * @return the notStartedTargetsCount - */ - public Long getNotStartedTargetsCount() { - return notStartedTargetsCount; - } + /** + * @return the finishedTargetsCount + */ + public Long getFinishedTargetsCount() { + return finishedTargetsCount; + } - /** - * @param notStartedTargetsCount - * the notStartedTargetsCount to set - */ - public void setNotStartedTargetsCount(final Long notStartedTargetsCount) { - this.notStartedTargetsCount = notStartedTargetsCount; - } + /** + * @param finishedTargetsCount + * the finishedTargetsCount to set + */ + public void setFinishedTargetsCount(final Long finishedTargetsCount) { + this.finishedTargetsCount = finishedTargetsCount; + } - /** - * @return the isActionRecieved - */ - public Boolean getIsActionRecieved() { - return isActionRecieved; - } + /** + * @return the notStartedTargetsCount + */ + public Long getNotStartedTargetsCount() { + return notStartedTargetsCount; + } - /** - * @param isActionRecieved - * the isActionRecieved to set - */ - public void setIsActionRecieved(final Boolean isActionRecieved) { - this.isActionRecieved = isActionRecieved; - } + /** + * @param notStartedTargetsCount + * the notStartedTargetsCount to set + */ + public void setNotStartedTargetsCount(final Long notStartedTargetsCount) { + this.notStartedTargetsCount = notStartedTargetsCount; + } - /** - * @return the totalTargetsCount - */ - public String getTotalTargetsCount() { - return totalTargetsCount; - } + /** + * @return the isActionRecieved + */ + public Boolean getIsActionRecieved() { + return isActionRecieved; + } - /** - * @param totalTargetsCount - * the totalTargetsCount to set - */ - public void setTotalTargetsCount(final String totalTargetsCount) { - this.totalTargetsCount = totalTargetsCount; - } + /** + * @param isActionRecieved + * the isActionRecieved to set + */ + public void setIsActionRecieved(final Boolean isActionRecieved) { + this.isActionRecieved = isActionRecieved; + } + + /** + * @return the totalTargetsCount + */ + public String getTotalTargetsCount() { + return totalTargetsCount; + } + + /** + * @param totalTargetsCount + * the totalTargetsCount to set + */ + public void setTotalTargetsCount(final String totalTargetsCount) { + this.totalTargetsCount = totalTargetsCount; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(final Long id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(final String description) { + this.description = description; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(final String createdBy) { + this.createdBy = createdBy; + } + + public String getLastModifiedBy() { + return lastModifiedBy; + } + + public void setLastModifiedBy(final String lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + public RolloutGroupStatus getStatus() { + return status; + } + + public void setStatus(final RolloutGroupStatus status) { + this.status = status; + } + + public TotalTargetCountStatus getTotalTargetCountStatus() { + return totalTargetCountStatus; + } + + public void setTotalTargetCountStatus(final TotalTargetCountStatus totalTargetCountStatus) { + this.totalTargetCountStatus = totalTargetCountStatus; + } + + public RolloutGroupSuccessCondition getSuccessCondition() { + return successCondition; + } + + public void setSuccessCondition(final RolloutGroupSuccessCondition successCondition) { + this.successCondition = successCondition; + } + + public String getSuccessConditionExp() { + return successConditionExp; + } + + public void setSuccessConditionExp(final String successConditionExp) { + this.successConditionExp = successConditionExp; + } + + public RolloutGroupSuccessAction getSuccessAction() { + return successAction; + } + + public void setSuccessAction(final RolloutGroupSuccessAction successAction) { + this.successAction = successAction; + } + + public String getSuccessActionExp() { + return successActionExp; + } + + public void setSuccessActionExp(final String successActionExp) { + this.successActionExp = successActionExp; + } + + public RolloutGroupErrorCondition getErrorCondition() { + return errorCondition; + } + + public void setErrorCondition(final RolloutGroupErrorCondition errorCondition) { + this.errorCondition = errorCondition; + } + + public String getErrorConditionExp() { + return errorConditionExp; + } + + public void setErrorConditionExp(final String errorConditionExp) { + this.errorConditionExp = errorConditionExp; + } + + public RolloutGroupErrorAction getErrorAction() { + return errorAction; + } + + public void setErrorAction(final RolloutGroupErrorAction errorAction) { + this.errorAction = errorAction; + } + + public String getErrorActionExp() { + return errorActionExp; + } + + public void setErrorActionExp(final String errorActionExp) { + this.errorActionExp = errorActionExp; + } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupListGrid.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupListGrid.java index 3706e685a..0a62e2fc8 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupListGrid.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupListGrid.java @@ -15,10 +15,10 @@ import java.util.List; import java.util.Locale; import java.util.Map; -import org.eclipse.hawkbit.eventbus.event.RolloutGroupChangeEvent; import org.eclipse.hawkbit.repository.RolloutGroupManagement; import org.eclipse.hawkbit.repository.RolloutManagement; import org.eclipse.hawkbit.repository.SpPermissionChecker; +import org.eclipse.hawkbit.repository.eventbus.event.RolloutGroupChangeEvent; import org.eclipse.hawkbit.repository.model.RolloutGroup; import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupStatus; import org.eclipse.hawkbit.repository.model.TotalTargetCountStatus; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java index a1091cd8a..da0e3e828 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/HawkbitCommonUtil.java @@ -19,15 +19,15 @@ import java.util.Map; import java.util.Map.Entry; import java.util.TimeZone; -import org.apache.commons.lang3.StringUtils; +import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.model.AssignmentResult; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.NamedEntity; +import org.eclipse.hawkbit.repository.model.PollStatus; import org.eclipse.hawkbit.repository.model.RolloutGroup; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; -import org.eclipse.hawkbit.repository.model.TargetInfo.PollStatus; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.repository.model.TotalTargetCountStatus; import org.eclipse.hawkbit.repository.model.TotalTargetCountStatus.Status; @@ -431,7 +431,7 @@ public final class HawkbitCommonUtil { return trimAndNullIfEmpty(orgText) == null ? SPUIDefinitions.SPACE : orgText; } - /** + /** * Find extra height required to increase by all the components to utilize * the full height of browser for the responsive UI. * @@ -761,10 +761,10 @@ public final class HawkbitCommonUtil { * base software module description * @return BaseSoftwareModule new base software module */ - public static SoftwareModule addNewBaseSoftware(final String bsname, final String bsversion, final String bsvendor, - final SoftwareModuleType bstype, final String description) { + public static SoftwareModule addNewBaseSoftware(final EntityFactory entityFactory, final String bsname, + final String bsversion, final String bsvendor, final SoftwareModuleType bstype, final String description) { final SoftwareManagement swMgmtService = SpringContextHelper.getBean(SoftwareManagement.class); - SoftwareModule newSWModule = new SoftwareModule(); + SoftwareModule newSWModule = entityFactory.generateSoftwareModule(); newSWModule.setType(bstype); newSWModule.setName(bsname); newSWModule.setVersion(bsversion); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUIButtonDefinitions.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUIButtonDefinitions.java index 8ab9318cf..0b727ce2a 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUIButtonDefinitions.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUIButtonDefinitions.java @@ -9,7 +9,7 @@ package org.eclipse.hawkbit.ui.utils; /** - * Constants required for Button. + * RepositoryConstants required for Button. * * * diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUIComponentIdProvider.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUIComponentIdProvider.java index 80d40104a..6649b12fe 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUIComponentIdProvider.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUIComponentIdProvider.java @@ -888,6 +888,30 @@ public final class SPUIComponentIdProvider { */ public static final String VALIDATION_STATUS_ICON_ID = "validation.status.icon"; + /** + * Artifact upload status popup - minimize button id. + */ + public static final String UPLOAD_STATUS_POPUP_MINIMIZE_BUTTON_ID = "artifact.upload.minimize.button.id"; + + /** + * Artifact upload status popup - close button id. + */ + public static final String UPLOAD_STATUS_POPUP_CLOSE_BUTTON_ID = "artifact.upload.close.button.id"; + + /** + * Artifact upload status popup - resize button id. + */ + public static final String UPLOAD_STATUS_POPUP_RESIZE_BUTTON_ID = "artifact.upload.resize.button.id"; + + /** + * Artifact upload view - upload status button id. + */ + public static final String UPLOAD_STATUS_BUTTON = "artficat.upload.status.button.id"; + + /** + * Artifact uplaod view - uplod status popup id. + */ + public static final String UPLOAD_STATUS_POPUP_ID = "artifact.upload.status.popup.id"; /** * /* Private Constructor. */ diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUILabelDefinitions.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUILabelDefinitions.java index 937a53adc..5e6feceb2 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUILabelDefinitions.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUILabelDefinitions.java @@ -11,7 +11,7 @@ package org.eclipse.hawkbit.ui.utils; import com.vaadin.ui.themes.ValoTheme; /** - * Constants required for Label. + * RepositoryConstants required for Label. * * * diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUIStyleDefinitions.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUIStyleDefinitions.java index c50135251..4ede7204d 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUIStyleDefinitions.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUIStyleDefinitions.java @@ -9,7 +9,7 @@ package org.eclipse.hawkbit.ui.utils; /** - * Constants required for Style. + * RepositoryConstants required for Style. * * * @@ -240,9 +240,9 @@ public final class SPUIStyleDefinitions { public static final String DISABLE_ACTION_TYPE_LAYOUT = "disable-action-type-layout"; /** - * Bulk upload progress indicator style. + * Upload progress indicator style. */ - public static final String BULK_UPLOAD_PROGRESS_INDICATOR_STYLE = "app-loading"; + public static final String UPLOAD_PROGRESS_INDICATOR_STYLE = "app-loading"; /** * Target filter search progress indicator style. @@ -293,6 +293,11 @@ public final class SPUIStyleDefinitions { * Status pending icon. */ public static final String STATUS_ICON_PENDING = "statusIconPending"; + + /** + * Footer layout style. + */ + public static final String FOOTER_LAYOUT = "footer-layout"; /** * Constructor. diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUITargetDefinitions.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUITargetDefinitions.java index 2474fb36c..1fd17b9e6 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUITargetDefinitions.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUITargetDefinitions.java @@ -9,7 +9,7 @@ package org.eclipse.hawkbit.ui.utils; /** - * Constants required for Target. + * RepositoryConstants required for Target. * * * diff --git a/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/customstyles/others.scss b/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/customstyles/others.scss index d327baa94..69dacfa57 100644 --- a/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/customstyles/others.scss +++ b/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/customstyles/others.scss @@ -10,7 +10,7 @@ @mixin others { //Style to display the pending action count - .unread { + .unread, .error-count { @include valo-badge-style; position: absolute; pointer-events: none; @@ -21,6 +21,15 @@ border-radius: $v-border-radius; color: $widget-bg; } + + .error-count { + top: round($v-unit-size / -5); + right: round($v-unit-size / 1.9); + } + + .error-count-color{ + @include valo-gradient($color: $red-color); + } //Deployment view - Style of count message .v-caption-count-msg-box { diff --git a/hawkbit-ui/src/main/resources/messages.properties b/hawkbit-ui/src/main/resources/messages.properties index 0f65ebe13..aa354e49d 100644 --- a/hawkbit-ui/src/main/resources/messages.properties +++ b/hawkbit-ui/src/main/resources/messages.properties @@ -86,6 +86,7 @@ caption.cancel.action.confirmbox = Confirm action cancel caption.forcequit.action.confirmbox = Confirm force quit action caption.forced.datefield = Force update at time caption.force.action.confirmbox = Confirm Force Active Action +caption.confirm.abort.action = Confirm abort action caption.filter.delete.confirmbox = Confirm Filter Delete Action @@ -321,8 +322,11 @@ message.duplicate.filename = Duplicate file name message.swModule.deleted = {0} Software module(s) deleted message.upload.failed = Streaming Failed message.uploadedfile.size.exceeded = File size exceeded .Allowed size {0} bytes +message.uploadedfile.aborted = File upload aborted message.file.not.found = File not found message.artifact.deleted =Artifact with file {0} deleted successfully +message.abort.upload = Are you sure that you want to abort the upload? + upload.swModuleTable.header = Software module diff --git a/hawkbit-ui/src/main/resources/messages_de.properties b/hawkbit-ui/src/main/resources/messages_de.properties index 12f04048a..1ced68c43 100644 --- a/hawkbit-ui/src/main/resources/messages_de.properties +++ b/hawkbit-ui/src/main/resources/messages_de.properties @@ -85,8 +85,9 @@ caption.forced.datefield = Force update at time caption.force.action.confirmbox = Confirm Force Active Action caption.filter.simple = Simple Filter caption.filter.custom = Custom Filter - caption.filter.delete.confirmbox = Confirm Filter Delete Action +caption.confirm.abort.action = Confirm abort action + # Labels prefix with - label label.dist.details.type = Type : @@ -319,8 +320,11 @@ message.swModule.deleted = {0} Software module(s) deleted message.error.missing.tagname = Please select tag name message.upload.failed = Streaming Failed message.uploadedfile.size.exceeded = File size exceeded .Allowed size {0} bytes +message.uploadedfile.aborted = File upload aborted message.file.not.found = File not found message.artifact.deleted =Artifact with file {0} deleted successfully +message.abort.upload = Are you sure that you want to abort the upload? + upload.swModuleTable.header = Software module diff --git a/hawkbit-ui/src/main/resources/messages_en.properties b/hawkbit-ui/src/main/resources/messages_en.properties index 23b8149e3..e88c92305 100644 --- a/hawkbit-ui/src/main/resources/messages_en.properties +++ b/hawkbit-ui/src/main/resources/messages_en.properties @@ -85,8 +85,8 @@ caption.soft.delete.confirmbox = Confirm Software Module Delete Action caption.cancel.action.confirmbox = Confirm action cancellation caption.forced.datefield = Force update at time caption.force.action.confirmbox = Confirm Force Active Action - caption.filter.delete.confirmbox = Confirm Filter Delete Action +caption.confirm.abort.action = Confirm abort action # Labels prefix with - label label.dist.details.type = Type : @@ -313,7 +313,10 @@ message.duplicate.filename = Duplicate file name message.swModule.deleted = {0} Software module(s) deleted message.upload.failed = Streaming Failed message.uploadedfile.size.exceeded = File size exceeded .Allowed size {0} bytes +message.uploadedfile.aborted = File upload aborted message.file.not.found = File not found +message.abort.upload = Are you sure that you want to abort the upload? + upload.swModuleTable.header = Software module upload.selectedfile.name = file selected for upload diff --git a/pom.xml b/pom.xml index 0e4fec71d..33ad1f81e 100644 --- a/pom.xml +++ b/pom.xml @@ -122,7 +122,7 @@ https://projects.eclipse.org/projects/iot.hawkbit https://circleci.com/gh/eclipse/hawkbit - 0.7.2.201409121644 + 0.7.6.201602180812 1.4 @@ -168,6 +168,8 @@ eclipse_codeformatter.xml **/addons.scss **/VAADIN/widgetsets/** + .sonar + **/.sonar/** JAVADOC_STYLE @@ -554,7 +556,6 @@ de.flapdoodle.embed de.flapdoodle.embed.mongo ${embedded-mongo.version} - test
org.easytesting