diff --git a/3rd-dependencies/listDeps.sh b/3rd-dependencies/listDeps.sh index dfb5b942cf..ed7bf59031 100755 --- a/3rd-dependencies/listDeps.sh +++ b/3rd-dependencies/listDeps.sh @@ -1,4 +1,12 @@ -# This script +#!/bin/sh +# +# 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 +# cd .. mvn dependency:list -DexcludeGroupIds=org.eclipse.hawkbit -Dsort=true -DoutputFile=dependencies.txt find . -name dependencies.txt|while read i; do cat $i;done|grep '.*:.*:compile'|sort|uniq > 3rd-dependencies/compile.txt diff --git a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityManagedConfiguration.java b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityManagedConfiguration.java index 0cb8f00279..42c69a1e05 100644 --- a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityManagedConfiguration.java +++ b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityManagedConfiguration.java @@ -335,7 +335,7 @@ public static class UISecurityConfigurationAdapter extends WebSecurityConfigurer private VaadinSecurityContext vaadinSecurityContext; @Autowired - private org.springframework.boot.autoconfigure.security.SecurityProperties springSecurityProperties; + private SecurityProperties springSecurityProperties; /** * post construct for setting the authentication success handler for the 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 66b66391a7..b5beb1d392 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 @@ -144,20 +144,16 @@ private ActionStatus checkAndReportDownloadByTarget(final HttpServletRequest req .getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(), artifact.getSoftwareModule()); final String range = request.getHeader("Range"); - final ActionStatus actionStatus = entityFactory.generateActionStatus(); - actionStatus.setAction(action); - actionStatus.setOccurredAt(System.currentTimeMillis()); - actionStatus.setStatus(Status.DOWNLOAD); - + String message; if (range != null) { - actionStatus.addMessage(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads range " + range - + " of: " + request.getRequestURI()); + message = RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads range " + range + " of: " + + request.getRequestURI(); } else { - actionStatus.addMessage( - RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads: " + request.getRequestURI()); + message = RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads: " + request.getRequestURI(); } - return controllerManagement.addInformationalActionStatus(actionStatus); + return controllerManagement.addInformationalActionStatus( + entityFactory.actionStatus().create(action.getId()).status(Status.DOWNLOAD).message(message)); } } 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 b654c382b8..b91298a47e 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 @@ -10,6 +10,7 @@ import java.io.IOException; import java.io.InputStream; +import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; @@ -34,6 +35,7 @@ import org.eclipse.hawkbit.repository.RepositoryConstants; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.SystemManagement; +import org.eclipse.hawkbit.repository.builder.ActionStatusCreate; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.Status; @@ -179,20 +181,16 @@ private ActionStatus checkAndLogDownload(final HttpServletRequest request, final .getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(), module); final String range = request.getHeader("Range"); - final ActionStatus statusMessage = entityFactory.generateActionStatus(); - statusMessage.setAction(action); - statusMessage.setOccurredAt(System.currentTimeMillis()); - statusMessage.setStatus(Status.DOWNLOAD); - + String message; if (range != null) { - statusMessage.addMessage(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads range " + range - + " of: " + request.getRequestURI()); + message = RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads range " + range + " of: " + + request.getRequestURI(); } else { - statusMessage.addMessage( - RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads " + request.getRequestURI()); + message = RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads " + request.getRequestURI(); } - return controllerManagement.addInformationalActionStatus(statusMessage); + return controllerManagement.addInformationalActionStatus( + entityFactory.actionStatus().create(action.getId()).status(Status.DOWNLOAD).message(message)); } private static boolean checkModule(final String fileName, final SoftwareModule module) { @@ -293,73 +291,69 @@ public ResponseEntity postBasedeploymentActionFeedback(@Valid @RequestBody return new ResponseEntity<>(HttpStatus.GONE); } - controllerManagement - .addUpdateActionStatus(generateUpdateStatus(feedback, controllerId, feedback.getId(), action)); + controllerManagement.addUpdateActionStatus(generateUpdateStatus(feedback, controllerId, feedback.getId())); return new ResponseEntity<>(HttpStatus.OK); } - private ActionStatus generateUpdateStatus(final DdiActionFeedback feedback, final String controllerId, - final Long actionid, final Action action) { - - final ActionStatus actionStatus = entityFactory.generateActionStatus(); - actionStatus.setAction(action); - actionStatus.setOccurredAt(System.currentTimeMillis()); + private ActionStatusCreate generateUpdateStatus(final DdiActionFeedback feedback, final String controllerId, + final Long actionid) { + final List messages = new ArrayList<>(); + Status status; switch (feedback.getStatus().getExecution()) { case CANCELED: LOG.debug("Controller confirmed cancel (actionid: {}, controllerId: {}) as we got {} report.", actionid, controllerId, feedback.getStatus().getExecution()); - actionStatus.setStatus(Status.CANCELED); - actionStatus.addMessage(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target confirmed cancelation."); + status = Status.CANCELED; + messages.add(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target confirmed cancelation."); break; case REJECTED: LOG.info("Controller reported internal error (actionid: {}, controllerId: {}) as we got {} report.", actionid, controllerId, feedback.getStatus().getExecution()); - actionStatus.setStatus(Status.WARNING); - actionStatus.addMessage(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target REJECTED update."); + status = Status.WARNING; + messages.add(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target REJECTED update."); break; case CLOSED: - handleClosedUpdateStatus(feedback, controllerId, actionid, actionStatus); + status = handleClosedCase(feedback, controllerId, actionid, messages); break; default: - handleDefaultUpdateStatus(feedback, controllerId, actionid, actionStatus); + status = handleDefaultCase(feedback, controllerId, actionid, messages); break; } - action.setStatus(actionStatus.getStatus()); - - if (feedback.getStatus().getDetails() != null && !feedback.getStatus().getDetails().isEmpty()) { - final List details = feedback.getStatus().getDetails(); - for (final String detailMsg : details) { - actionStatus.addMessage(detailMsg); - } + if (feedback.getStatus().getDetails() != null) { + messages.addAll(feedback.getStatus().getDetails()); } - return actionStatus; + return entityFactory.actionStatus().create(actionid).status(status).messages(messages); } - private static void handleDefaultUpdateStatus(final DdiActionFeedback feedback, final String controllerId, - final Long actionid, final ActionStatus actionStatus) { + private Status handleDefaultCase(final DdiActionFeedback feedback, final String controllerId, final Long actionid, + final List messages) { + Status status; LOG.debug("Controller reported intermediate status (actionid: {}, controllerId: {}) as we got {} report.", actionid, controllerId, feedback.getStatus().getExecution()); - actionStatus.setStatus(Status.RUNNING); - actionStatus.addMessage( + status = Status.RUNNING; + messages.add( RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target reported " + feedback.getStatus().getExecution()); + return status; } - private static void handleClosedUpdateStatus(final DdiActionFeedback feedback, final String controllerId, - final Long actionid, final ActionStatus actionStatus) { + private Status handleClosedCase(final DdiActionFeedback feedback, final String controllerId, final Long actionid, + final List messages) { + Status status; LOG.debug("Controller reported closed (actionid: {}, controllerId: {}) as we got {} report.", actionid, controllerId, feedback.getStatus().getExecution()); if (feedback.getStatus().getResult().getFinished() == FinalResult.FAILURE) { - actionStatus.setStatus(Status.ERROR); - actionStatus.addMessage(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target reported CLOSED with ERROR!"); + status = Status.ERROR; + messages.add(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target reported CLOSED with ERROR!"); } else { - actionStatus.setStatus(Status.FINISHED); - actionStatus.addMessage(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target reported CLOSED with OK!"); + status = Status.FINISHED; + messages.add(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target reported CLOSED with OK!"); } + return status; } @Override @@ -426,57 +420,64 @@ public ResponseEntity postCancelActionFeedback(@Valid @RequestBody final D return new ResponseEntity<>(HttpStatus.NOT_FOUND); } - controllerManagement.addCancelActionStatus( - generateActionCancelStatus(feedback, target, feedback.getId(), action, entityFactory)); + controllerManagement + .addCancelActionStatus(generateActionCancelStatus(feedback, target, feedback.getId(), entityFactory)); return new ResponseEntity<>(HttpStatus.OK); } - private static ActionStatus generateActionCancelStatus(final DdiActionFeedback feedback, final Target target, - final Long actionid, final Action action, final EntityFactory entityFactory) { - - final ActionStatus actionStatus = entityFactory.generateActionStatus(); - actionStatus.setAction(action); - actionStatus.setOccurredAt(System.currentTimeMillis()); + private static ActionStatusCreate generateActionCancelStatus(final DdiActionFeedback feedback, final Target target, + final Long actionid, final EntityFactory entityFactory) { + final List messages = new ArrayList<>(); + Status status; switch (feedback.getStatus().getExecution()) { case CANCELED: - LOG.error( - "Controller reported cancel for a cancel which is not supported by the server (actionid: {}, controllerId: {}) as we got {} report.", - actionid, target.getControllerId(), feedback.getStatus().getExecution()); - actionStatus.setStatus(Status.WARNING); + status = handleCaseCancelCanceled(feedback, target, actionid, messages); break; case REJECTED: - LOG.info("Controller rejected the cancelation request (too late) (actionid: {}, controllerId: {}).", - actionid, target.getControllerId()); - actionStatus.setStatus(Status.WARNING); + LOG.info("Target rejected the cancelation request (actionid: {}, controllerId: {}).", actionid, + target.getControllerId()); + status = Status.WARNING; + messages.add(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target rejected the cancelation request."); break; case CLOSED: - handleClosedCancelStatus(feedback, actionStatus); + status = handleCancelClosedCase(feedback, messages); break; default: - actionStatus.setStatus(Status.RUNNING); + status = Status.RUNNING; break; } - action.setStatus(actionStatus.getStatus()); - - if (feedback.getStatus().getDetails() != null && !feedback.getStatus().getDetails().isEmpty()) { - final List details = feedback.getStatus().getDetails(); - for (final String detailMsg : details) { - actionStatus.addMessage(detailMsg); - } + if (feedback.getStatus().getDetails() != null) { + messages.addAll(feedback.getStatus().getDetails()); } - return actionStatus; + return entityFactory.actionStatus().create(actionid).status(status).messages(messages); } - private static void handleClosedCancelStatus(final DdiActionFeedback feedback, final ActionStatus actionStatus) { + private static Status handleCancelClosedCase(final DdiActionFeedback feedback, final List messages) { + Status status; if (feedback.getStatus().getResult().getFinished() == FinalResult.FAILURE) { - actionStatus.setStatus(Status.ERROR); + status = Status.ERROR; + messages.add(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target was not able to complete cancelation."); } else { - actionStatus.setStatus(Status.CANCELED); + status = Status.CANCELED; + messages.add(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Cancelation confirmed."); } + return status; + } + + private static Status handleCaseCancelCanceled(final DdiActionFeedback feedback, final Target target, + final Long actionid, final List messages) { + Status status; + LOG.error( + "Target reported cancel for a cancel which is not supported by the server (actionid: {}, controllerId: {}) as we got {} report.", + actionid, target.getControllerId(), feedback.getStatus().getExecution()); + status = Status.WARNING; + messages.add(RepositoryConstants.SERVER_MESSAGE_PREFIX + + "Target reported cancel for a cancel which is not supported by the server."); + return status; } private Action findActionWithExceptionIfNotFound(final Long actionId) { 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 de42360fe7..c31ada5bcf 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 @@ -22,7 +22,6 @@ import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; -import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; @@ -37,6 +36,7 @@ import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.Target; +import org.eclipse.hawkbit.repository.test.util.TestdataFactory; import org.eclipse.hawkbit.repository.test.util.WithUser; import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest; import org.junit.Before; @@ -50,6 +50,7 @@ import org.springframework.test.web.servlet.MvcResult; import com.google.common.base.Charsets; +import com.google.common.collect.Lists; import com.google.common.net.HttpHeaders; import ru.yandex.qatools.allure.annotations.Description; @@ -80,14 +81,12 @@ public void setup() { @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 = entityFactory.generateTarget("4712"); - target = targetManagement.createTarget(target); - final List targets = new ArrayList<>(); - targets.add(target); + final Target target = testdataFactory.createTarget(); + final List targets = Lists.newArrayList(target); // create ds final DistributionSet ds = testdataFactory.createDistributionSet(""); - deploymentManagement.assignDistributionSet(ds, targets); + assignDistributionSet(ds, targets); // create artifact final byte random[] = RandomUtils.nextBytes(5 * 1024); @@ -96,9 +95,9 @@ public void invalidRequestsOnArtifactResource() throws Exception { // no artifact available mvc.perform(get("/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/123455", - target.getControllerId(), ds.findFirstModuleByType(osType).getId())).andExpect(status().isNotFound()); + target.getControllerId(), getOsModule(ds))).andExpect(status().isNotFound()); mvc.perform(get("/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/123455.MD5SUM", - target.getControllerId(), ds.findFirstModuleByType(osType).getId())).andExpect(status().isNotFound()); + target.getControllerId(), getOsModule(ds))).andExpect(status().isNotFound()); // SM does not exist mvc.perform(get("/controller/v1/{targetid}/softwaremodules/1234567890/artifacts/{filename}", @@ -108,70 +107,69 @@ public void invalidRequestsOnArtifactResource() throws Exception { // test now consistent data to test allowed methods mvc.perform(get("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}", - tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), - artifact.getFilename()).header(HttpHeaders.IF_MATCH, artifact.getSha1Hash())) + tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename()) + .header(HttpHeaders.IF_MATCH, artifact.getSha1Hash())) .andExpect(status().isOk()); mvc.perform(get("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}.MD5SUM", - tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), - artifact.getFilename())).andExpect(status().isOk()); + tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename())) + .andExpect(status().isOk()); // test failed If-match mvc.perform(get("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}", - tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), - artifact.getFilename()).header("If-Match", "fsjkhgjfdhg")).andExpect(status().isPreconditionFailed()); + tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename()) + .header("If-Match", "fsjkhgjfdhg")) + .andExpect(status().isPreconditionFailed()); // test invalid range mvc.perform(get("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}", - tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), - artifact.getFilename()).header("Range", "bytes=1-10,hdsfjksdh")) + tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename()) + .header("Range", "bytes=1-10,hdsfjksdh")) .andExpect(header().string("Content-Range", "bytes */" + 5 * 1024)) .andExpect(status().isRequestedRangeNotSatisfiable()); mvc.perform(get("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}", - tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), - artifact.getFilename()).header("Range", "bytes=100-10")) + tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename()) + .header("Range", "bytes=100-10")) .andExpect(header().string("Content-Range", "bytes */" + 5 * 1024)) .andExpect(status().isRequestedRangeNotSatisfiable()); // not allowed methods mvc.perform(put("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}", - tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), - artifact.getFilename())).andExpect(status().isMethodNotAllowed()); + tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename())) + .andExpect(status().isMethodNotAllowed()); mvc.perform(delete("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}", - tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), - artifact.getFilename())).andExpect(status().isMethodNotAllowed()); + tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename())) + .andExpect(status().isMethodNotAllowed()); mvc.perform(post("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}", - tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), - artifact.getFilename())).andExpect(status().isMethodNotAllowed()); + tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename())) + .andExpect(status().isMethodNotAllowed()); mvc.perform(put("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}.MD5SUM", - tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), - artifact.getFilename())).andExpect(status().isMethodNotAllowed()); + tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename())) + .andExpect(status().isMethodNotAllowed()); mvc.perform(delete("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}.MD5SUM", - tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), - artifact.getFilename())).andExpect(status().isMethodNotAllowed()); + tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename())) + .andExpect(status().isMethodNotAllowed()); mvc.perform(post("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}.MD5SUM", - tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), - artifact.getFilename())).andExpect(status().isMethodNotAllowed()); + tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename())) + .andExpect(status().isMethodNotAllowed()); } @Test - @WithUser(principal = "4712", authorities = "ROLE_CONTROLLER", allSpPermissions = true) + @WithUser(principal = TestdataFactory.DEFAULT_CONTROLLER_ID, authorities = "ROLE_CONTROLLER", allSpPermissions = true) @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 = entityFactory.generateTarget("4712"); - target = targetManagement.createTarget(target); - final List targets = new ArrayList<>(); - targets.add(target); + final Target target = testdataFactory.createTarget(); + final List targets = Lists.newArrayList(target); // create ds final DistributionSet ds = testdataFactory.createDistributionSet(""); - deploymentManagement.assignDistributionSet(ds, targets); + assignDistributionSet(ds, targets); // create artifact final byte random[] = RandomUtils.nextBytes(5 * 1024); @@ -185,8 +183,8 @@ public void invalidRequestsOnArtifactResourceByName() throws Exception { .andExpect(status().isNotFound()); // test now consistent data to test allowed methods - final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), - ds.findFirstModuleByType(osType).getId(), "file1", false); + final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), getOsModule(ds), + "file1", false); mvc.perform( get("/{tenant}/controller/artifacts/v1/filename/{filename}", tenantAware.getCurrentTenant(), "file1") @@ -248,10 +246,8 @@ public void downloadArtifactThroughFileName() throws Exception { assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); // create target - Target target = entityFactory.generateTarget("4712"); - target = targetManagement.createTarget(target); - final List targets = new ArrayList(); - targets.add(target); + final Target target = testdataFactory.createTarget(); + final List targets = Lists.newArrayList(target); // create ds final DistributionSet ds = testdataFactory.createDistributionSet(""); @@ -263,16 +259,15 @@ public void downloadArtifactThroughFileName() throws Exception { // download fails as artifact is not yet assigned mvc.perform(get("/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/{filename}", - target.getControllerId(), ds.findFirstModuleByType(osType).getId(), artifact.getFilename())) - .andExpect(status().isNotFound()); + target.getControllerId(), getOsModule(ds), artifact.getFilename())).andExpect(status().isNotFound()); // now assign and download successful - deploymentManagement.assignDistributionSet(ds, targets); + assignDistributionSet(ds, targets); final MvcResult result = mvc .perform( get("/{tenant}/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/{filename}", - tenantAware.getCurrentTenant(), target.getControllerId(), - ds.findFirstModuleByType(osType).getId(), artifact.getFilename())) + tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), + artifact.getFilename())) .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM)) .andExpect(header().string("Accept-Ranges", "bytes")) .andExpect(header().string("Last-Modified", dateFormat.format(new Date(artifact.getCreatedAt())))) @@ -291,23 +286,22 @@ public void downloadArtifactThroughFileName() throws Exception { @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 = entityFactory.generateTarget("4712"); - target = targetManagement.createTarget(target); + final Target target = testdataFactory.createTarget(); // create ds final DistributionSet ds = testdataFactory.createDistributionSet(""); // create artifact final byte random[] = RandomUtils.nextBytes(5 * 1024); - final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), - ds.findFirstModuleByType(osType).getId(), "file1", false); + final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), getOsModule(ds), + "file1", false); // download final MvcResult result = mvc .perform( get("/{tenant}/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/{filename}.MD5SUM", - tenantAware.getCurrentTenant(), target.getControllerId(), - ds.findFirstModuleByType(osType).getId(), artifact.getFilename())) + tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), + artifact.getFilename())) .andExpect(status().isOk()).andExpect(header().string("Content-Disposition", "attachment;filename=" + artifact.getFilename() + ".MD5SUM")) .andReturn(); @@ -327,21 +321,18 @@ public void downloadArtifactByNameFailsIfNotAuthenticated() throws Exception { assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); // create target - Target target = entityFactory.generateTarget("4712"); - target = targetManagement.createTarget(target); - final List targets = new ArrayList<>(); - targets.add(target); + final Target target = testdataFactory.createTarget(); + final List targets = Lists.newArrayList(target); // create ds final DistributionSet ds = testdataFactory.createDistributionSet(""); // create artifact final byte random[] = RandomUtils.nextBytes(ARTIFACT_SIZE); - artifactManagement.createArtifact(new ByteArrayInputStream(random), ds.findFirstModuleByType(osType).getId(), - "file1.tar.bz2", false); + artifactManagement.createArtifact(new ByteArrayInputStream(random), getOsModule(ds), "file1.tar.bz2", false); // download fails as artifact is not yet assigned to target - deploymentManagement.assignDistributionSet(ds, targets); + assignDistributionSet(ds, targets); mvc.perform(get("/controller/artifacts/v1/filename/{filename}", "file1.tar.bz2")) .andExpect(status().isNotFound()); @@ -350,7 +341,7 @@ public void downloadArtifactByNameFailsIfNotAuthenticated() throws Exception { } @Test - @WithUser(principal = "4712", authorities = "ROLE_CONTROLLER", allSpPermissions = true) + @WithUser(principal = TestdataFactory.DEFAULT_CONTROLLER_ID, authorities = "ROLE_CONTROLLER", allSpPermissions = true) @Description("Ensures that an authenticated and named controller is permitted to download.") public void downloadArtifactByNameByNamedController() throws Exception { downLoadProgress = 1; @@ -359,25 +350,23 @@ public void downloadArtifactByNameByNamedController() throws Exception { assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); // create target - Target target = entityFactory.generateTarget("4712"); - target = targetManagement.createTarget(target); - final List targets = new ArrayList<>(); - targets.add(target); + final Target target = testdataFactory.createTarget(); + final List targets = Lists.newArrayList(target); // create ds final DistributionSet ds = testdataFactory.createDistributionSet(""); // create artifact final byte random[] = RandomUtils.nextBytes(ARTIFACT_SIZE); - final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), - ds.findFirstModuleByType(osType).getId(), "file1", false); + final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), getOsModule(ds), + "file1", false); // download fails as artifact is not yet assigned to target mvc.perform(get("/{tenant}/controller/artifacts/v1/filename/{filename}", tenantAware.getCurrentTenant(), "file1.tar.bz2")).andExpect(status().isNotFound()); // now assign and download successful - deploymentManagement.assignDistributionSet(ds, targets); + assignDistributionSet(ds, targets); final MvcResult result = mvc .perform(get("/{tenant}/controller/artifacts/v1/filename/{filename}", tenantAware.getCurrentTenant(), "file1")) @@ -405,14 +394,12 @@ public void downloadArtifactByNameByNamedController() throws Exception { } @Test - @WithUser(principal = "4712", authorities = "ROLE_CONTROLLER", allSpPermissions = true) + @WithUser(principal = TestdataFactory.DEFAULT_CONTROLLER_ID, authorities = "ROLE_CONTROLLER", allSpPermissions = true) @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 = entityFactory.generateTarget("4712"); - target = targetManagement.createTarget(target); - final List targets = new ArrayList<>(); - targets.add(target); + final Target target = testdataFactory.createTarget(); + final List targets = Lists.newArrayList(target); // create ds final DistributionSet ds = testdataFactory.createDistributionSet(""); @@ -421,13 +408,13 @@ public void rangeDownloadArtifactByName() throws Exception { // create artifact final byte random[] = RandomUtils.nextBytes(resultLength); - final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), - ds.findFirstModuleByType(osType).getId(), "file1", false); + final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), getOsModule(ds), + "file1", false); assertThat(random.length).isEqualTo(resultLength); // now assign and download successful - deploymentManagement.assignDistributionSet(ds, targets); + assignDistributionSet(ds, targets); final int range = 100 * 1024; @@ -515,18 +502,16 @@ public void faildDownloadArtifactByNameIfAuthenticationMissing() throws Exceptio assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); // create target - Target target = entityFactory.generateTarget("4712"); - target = targetManagement.createTarget(target); - final List targets = new ArrayList<>(); - targets.add(target); + final Target target = testdataFactory.createTarget(); + final List targets = Lists.newArrayList(target); // create ds final DistributionSet ds = testdataFactory.createDistributionSet(""); // create artifact final byte random[] = RandomUtils.nextBytes(5 * 1024); - final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), - ds.findFirstModuleByType(osType).getId(), "file1.tar.bz2", false); + final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), getOsModule(ds), + "file1.tar.bz2", false); // download fails as artifact is not yet assigned to target mvc.perform(get("/controller/artifacts/v1/filename/{filename}", "file1.tar.bz2")) @@ -537,16 +522,15 @@ public void faildDownloadArtifactByNameIfAuthenticationMissing() throws Exceptio @Description("Downloads an MD5SUM file by the related artifacts filename.") public void downloadMd5sumFileByName() throws Exception { // create target - Target target = entityFactory.generateTarget("4712"); - target = targetManagement.createTarget(target); + final Target target = testdataFactory.createTarget(); // create ds final DistributionSet ds = testdataFactory.createDistributionSet(""); // create artifact final byte random[] = RandomUtils.nextBytes(5 * 1024); - final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), - ds.findFirstModuleByType(osType).getId(), "file1.tar.bz2", false); + final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), getOsModule(ds), + "file1.tar.bz2", false); // download final MvcResult result = mvc 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 ce977b016a..8430131d83 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 @@ -27,6 +27,7 @@ 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.test.util.TestdataFactory; import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest; import org.eclipse.hawkbit.rest.util.JsonBuilder; import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; @@ -48,22 +49,18 @@ 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 = entityFactory.generateTarget("4712"); final DistributionSet ds = testdataFactory.createDistributionSet(""); - final Target savedTarget = targetManagement.createTarget(target); + final Target savedTarget = testdataFactory.createTarget(); - final List toAssign = new ArrayList(); - toAssign.add(savedTarget); - - final Action updateAction = deploymentManagement - .findActionWithDetails(deploymentManagement.assignDistributionSet(ds, toAssign).getActions().get(0)); + final Action updateAction = deploymentManagement.findActionWithDetails( + assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getActions().get(0)); final Action cancelAction = deploymentManagement.cancelAction(updateAction, targetManagement.findTargetByControllerID(savedTarget.getControllerId())); // controller rejects cancelation - mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", - tenantAware.getCurrentTenant()) + mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "rejected")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); @@ -71,9 +68,10 @@ public void rootRsCancelActionButContinueAnyway() throws Exception { final long current = System.currentTimeMillis(); // get update action anyway - mvc.perform(get("/{tenant}/controller/v1/4712/deploymentBase/" + updateAction.getId(), - tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) - .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/deploymentBase/" + + updateAction.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)) + .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$.id", equalTo(String.valueOf(updateAction.getId())))) .andExpect(jsonPath("$.deployment.download", equalTo("forced"))) .andExpect(jsonPath("$.deployment.update", equalTo("forced"))) @@ -85,50 +83,46 @@ public void rootRsCancelActionButContinueAnyway() throws Exception { contains(ds.findFirstModuleByType(appType).getVersion()))); // and finish it - mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + updateAction.getId() + "/feedback", - tenantAware.getCurrentTenant()).content( + mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/deploymentBase/" + + updateAction.getId() + "/feedback", tenantAware.getCurrentTenant()).content( JsonBuilder.deploymentActionFeedback(updateAction.getId().toString(), "closed", "success")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); // check database after test - assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet().getId()) - .isEqualTo(ds.getId()); - assertThat(targetManagement.findTargetByControllerIDWithDetails("4712").getTargetInfo() - .getInstalledDistributionSet().getId()).isEqualTo(ds.getId()); - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getInstallationDate()) - .isGreaterThanOrEqualTo(current); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID) + .getAssignedDistributionSet().getId()).isEqualTo(ds.getId()); + assertThat(targetManagement.findTargetByControllerIDWithDetails(TestdataFactory.DEFAULT_CONTROLLER_ID) + .getTargetInfo().getInstalledDistributionSet().getId()).isEqualTo(ds.getId()); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getInstallationDate()).isGreaterThanOrEqualTo(current); } @Test @Description("Test for cancel operation of a update action.") public void rootRsCancelAction() throws Exception { - final Target target = entityFactory.generateTarget("4712"); final DistributionSet ds = testdataFactory.createDistributionSet(""); - final Target savedTarget = targetManagement.createTarget(target); + final Target savedTarget = testdataFactory.createTarget(); - final List toAssign = new ArrayList(); - toAssign.add(savedTarget); - - final Action updateAction = deploymentManagement - .findActionWithDetails(deploymentManagement.assignDistributionSet(ds, toAssign).getActions().get(0)); + final Action updateAction = deploymentManagement.findActionWithDetails( + assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getActions().get(0)); long current = System.currentTimeMillis(); - mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant())) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + mvc.perform(get("/{tenant}/controller/v1/{controller}", tenantAware.getCurrentTenant(), + TestdataFactory.DEFAULT_CONTROLLER_ID)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON_HAL_UTF)) .andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00"))) .andExpect(jsonPath("$._links.deploymentBase.href", - startsWith("http://localhost/" + tenantAware.getCurrentTenant() - + "/controller/v1/4712/deploymentBase/" + updateAction.getId()))); + startsWith("http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/" + + TestdataFactory.DEFAULT_CONTROLLER_ID + "/deploymentBase/" + updateAction.getId()))); Thread.sleep(1); // is required: otherwise processing the next line is // often too fast and // the following assert will fail - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) - .isLessThanOrEqualTo(System.currentTimeMillis()); - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) - .isGreaterThanOrEqualTo(current); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis()); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getLastTargetQuery()).isGreaterThanOrEqualTo(current); // Retrieved is reported @@ -147,39 +141,38 @@ public void rootRsCancelAction() throws Exception { assertThat(activeActionsByTarget.get(0).getStatus()).isEqualTo(Status.CANCELING); current = System.currentTimeMillis(); - mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant())) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + mvc.perform(get("/{tenant}/controller/v1/{controller}", tenantAware.getCurrentTenant(), + TestdataFactory.DEFAULT_CONTROLLER_ID)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON_HAL_UTF)) .andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00"))) .andExpect(jsonPath("$._links.cancelAction.href", - equalTo("http://localhost/" + tenantAware.getCurrentTenant() - + "/controller/v1/4712/cancelAction/" + cancelAction.getId()))); + equalTo("http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/" + + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId()))); Thread.sleep(1); // is required: otherwise processing the next line is // often too fast and // the following assert will fail - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) - .isLessThanOrEqualTo(System.currentTimeMillis()); - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) - .isGreaterThanOrEqualTo(current); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis()); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getLastTargetQuery()).isGreaterThanOrEqualTo(current); current = System.currentTimeMillis(); - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) - .isLessThanOrEqualTo(System.currentTimeMillis()); - mvc.perform( - get("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId(), tenantAware.getCurrentTenant()) - .accept(MediaType.APPLICATION_JSON)) + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis()); + mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$.id", equalTo(String.valueOf(cancelAction.getId())))) .andExpect(jsonPath("$.cancelAction.stopId", equalTo(String.valueOf(updateAction.getId())))); - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) - .isLessThanOrEqualTo(System.currentTimeMillis()); - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) - .isGreaterThanOrEqualTo(current); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis()); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getLastTargetQuery()).isGreaterThanOrEqualTo(current); // controller confirmed cancelled action, should not be active anymore - mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", - tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON) + mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON) .content(JsonBuilder.cancelActionFeedback(updateAction.getId().toString(), "closed")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); @@ -197,14 +190,17 @@ public void rootRsCancelAction() throws Exception { public void badCancelAction() throws Exception { // not allowed methods - mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/1", tenantAware.getCurrentTenant())) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed()); + mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/1", + tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print()) + .andExpect(status().isMethodNotAllowed()); - mvc.perform(put("/{tenant}/controller/v1/4712/cancelAction/1", tenantAware.getCurrentTenant())) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed()); + mvc.perform(put("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/1", + tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print()) + .andExpect(status().isMethodNotAllowed()); - mvc.perform(delete("/{tenant}/controller/v1/4712/cancelAction/1", tenantAware.getCurrentTenant())) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed()); + mvc.perform(delete("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/1", + tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print()) + .andExpect(status().isMethodNotAllowed()); // non existing target mvc.perform(get("/{tenant}/controller/v1/34534543/cancelAction/1", tenantAware.getCurrentTenant()) @@ -221,13 +217,12 @@ public void badCancelAction() throws Exception { } private Action createCancelAction(final String targetid) { - final Target target = entityFactory.generateTarget(targetid); final DistributionSet ds = testdataFactory.createDistributionSet(targetid); - final Target savedTarget = targetManagement.createTarget(target); - final List toAssign = new ArrayList(); + final Target savedTarget = testdataFactory.createTarget(targetid); + final List toAssign = new ArrayList<>(); toAssign.add(savedTarget); final Action updateAction = deploymentManagement - .findActionWithDetails(deploymentManagement.assignDistributionSet(ds, toAssign).getActions().get(0)); + .findActionWithDetails(assignDistributionSet(ds, toAssign).getActions().get(0)); return deploymentManagement.cancelAction(updateAction, targetManagement.findTargetByControllerID(savedTarget.getControllerId())); @@ -237,13 +232,12 @@ private Action createCancelAction(final String targetid) { @Description("Tests the feedback channel of the cancel operation.") public void rootRsCancelActionFeedback() throws Exception { - final Target target = entityFactory.generateTarget("4712"); final DistributionSet ds = testdataFactory.createDistributionSet(""); - final Target savedTarget = targetManagement.createTarget(target); + final Target savedTarget = testdataFactory.createTarget(); final Action updateAction = deploymentManagement.findActionWithDetails( - deploymentManagement.assignDistributionSet(ds.getId(), new String[] { "4712" }).getActions().get(0)); + assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0)); // cancel action manually final Action cancelAction = deploymentManagement.cancelAction(updateAction, @@ -252,49 +246,49 @@ public void rootRsCancelActionFeedback() throws Exception { assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); long current = System.currentTimeMillis(); - mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", - tenantAware.getCurrentTenant()) + mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "proceeding")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) - .isGreaterThanOrEqualTo(current); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getLastTargetQuery()).isGreaterThanOrEqualTo(current); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(3); current = System.currentTimeMillis(); - mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", - tenantAware.getCurrentTenant()) + mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "resumed")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) - .isGreaterThanOrEqualTo(current); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getLastTargetQuery()).isGreaterThanOrEqualTo(current); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(4); current = System.currentTimeMillis(); - mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", - tenantAware.getCurrentTenant()) + mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "scheduled")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) - .isGreaterThanOrEqualTo(current); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getLastTargetQuery()).isGreaterThanOrEqualTo(current); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(5); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); // cancelation canceled -> should remove the action from active assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); current = System.currentTimeMillis(); - mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", - tenantAware.getCurrentTenant()) + mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "canceled")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) - .isGreaterThanOrEqualTo(current); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getLastTargetQuery()).isGreaterThanOrEqualTo(current); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(6); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); @@ -303,25 +297,25 @@ public void rootRsCancelActionFeedback() throws Exception { // error assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); current = System.currentTimeMillis(); - mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", - tenantAware.getCurrentTenant()) + mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "rejected")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) - .isGreaterThanOrEqualTo(current); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getLastTargetQuery()).isGreaterThanOrEqualTo(current); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(7); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); // cancelaction closed -> should remove the action from active current = System.currentTimeMillis(); - mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", - tenantAware.getCurrentTenant()) + mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) - .isGreaterThanOrEqualTo(current); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getLastTargetQuery()).isGreaterThanOrEqualTo(current); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(8); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(0); } @@ -329,19 +323,18 @@ public void rootRsCancelActionFeedback() throws Exception { @Test @Description("Tests the feeback chanel of for multiple open cancel operations on the same target.") public void multipleCancelActionFeedback() throws Exception { - 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); + final Target savedTarget = testdataFactory.createTarget(); final Action updateAction = deploymentManagement.findActionWithDetails( - deploymentManagement.assignDistributionSet(ds.getId(), new String[] { "4712" }).getActions().get(0)); + assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0)); final Action updateAction2 = deploymentManagement.findActionWithDetails( - deploymentManagement.assignDistributionSet(ds2.getId(), new String[] { "4712" }).getActions().get(0)); + assignDistributionSet(ds2.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0)); final Action updateAction3 = deploymentManagement.findActionWithDetails( - deploymentManagement.assignDistributionSet(ds3.getId(), new String[] { "4712" }).getActions().get(0)); + assignDistributionSet(ds3.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0)); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(3); @@ -355,26 +348,25 @@ public void multipleCancelActionFeedback() throws Exception { assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(3); assertThat(deploymentManagement.findActionsByTarget(savedTarget)).hasSize(3); - mvc.perform( - get("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId(), tenantAware.getCurrentTenant()) - .accept(MediaType.APPLICATION_JSON)) + mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id", equalTo(String.valueOf(cancelAction.getId())))) .andExpect(jsonPath("$.cancelAction.stopId", equalTo(String.valueOf(updateAction.getId())))); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(6); - mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant())) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + mvc.perform(get("/{tenant}/controller/v1/{controllerId}", tenantAware.getCurrentTenant(), + TestdataFactory.DEFAULT_CONTROLLER_ID)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON_HAL_UTF)) .andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00"))) .andExpect(jsonPath("$._links.cancelAction.href", - equalTo("http://localhost/" + tenantAware.getCurrentTenant() - + "/controller/v1/4712/cancelAction/" + cancelAction.getId()))); + equalTo("http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/" + + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId()))); // now lets return feedback for the first cancelation - mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", - tenantAware.getCurrentTenant()) + mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); @@ -383,32 +375,35 @@ public void multipleCancelActionFeedback() throws Exception { // 1 update actions, 1 cancel actions assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2); assertThat(deploymentManagement.findActionsByTarget(savedTarget)).hasSize(3); - mvc.perform(get("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction2.getId(), - tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) - .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction2.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)) + .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$.id", equalTo(String.valueOf(cancelAction2.getId())))) .andExpect(jsonPath("$.cancelAction.stopId", equalTo(String.valueOf(updateAction2.getId())))); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(8); - mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant())) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + mvc.perform(get("/{tenant}/controller/v1/{controller}", tenantAware.getCurrentTenant(), + TestdataFactory.DEFAULT_CONTROLLER_ID)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON_HAL_UTF)) .andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00"))) .andExpect(jsonPath("$._links.cancelAction.href", - equalTo("http://localhost/" + tenantAware.getCurrentTenant() - + "/controller/v1/4712/cancelAction/" + cancelAction2.getId()))); + equalTo("http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/" + + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction2.getId()))); // now lets return feedback for the second cancelation - mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction2.getId() + "/feedback", - tenantAware.getCurrentTenant()) + mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction2.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction2.getId().toString(), "closed")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); 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(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID) + .getAssignedDistributionSet()).isEqualTo(ds3); + mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/deploymentBase/" + + updateAction3.getId(), tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print()) + .andExpect(status().isOk()); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(10); // 1 update actions, 0 cancel actions @@ -421,18 +416,20 @@ public void multipleCancelActionFeedback() throws Exception { // action is in cancelling state assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); assertThat(deploymentManagement.findActionsByTarget(savedTarget)).hasSize(3); - assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet()).isEqualTo(ds3); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID) + .getAssignedDistributionSet()).isEqualTo(ds3); - mvc.perform(get("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction3.getId(), - tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) - .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) + mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction3.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)) + .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$.id", equalTo(String.valueOf(cancelAction3.getId())))) .andExpect(jsonPath("$.cancelAction.stopId", equalTo(String.valueOf(updateAction3.getId())))); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(12); // now lets return feedback for the third cancelation - mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction3.getId() + "/feedback", - tenantAware.getCurrentTenant()) + mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction3.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction3.getId().toString(), "closed")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON_UTF8)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); @@ -446,14 +443,11 @@ public void multipleCancelActionFeedback() throws Exception { @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(entityFactory.generateTarget("4712")); + final Target target = testdataFactory.createTarget(); final DistributionSet ds = testdataFactory.createDistributionSet(""); - final List toAssign = new ArrayList(); - toAssign.add(target); - final Action action = deploymentManagement.findActionWithDetails( - deploymentManagement.assignDistributionSet(ds.getId(), new String[] { "4712" }).getActions().get(0)); + assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0)); final Action cancelAction = deploymentManagement.cancelAction(action, targetManagement.findTargetByControllerID(target.getControllerId())); @@ -463,49 +457,49 @@ public void tooMuchCancelActionFeedback() throws Exception { // stores an action status, so // only 97 action status left for (int i = 0; i < 98; i++) { - mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", - tenantAware.getCurrentTenant()).content(feedback).contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON)) + mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()).content(feedback) + .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); } - mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", - tenantAware.getCurrentTenant()).content(feedback).contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON)) + mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()).content(feedback) + .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isForbidden()); } @Test @Description("test the correct rejection of various invalid feedback requests") public void badCancelActionFeedback() throws Exception { - final Action cancelAction = createCancelAction("4712"); + final Action cancelAction = createCancelAction(TestdataFactory.DEFAULT_CONTROLLER_ID); final Action cancelAction2 = createCancelAction("4715"); // not allowed methods - mvc.perform(put("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", - tenantAware.getCurrentTenant()) + mvc.perform(put("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed()); - mvc.perform(delete("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", - tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print()) - .andExpect(status().isMethodNotAllowed()); + mvc.perform(delete("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant())) + .andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed()); - mvc.perform(get("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", - tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print()) - .andExpect(status().isMethodNotAllowed()); + mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant())) + .andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed()); // bad content type - mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", - tenantAware.getCurrentTenant()) + mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed")) .contentType(MediaType.APPLICATION_ATOM_XML).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isUnsupportedMediaType()); // bad body - mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", - tenantAware.getCurrentTenant()) + mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "546456456")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()); @@ -518,25 +512,27 @@ public void badCancelActionFeedback() throws Exception { .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound()); // invalid action - mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", - tenantAware.getCurrentTenant()).content(JsonBuilder.cancelActionFeedback("sdfsdfsdfs", "closed")) + mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) + .content(JsonBuilder.cancelActionFeedback("sdfsdfsdfs", "closed")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()); - mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", - tenantAware.getCurrentTenant()).content(JsonBuilder.cancelActionFeedback("1234", "closed")) + mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) + .content(JsonBuilder.cancelActionFeedback("1234", "closed")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound()); // right action but for wrong target - mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", - tenantAware.getCurrentTenant()) + mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction2.getId().toString(), "closed")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound()); // finally get it right :) - mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", - tenantAware.getCurrentTenant()) + mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed")) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); 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 e828e50498..1a0632ca7f 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 @@ -46,8 +46,7 @@ public class DdiConfigDataTest extends AbstractRestIntegrationTest { @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 = entityFactory.generateTarget("4712"); - final Target savedTarget = targetManagement.createTarget(target); + final Target savedTarget = testdataFactory.createTarget("4712"); final long current = System.currentTimeMillis(); mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant())) @@ -84,7 +83,7 @@ public void requestConfigDataIfEmpty() throws Exception { @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(entityFactory.generateTarget("4717")); + testdataFactory.createTarget("4717"); // initial final Map attributes = new HashMap<>(); @@ -127,7 +126,7 @@ public void putConfigData() throws Exception { @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(entityFactory.generateTarget("4717")); + testdataFactory.createTarget("4717"); // initial Map attributes = new HashMap<>(); @@ -150,8 +149,7 @@ public void putToMuchConfigData() throws Exception { @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 = entityFactory.generateTarget("4712"); - final Target savedTarget = targetManagement.createTarget(target); + final Target savedTarget = testdataFactory.createTarget("4712"); // not allowed methods mvc.perform(post("/{tenant}/controller/v1/4712/configData", tenantAware.getCurrentTenant())) 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 762e6f35cd..da2cfd85d3 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 @@ -79,7 +79,7 @@ public void artifactsExists() throws Exception { final Target target = testdataFactory.createTarget(); final DistributionSet distributionSet = testdataFactory.createDistributionSet(""); - deploymentManagement.assignDistributionSet(distributionSet.getId(), new String[] { target.getName() }); + assignDistributionSet(distributionSet.getId(), target.getName()); final Long softwareModuleId = distributionSet.getModules().stream().findFirst().get().getId(); mvc.perform(get("/{tenant}/controller/v1/{targetNotExist}/softwaremodules/{softwareModuleId}/artifacts", @@ -101,29 +101,29 @@ public void artifactsExists() throws Exception { @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 = entityFactory.generateTarget("4712"); final DistributionSet ds = testdataFactory.createDistributionSet("", true); final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true); final byte random[] = RandomUtils.nextBytes(5 * 1024); - final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), - ds.findFirstModuleByType(osType).getId(), "test1", false); + final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), getOsModule(ds), + "test1", false); final Artifact artifactSignature = artifactManagement.createArtifact(new ByteArrayInputStream(random), - ds.findFirstModuleByType(osType).getId(), "test1.signature", false); + getOsModule(ds), "test1.signature", false); - final Target savedTarget = targetManagement.createTarget(target); + final Target savedTarget = testdataFactory.createTarget("4712"); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).isEmpty(); assertThat(deploymentManagement.countActionsAll()).isEqualTo(0); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(0); List saved = deploymentManagement.assignDistributionSet(ds.getId(), ActionType.FORCED, - RepositoryModelConstants.NO_FORCE_TIME, savedTarget.getControllerId()).getAssignedEntity(); + RepositoryModelConstants.NO_FORCE_TIME, Lists.newArrayList(savedTarget.getControllerId())) + .getAssignedEntity(); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); final Action action = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0); assertThat(deploymentManagement.countActionsAll()).isEqualTo(1); - saved = deploymentManagement.assignDistributionSet(ds2, saved).getAssignedEntity(); + saved = assignDistributionSet(ds2, saved).getAssignedEntity(); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2); assertThat(deploymentManagement.countActionsAll()).isEqualTo(2); @@ -225,11 +225,12 @@ public void deplomentForceAction() throws Exception { @Description("Checks that the deployementBase URL changes when the action is switched from soft to forced in TIMEFORCED case.") public void changeEtagIfActionSwitchesFromSoftToForced() throws Exception { // Prepare test data - final Target target = targetManagement.createTarget(entityFactory.generateTarget("4712")); + final Target target = testdataFactory.createTarget("4712"); final DistributionSet ds = testdataFactory.createDistributionSet("", true); final DistributionSetAssignmentResult result = deploymentManagement.assignDistributionSet(ds.getId(), - ActionType.TIMEFORCED, System.currentTimeMillis() + 1_000, target.getControllerId()); + ActionType.TIMEFORCED, System.currentTimeMillis() + 1_000, + Lists.newArrayList(target.getControllerId())); final Action action = deploymentManagement.findActiveActionsByTarget(result.getAssignedEntity().get(0)).get(0); @@ -264,29 +265,29 @@ public void changeEtagIfActionSwitchesFromSoftToForced() throws Exception { @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 = entityFactory.generateTarget("4712"); final DistributionSet ds = testdataFactory.createDistributionSet("", true); final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true); final byte random[] = RandomUtils.nextBytes(5 * 1024); - final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), - ds.findFirstModuleByType(osType).getId(), "test1", false); + final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), getOsModule(ds), + "test1", false); final Artifact artifactSignature = artifactManagement.createArtifact(new ByteArrayInputStream(random), - ds.findFirstModuleByType(osType).getId(), "test1.signature", false); + getOsModule(ds), "test1.signature", false); - final Target savedTarget = targetManagement.createTarget(target); + final Target savedTarget = testdataFactory.createTarget("4712"); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).isEmpty(); assertThat(deploymentManagement.countActionsAll()).isEqualTo(0); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(0); List saved = deploymentManagement.assignDistributionSet(ds.getId(), ActionType.SOFT, - RepositoryModelConstants.NO_FORCE_TIME, savedTarget.getControllerId()).getAssignedEntity(); + RepositoryModelConstants.NO_FORCE_TIME, Lists.newArrayList(savedTarget.getControllerId())) + .getAssignedEntity(); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); final Action action = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0); assertThat(deploymentManagement.countActionsAll()).isEqualTo(1); - saved = deploymentManagement.assignDistributionSet(ds2, saved).getAssignedEntity(); + saved = assignDistributionSet(ds2, saved).getAssignedEntity(); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2); assertThat(deploymentManagement.countActionsAll()).isEqualTo(2); @@ -334,41 +335,34 @@ public void deplomentAttemptAction() throws Exception { .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].filename", contains("test1"))) .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.md5", contains(artifact.getMd5Hash()))) - .andExpect( - jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.sha1", - contains(artifact.getSha1Hash()))) + .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.sha1", + contains(artifact.getSha1Hash()))) .andExpect( jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.download.href", contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/" - + findDistributionSetByAction.findFirstModuleByType(osType).getId() - + "/artifacts/test1"))) + + getOsModule(findDistributionSetByAction) + "/artifacts/test1"))) .andExpect( jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.md5sum.href", contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/" - + findDistributionSetByAction.findFirstModuleByType(osType).getId() - + "/artifacts/test1.MD5SUM"))) + + getOsModule(findDistributionSetByAction) + "/artifacts/test1.MD5SUM"))) .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].size", contains(5 * 1024))) .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].filename", contains("test1.signature"))) .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].hashes.md5", contains(artifactSignature.getMd5Hash()))) - .andExpect( - jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].hashes.sha1", - contains(artifactSignature.getSha1Hash()))) + .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].hashes.sha1", + contains(artifactSignature.getSha1Hash()))) .andExpect( jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.download.href", contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/" - + findDistributionSetByAction.findFirstModuleByType(osType).getId() - + "/artifacts/test1.signature"))) - .andExpect( - jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.md5sum.href", - contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant() - + "/controller/v1/4712/softwaremodules/" - + findDistributionSetByAction.findFirstModuleByType(osType).getId() - + "/artifacts/test1.signature.MD5SUM"))) + + getOsModule(findDistributionSetByAction) + "/artifacts/test1.signature"))) + .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.md5sum.href", + contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant() + + "/controller/v1/4712/softwaremodules/" + getOsModule(findDistributionSetByAction) + + "/artifacts/test1.signature.MD5SUM"))) .andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].version", contains(ds.findFirstModuleByType(appType).getVersion()))) .andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].name", @@ -388,29 +382,28 @@ public void deplomentAttemptAction() throws Exception { @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 = entityFactory.generateTarget("4712"); final DistributionSet ds = testdataFactory.createDistributionSet("", true); final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true); final byte random[] = RandomUtils.nextBytes(5 * 1024); - final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), - ds.findFirstModuleByType(osType).getId(), "test1", false); + final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), getOsModule(ds), + "test1", false); final Artifact artifactSignature = artifactManagement.createArtifact(new ByteArrayInputStream(random), - ds.findFirstModuleByType(osType).getId(), "test1.signature", false); + getOsModule(ds), "test1.signature", false); - final Target savedTarget = targetManagement.createTarget(target); + final Target savedTarget = testdataFactory.createTarget("4712"); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).isEmpty(); assertThat(deploymentManagement.countActionsAll()).isEqualTo(0); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(0); List saved = deploymentManagement.assignDistributionSet(ds.getId(), ActionType.TIMEFORCED, - System.currentTimeMillis(), savedTarget.getControllerId()).getAssignedEntity(); + System.currentTimeMillis(), Lists.newArrayList(savedTarget.getControllerId())).getAssignedEntity(); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); final Action action = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0); assertThat(deploymentManagement.countActionsAll()).isEqualTo(1); - saved = deploymentManagement.assignDistributionSet(ds2, saved).getAssignedEntity(); + saved = assignDistributionSet(ds2, saved).getAssignedEntity(); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2); @@ -511,7 +504,7 @@ public void deplomentAutoForceAction() throws Exception { @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(entityFactory.generateTarget("4712")); + final Target target = testdataFactory.createTarget("4712"); // not allowed methods mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/1", tenantAware.getCurrentTenant())) @@ -536,8 +529,8 @@ public void badDeploymentAction() throws Exception { toAssign.add(target); final DistributionSet savedSet = testdataFactory.createDistributionSet(""); - final Action action1 = deploymentManagement.findActionWithDetails( - deploymentManagement.assignDistributionSet(savedSet, toAssign).getActions().get(0)); + final Action action1 = deploymentManagement + .findActionWithDetails(assignDistributionSet(savedSet, toAssign).getActions().get(0)); mvc.perform( get("/{tenant}/controller/v1/4712/deploymentBase/" + action1.getId(), tenantAware.getCurrentTenant())) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); @@ -551,13 +544,10 @@ public void badDeploymentAction() throws Exception { @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(entityFactory.generateTarget("4712")); + final Target target = testdataFactory.createTarget("4712"); final DistributionSet ds = testdataFactory.createDistributionSet(""); - final List toAssign = new ArrayList<>(); - toAssign.add(target); - - deploymentManagement.assignDistributionSet(ds.getId(), new String[] { "4712" }); + assignDistributionSet(ds.getId(), "4712"); final Action action = deploymentManagement.findActionsByTarget(target).get(0); final String feedback = JsonBuilder.deploymentActionFeedback(action.getId().toString(), "proceeding"); @@ -578,12 +568,9 @@ public void toMuchDeplomentActionFeedback() throws Exception { @Test @Description("Multiple uploads of deployment status feedback to the server.") public void multipleDeplomentActionFeedback() throws Exception { - 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 Target savedTarget1 = testdataFactory.createTarget("4712"); + testdataFactory.createTarget("4713"); + testdataFactory.createTarget("4714"); final DistributionSet ds1 = testdataFactory.createDistributionSet("1", true); final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true); @@ -592,12 +579,12 @@ public void multipleDeplomentActionFeedback() throws Exception { final List toAssign = new ArrayList<>(); toAssign.add(savedTarget1); - final Action action1 = deploymentManagement.findActionWithDetails( - deploymentManagement.assignDistributionSet(ds1.getId(), new String[] { "4712" }).getActions().get(0)); - final Action action2 = deploymentManagement.findActionWithDetails( - deploymentManagement.assignDistributionSet(ds2.getId(), new String[] { "4712" }).getActions().get(0)); - final Action action3 = deploymentManagement.findActionWithDetails( - deploymentManagement.assignDistributionSet(ds3.getId(), new String[] { "4712" }).getActions().get(0)); + final Action action1 = deploymentManagement + .findActionWithDetails(assignDistributionSet(ds1.getId(), "4712").getActions().get(0)); + final Action action2 = deploymentManagement + .findActionWithDetails(assignDistributionSet(ds2.getId(), "4712").getActions().get(0)); + final Action action3 = deploymentManagement + .findActionWithDetails(assignDistributionSet(ds3.getId(), "4712").getActions().get(0)); Target myT = targetManagement.findTargetByControllerID("4712"); assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); @@ -680,17 +667,15 @@ public void multipleDeplomentActionFeedback() throws Exception { @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 = entityFactory.generateTarget("4712"); DistributionSet ds = testdataFactory.createDistributionSet(""); - - final Target savedTarget = targetManagement.createTarget(target); + final Target savedTarget = testdataFactory.createTarget("4712"); List toAssign = new ArrayList<>(); toAssign.add(savedTarget); assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) .isEqualTo(TargetUpdateStatus.UNKNOWN); - deploymentManagement.assignDistributionSet(ds, toAssign); + assignDistributionSet(ds, toAssign); final Action action = deploymentManagement.findActionsByDistributionSet(pageReq, ds).getContent().get(0); long current = System.currentTimeMillis(); @@ -720,10 +705,10 @@ public void rootRsSingleDeplomentActionWithErrorFeedback() throws Exception { assertThat(actionStatusMessages).haveAtLeast(1, new ActionStatusCondition(Status.ERROR)); // redo - toAssign = new ArrayList(); + toAssign = new ArrayList<>(); toAssign.add(targetManagement.findTargetByControllerID("4712")); ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId()); - deploymentManagement.assignDistributionSet(ds, toAssign); + assignDistributionSet(ds, toAssign); final Action action2 = deploymentManagement.findActiveActionsByTarget(myT).get(0); current = System.currentTimeMillis(); lastModified = targetManagement.findTargetByControllerID("4712").getLastModifiedAt(); @@ -757,17 +742,15 @@ public void rootRsSingleDeplomentActionWithErrorFeedback() throws Exception { @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 = entityFactory.generateTarget("4712"); final DistributionSet ds = testdataFactory.createDistributionSet(""); - final Target savedTarget = targetManagement.createTarget(target); + final Target savedTarget = testdataFactory.createTarget("4712"); - final List toAssign = new ArrayList<>(); - toAssign.add(savedTarget); + final List toAssign = Lists.newArrayList(savedTarget); Target myT = targetManagement.findTargetByControllerID("4712"); assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.UNKNOWN); - deploymentManagement.assignDistributionSet(ds, toAssign); + assignDistributionSet(ds, toAssign); final Action action = deploymentManagement.findActionsByDistributionSet(pageReq, ds).getContent().get(0); myT = targetManagement.findTargetByControllerID("4712"); @@ -914,8 +897,6 @@ public void rootRsSingleDeplomentActionFeedback() throws Exception { @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 = entityFactory.generateTarget("4712"); - final Target target2 = entityFactory.generateTarget("4713"); final DistributionSet savedSet = testdataFactory.createDistributionSet(""); final DistributionSet savedSet2 = testdataFactory.createDistributionSet("1"); @@ -925,8 +906,8 @@ public void badDeplomentActionFeedback() throws Exception { .accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isNotFound()); - Target savedTarget = targetManagement.createTarget(target); - final Target savedTarget2 = targetManagement.createTarget(target2); + Target savedTarget = testdataFactory.createTarget("4712"); + final Target savedTarget2 = testdataFactory.createTarget("4713"); // Action does not exists mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/1234/feedback", tenantAware.getCurrentTenant()) @@ -937,9 +918,8 @@ public void badDeplomentActionFeedback() throws Exception { final List toAssign = Lists.newArrayList(savedTarget); final List toAssign2 = Lists.newArrayList(savedTarget2); - savedTarget = deploymentManagement.assignDistributionSet(savedSet, toAssign).getAssignedEntity().iterator() - .next(); - deploymentManagement.assignDistributionSet(savedSet2, toAssign2); + savedTarget = assignDistributionSet(savedSet, toAssign).getAssignedEntity().iterator().next(); + assignDistributionSet(savedSet2, toAssign2); // wrong format mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/AAAA/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 7e7fb6c233..589ceb68c6 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 @@ -23,11 +23,12 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import java.util.ArrayList; -import java.util.List; - import org.eclipse.hawkbit.im.authentication.SpPermission; +import org.eclipse.hawkbit.repository.event.remote.TargetAssignDistributionSetEvent; import org.eclipse.hawkbit.repository.event.remote.TargetDeletedEvent; +import org.eclipse.hawkbit.repository.event.remote.entity.ActionCreatedEvent; +import org.eclipse.hawkbit.repository.event.remote.entity.ActionUpdatedEvent; +import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetCreatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.TargetCreatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.TargetUpdatedEvent; import org.eclipse.hawkbit.repository.model.Action; @@ -96,7 +97,7 @@ public void targetPollDoesNotModifyAuditData() throws Exception { // create target first with "knownPrincipal" user and audit data final String knownTargetControllerId = "target1"; final String knownCreatedBy = "knownPrincipal"; - targetManagement.createTarget(entityFactory.generateTarget(knownTargetControllerId)); + testdataFactory.createTarget(knownTargetControllerId); final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownTargetControllerId); assertThat(findTargetByControllerID.getCreatedBy()).isEqualTo(knownCreatedBy); assertThat(findTargetByControllerID.getCreatedAt()).isNotNull(); @@ -186,7 +187,7 @@ public void rootRsNotModified() throws Exception { final Target target = targetManagement.findTargetByControllerID("4711"); final DistributionSet ds = testdataFactory.createDistributionSet(""); - deploymentManagement.assignDistributionSet(ds.getId(), new String[] { "4711" }); + assignDistributionSet(ds.getId(), "4711"); final Action updateAction = deploymentManagement.findActiveActionsByTarget(target).get(0); final String etagWithFirstUpdate = mvc @@ -219,7 +220,7 @@ public void rootRsNotModified() throws Exception { // Now another deployment final DistributionSet ds2 = testdataFactory.createDistributionSet("2"); - deploymentManagement.assignDistributionSet(ds2.getId(), new String[] { "4711" }); + assignDistributionSet(ds2.getId(), "4711"); final Action updateAction2 = deploymentManagement.findActiveActionsByTarget(target).get(0); @@ -240,8 +241,7 @@ public void rootRsNotModified() throws Exception { @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1), @Expect(type = TargetUpdatedEvent.class, count = 1) }) public void rootRsPrecommissioned() throws Exception { - final Target target = entityFactory.generateTarget("4711"); - targetManagement.createTarget(target); + final Target target = testdataFactory.createTarget("4711"); assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getUpdateStatus()) .isEqualTo(TargetUpdateStatus.UNKNOWN); @@ -296,15 +296,16 @@ public void rootRsIpAddressNotStoredIfDisabled() throws Exception { @Test @Description("Controller trys to finish an update process after it has been finished by an error action status.") + @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1), + @Expect(type = DistributionSetCreatedEvent.class, count = 1), + @Expect(type = TargetAssignDistributionSetEvent.class, count = 1), + @Expect(type = ActionCreatedEvent.class, count = 1), @Expect(type = ActionUpdatedEvent.class, count = 1), + @Expect(type = TargetUpdatedEvent.class, count = 2) }) public void tryToFinishAnUpdateProcessAfterItHasBeenFinished() throws Exception { - - // mock - final Target target = entityFactory.generateTarget("911"); final DistributionSet ds = testdataFactory.createDistributionSet(""); - Target savedTarget = targetManagement.createTarget(target); - final List toAssign = new ArrayList<>(); - toAssign.add(savedTarget); - savedTarget = deploymentManagement.assignDistributionSet(ds, toAssign).getAssignedEntity().iterator().next(); + Target savedTarget = testdataFactory.createTarget("911"); + savedTarget = assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getAssignedEntity().iterator() + .next(); final Action savedAction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0); mvc.perform(post("/{tenant}/controller/v1/911/deploymentBase/" + savedAction.getId() + "/feedback", tenantAware.getCurrentTenant()) 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 index d63d9efc19..83eb9c0047 100644 --- 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 @@ -13,7 +13,6 @@ 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; @@ -27,6 +26,7 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MvcResult; +import com.google.common.collect.Lists; import com.google.common.net.HttpHeaders; import ru.yandex.qatools.allure.annotations.Description; @@ -147,11 +147,10 @@ public void acceptablePutPostLoad() throws Exception { 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 Target target = testdataFactory.createTarget("4711"); + final List toAssign = Lists.newArrayList(target); - final Iterable saved = deploymentManagement.assignDistributionSet(ds, toAssign).getAssignedEntity(); + final Iterable saved = assignDistributionSet(ds, toAssign).getAssignedEntity(); assertThat(deploymentManagement.findActiveActionsByTarget(target)).hasSize(1); final Action uaction = deploymentManagement.findActiveActionsByTarget(target).get(0); diff --git a/hawkbit-ddi-resource/src/test/resources/application-test.properties b/hawkbit-ddi-resource/src/test/resources/application-test.properties index 762218d22e..f4d7832c4a 100644 --- a/hawkbit-ddi-resource/src/test/resources/application-test.properties +++ b/hawkbit-ddi-resource/src/test/resources/application-test.properties @@ -7,6 +7,7 @@ # http://www.eclipse.org/legal/epl-v10.html # +#logging.level.org.eclipse.hawkbit.rest.util.MockMvcResultPrinter=DEBUG logging.level.=INFO logging.level.org.eclipse.persistence=ERROR 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 14698c9f42..250f80d9a0 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 @@ -11,6 +11,7 @@ import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Collections; +import java.util.List; import java.util.Optional; import java.util.UUID; @@ -25,11 +26,11 @@ import org.eclipse.hawkbit.repository.ControllerManagement; import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.RepositoryConstants; +import org.eclipse.hawkbit.repository.builder.ActionStatusCreate; import org.eclipse.hawkbit.repository.exception.TenantNotExistException; import org.eclipse.hawkbit.repository.exception.TooManyStatusEntriesException; 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.Target; import org.eclipse.hawkbit.util.IpUtil; import org.slf4j.Logger; @@ -224,42 +225,66 @@ private void updateActionStatus(final Message message) { final ActionUpdateStatus actionUpdateStatus = convertMessage(message, ActionUpdateStatus.class); final Action action = checkActionExist(message, actionUpdateStatus); - final ActionStatus actionStatus = createActionStatus(message, actionUpdateStatus, action); + final List messages = actionUpdateStatus.getMessage(); + if (ArrayUtils.isNotEmpty(message.getMessageProperties().getCorrelationId())) { + messages.add(RepositoryConstants.SERVER_MESSAGE_PREFIX + "DMF message correlation-id " + + convertCorrelationId(message)); + } + updateLastPollTime(action.getTarget()); + final Status status = mapStatus(message, actionUpdateStatus, action); + final ActionStatusCreate actionStatus = entityFactory.actionStatus().create(action.getId()).status(status) + .messages(messages); + + final Action addUpdateActionStatus = getUpdateActionStatus(status, actionStatus); + + if (!addUpdateActionStatus.isActive()) { + lookIfUpdateAvailable(action.getTarget()); + } + } + + private Status mapStatus(final Message message, final ActionUpdateStatus actionUpdateStatus, final Action action) { + Status status = null; switch (actionUpdateStatus.getActionStatus()) { case DOWNLOAD: - actionStatus.setStatus(Status.DOWNLOAD); + status = Status.DOWNLOAD; break; case RETRIEVED: - actionStatus.setStatus(Status.RETRIEVED); + status = Status.RETRIEVED; break; case RUNNING: - actionStatus.setStatus(Status.RUNNING); + status = Status.RUNNING; break; case CANCELED: - actionStatus.setStatus(Status.CANCELED); + status = Status.CANCELED; break; case FINISHED: - actionStatus.setStatus(Status.FINISHED); + status = Status.FINISHED; break; case ERROR: - actionStatus.setStatus(Status.ERROR); + status = Status.ERROR; break; case WARNING: - actionStatus.setStatus(Status.WARNING); + status = Status.WARNING; break; case CANCEL_REJECTED: - handleCancelRejected(message, action, actionStatus); + status = hanldeCancelRejectedState(message, action); break; default: logAndThrowMessageError(message, "Status for action does not exisit."); } - final Action addUpdateActionStatus = getUpdateActionStatus(actionStatus); + return status; + } - if (!addUpdateActionStatus.isActive()) { - lookIfUpdateAvailable(action.getTarget()); + private Status hanldeCancelRejectedState(final Message message, final Action action) { + if (action.isCancelingOrCanceled()) { + return Status.WARNING; + } else { + logAndThrowMessageError(message, + "Cancel recjected message is not allowed, if action is on state: " + action.getStatus()); + return null; } } @@ -267,27 +292,12 @@ private void updateLastPollTime(final Target target) { controllerManagement.updateTargetStatus(target.getTargetInfo(), null, System.currentTimeMillis(), null); } - private ActionStatus createActionStatus(final Message message, final ActionUpdateStatus actionUpdateStatus, - final Action action) { - final ActionStatus actionStatus = entityFactory.generateActionStatus(); - actionUpdateStatus.getMessage().forEach(actionStatus::addMessage); - - if (ArrayUtils.isNotEmpty(message.getMessageProperties().getCorrelationId())) { - actionStatus.addMessage(RepositoryConstants.SERVER_MESSAGE_PREFIX + "DMF message correlation-id " - + convertCorrelationId(message)); - } - - actionStatus.setAction(action); - actionStatus.setOccurredAt(System.currentTimeMillis()); - return actionStatus; - } - private static String convertCorrelationId(final Message message) { return new String(message.getMessageProperties().getCorrelationId(), StandardCharsets.UTF_8); } - private Action getUpdateActionStatus(final ActionStatus actionStatus) { - if (actionStatus.getStatus().equals(Status.CANCELED)) { + private Action getUpdateActionStatus(final Status status, final ActionStatusCreate actionStatus) { + if (Status.CANCELED.equals(status)) { return controllerManagement.addCancelActionStatus(actionStatus); } return controllerManagement.addUpdateActionStatus(actionStatus); @@ -310,18 +320,4 @@ private Action checkActionExist(final Message message, final ActionUpdateStatus } return action; } - - private static void handleCancelRejected(final Message message, final Action action, - final ActionStatus actionStatus) { - if (action.isCancelingOrCanceled()) { - - actionStatus.setStatus(Status.WARNING); - - // cancel action rejected, write warning status message and fall - // back to running action status - } else { - logAndThrowMessageError(message, - "Cancel recjected message is not allowed, if action is on state: " + action.getStatus()); - } - } } diff --git a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthenticationTest.java b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthenticationTest.java index 07e5b245e8..64ca8590a0 100644 --- a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthenticationTest.java +++ b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthenticationTest.java @@ -123,8 +123,7 @@ public void before() throws Exception { final DdiSecurityProperties secruityProperties = mock(DdiSecurityProperties.class); final Rp rp = mock(Rp.class); - final org.eclipse.hawkbit.security.DdiSecurityProperties.Authentication ddiAuthentication = mock( - org.eclipse.hawkbit.security.DdiSecurityProperties.Authentication.class); + final DdiSecurityProperties.Authentication ddiAuthentication = mock(DdiSecurityProperties.Authentication.class); final Anonymous anonymous = mock(Anonymous.class); when(secruityProperties.getRp()).thenReturn(rp); when(rp.getSslIssuerHashHeader()).thenReturn("X-Ssl-Issuer-Hash-%d"); 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 448c3c7cec..6ab7286024 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 @@ -34,9 +34,7 @@ import org.eclipse.hawkbit.repository.event.remote.TargetAssignDistributionSetEvent; import org.eclipse.hawkbit.repository.event.remote.entity.CancelTargetAssignmentEvent; import org.eclipse.hawkbit.repository.jpa.ActionRepository; -import org.eclipse.hawkbit.repository.jpa.model.JpaAction; import org.eclipse.hawkbit.repository.model.Action; -import org.eclipse.hawkbit.repository.model.Action.ActionType; import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.SoftwareModule; @@ -93,9 +91,8 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest { @Override public void before() throws Exception { super.before(); - final Target generateTarget = entityFactory.generateTarget(CONTROLLER_ID, TEST_TOKEN); - generateTarget.getTargetInfo().setAddress(AMQP_URI.toString()); - testTarget = targetManagement.createTarget(generateTarget); + testTarget = targetManagement.createTarget(entityFactory.target().create().controllerId(CONTROLLER_ID) + .securityToken(TEST_TOKEN).address(AMQP_URI.toString())); this.rabbitTemplate = Mockito.mock(RabbitTemplate.class); when(rabbitTemplate.getMessageConverter()).thenReturn(new Jackson2JsonMessageConverter()); @@ -121,15 +118,13 @@ public void before() throws Exception { @Test @Description("Verfies that download and install event with no software modul works") public void testSendDownloadRequesWithEmptySoftwareModules() { - final Action action = createAction( - testdataFactory.createDistributionSetWithNoSoftwareModules(UUID.randomUUID().toString(), "1.0")); final TargetAssignDistributionSetEvent targetAssignDistributionSetEvent = new TargetAssignDistributionSetEvent( - action, serviceMatcher.getServiceId()); + "DEFAULT", 1L, 1L, CONTROLLER_ID, serviceMatcher.getServiceId()); amqpMessageDispatcherService.targetAssignDistributionSet(targetAssignDistributionSetEvent); final Message sendMessage = getCaptureAdressEvent(targetAssignDistributionSetEvent); - final DownloadAndUpdateRequest downloadAndUpdateRequest = assertDownloadAndInstallMessage(sendMessage, action); + final DownloadAndUpdateRequest downloadAndUpdateRequest = assertDownloadAndInstallMessage(sendMessage, 1L); assertThat(downloadAndUpdateRequest.getTargetSecurityToken()).isEqualTo(TEST_TOKEN); assertTrue("No softwaremmodule should be contained in the request", downloadAndUpdateRequest.getSoftwareModules().isEmpty()); @@ -142,14 +137,8 @@ private Message getCaptureAdressEvent(final TargetAssignDistributionSetEvent tar return sendMessage; } - private JpaAction createAction(final DistributionSet testDs) { - final Action action = entityFactory.generateAction(); - final JpaAction jpaAction = (JpaAction) action; - action.setDistributionSet(testDs); - action.setTarget(testTarget); - jpaAction.setActionType(ActionType.FORCED); - - return actionRepository.save(jpaAction); + private Action createAction(final DistributionSet testDs) { + return deploymentManagement.findAction(assignDistributionSet(testDs, testTarget).getActions().get(0)); } @Test @@ -163,7 +152,8 @@ public void testSendDownloadRequesWithSoftwareModulesAndNoArtifacts() { action, serviceMatcher.getServiceId()); amqpMessageDispatcherService.targetAssignDistributionSet(targetAssignDistributionSetEvent); final Message sendMessage = getCaptureAdressEvent(targetAssignDistributionSetEvent); - final DownloadAndUpdateRequest downloadAndUpdateRequest = assertDownloadAndInstallMessage(sendMessage, action); + final DownloadAndUpdateRequest downloadAndUpdateRequest = assertDownloadAndInstallMessage(sendMessage, + action.getId()); assertThat(createDistributionSet.getModules()).hasSameSizeAs(downloadAndUpdateRequest.getSoftwareModules()); assertThat(downloadAndUpdateRequest.getTargetSecurityToken()).isEqualTo(TEST_TOKEN); for (final org.eclipse.hawkbit.dmf.json.model.SoftwareModule softwareModule : downloadAndUpdateRequest @@ -187,13 +177,14 @@ public void testSendDownloadRequesWithSoftwareModulesAndNoArtifacts() { @Test @Description("Verfies that download and install event with software moduls and artifacts works") public void testSendDownloadRequest() { - final DistributionSet dsA = testdataFactory.createDistributionSet(UUID.randomUUID().toString()); - final SoftwareModule module = dsA.getModules().iterator().next(); + DistributionSet dsA = testdataFactory.createDistributionSet(UUID.randomUUID().toString()); + SoftwareModule module = dsA.getModules().iterator().next(); final List receivedList = new ArrayList<>(); for (final Artifact artifact : testdataFactory.createArtifacts(module.getId())) { - module.addArtifact(artifact); receivedList.add(new DbArtifact()); } + module = softwareManagement.findSoftwareModuleById(module.getId()); + dsA = distributionSetManagement.findDistributionSetById(dsA.getId()); final Action action = createAction(dsA); @@ -203,7 +194,8 @@ public void testSendDownloadRequest() { action, serviceMatcher.getServiceId()); amqpMessageDispatcherService.targetAssignDistributionSet(targetAssignDistributionSetEvent); final Message sendMessage = getCaptureAdressEvent(targetAssignDistributionSetEvent); - final DownloadAndUpdateRequest downloadAndUpdateRequest = assertDownloadAndInstallMessage(sendMessage, action); + final DownloadAndUpdateRequest downloadAndUpdateRequest = assertDownloadAndInstallMessage(sendMessage, + action.getId()); assertEquals("DownloadAndUpdateRequest event should contains 3 software modules", 3, downloadAndUpdateRequest.getSoftwareModules().size()); @@ -251,11 +243,11 @@ private void assertCancelMessage(final Message sendMessage) { } - private DownloadAndUpdateRequest assertDownloadAndInstallMessage(final Message sendMessage, final Action action) { + private DownloadAndUpdateRequest assertDownloadAndInstallMessage(final Message sendMessage, final Long action) { assertEventMessage(sendMessage); final DownloadAndUpdateRequest downloadAndUpdateRequest = convertMessage(sendMessage, DownloadAndUpdateRequest.class); - assertEquals(downloadAndUpdateRequest.getActionId(), action.getId()); + assertEquals(downloadAndUpdateRequest.getActionId(), action); assertEquals("The topic of the event shuold contain DOWNLOAD_AND_INSTALL", EventTopic.DOWNLOAD_AND_INSTALL, sendMessage.getMessageProperties().getHeaders().get(MessageHeaderKey.TOPIC)); assertEquals("Security token of target", downloadAndUpdateRequest.getTargetSecurityToken(), TEST_TOKEN); 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 ff4c5a82b3..c1d8ba35b9 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 @@ -40,16 +40,16 @@ import org.eclipse.hawkbit.repository.ArtifactManagement; import org.eclipse.hawkbit.repository.ControllerManagement; import org.eclipse.hawkbit.repository.EntityFactory; +import org.eclipse.hawkbit.repository.builder.ActionStatusBuilder; +import org.eclipse.hawkbit.repository.builder.ActionStatusCreate; 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.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.Artifact; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.Target; +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.security.SecurityTokenGenerator; @@ -359,7 +359,11 @@ public void lookupNextUpdateActionAfterFinished() throws IllegalAccessException final Action action = createActionWithTarget(22L, Status.FINISHED); when(controllerManagementMock.findActionWithDetails(Matchers.any())).thenReturn(action); when(controllerManagementMock.addUpdateActionStatus(Matchers.any())).thenReturn(action); - when(entityFactoryMock.generateActionStatus()).thenReturn(new JpaActionStatus()); + final ActionStatusBuilder builder = mock(ActionStatusBuilder.class); + final ActionStatusCreate create = mock(ActionStatusCreate.class); + when(builder.create(22L)).thenReturn(create); + when(create.status(Matchers.any())).thenReturn(create); + when(entityFactoryMock.actionStatus()).thenReturn(builder); // for the test the same action can be used when(controllerManagementMock.findOldestActiveActionByTarget(Matchers.any())).thenReturn(Optional.of(action)); @@ -424,8 +428,8 @@ private Action createActionWithTarget(final Long targetId, final Status status) initalizeSecurityTokenGenerator(); // Mock - final JpaAction actionMock = mock(JpaAction.class); - final JpaTarget targetMock = mock(JpaTarget.class); + final Action actionMock = mock(Action.class); + final Target targetMock = mock(Target.class); final TargetInfo targetInfoMock = mock(TargetInfo.class); final DistributionSet distributionSetMock = mock(DistributionSet.class); diff --git a/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/ActionUpdateStatus.java b/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/ActionUpdateStatus.java index f17252bd8c..a2024bfc63 100644 --- a/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/ActionUpdateStatus.java +++ b/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/ActionUpdateStatus.java @@ -62,7 +62,7 @@ public List getMessage() { return Collections.emptyList(); } - return Collections.unmodifiableList(message); + return message; } public boolean addMessage(final String message) { diff --git a/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtDistributionSetRequestBodyPost.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtDistributionSetRequestBodyPost.java index a56b5aaba2..f38c80203b 100644 --- a/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtDistributionSetRequestBodyPost.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtDistributionSetRequestBodyPost.java @@ -41,7 +41,7 @@ public class MgmtDistributionSetRequestBodyPost extends MgmtDistributionSetReque private List modules; @JsonProperty - private boolean requiredMigrationStep; + private Boolean requiredMigrationStep; @JsonProperty private String type; @@ -105,7 +105,7 @@ public MgmtDistributionSetRequestBodyPost setApplication(final MgmtSoftwareModul /** * @return the requiredMigrationStep */ - public boolean isRequiredMigrationStep() { + public Boolean isRequiredMigrationStep() { return requiredMigrationStep; } @@ -115,7 +115,7 @@ public boolean isRequiredMigrationStep() { * * @return updated body */ - public MgmtDistributionSetRequestBodyPost setRequiredMigrationStep(final boolean requiredMigrationStep) { + public MgmtDistributionSetRequestBodyPost setRequiredMigrationStep(final Boolean requiredMigrationStep) { this.requiredMigrationStep = requiredMigrationStep; return this; diff --git a/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionsettype/MgmtDistributionSetTypeRequestBodyPost.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionsettype/MgmtDistributionSetTypeRequestBodyPost.java index 82ecb2cc5e..673623d905 100644 --- a/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionsettype/MgmtDistributionSetTypeRequestBodyPost.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionsettype/MgmtDistributionSetTypeRequestBodyPost.java @@ -18,14 +18,11 @@ * Request Body for DistributionSetType POST. * */ -public class MgmtDistributionSetTypeRequestBodyPost { +public class MgmtDistributionSetTypeRequestBodyPost extends MgmtDistributionSetTypeRequestBodyPut { @JsonProperty(required = true) private String name; - @JsonProperty - private String description; - @JsonProperty private String key; @@ -35,6 +32,18 @@ public class MgmtDistributionSetTypeRequestBodyPost { @JsonProperty private List optionalmodules; + @Override + public MgmtDistributionSetTypeRequestBodyPost setDescription(final String description) { + super.setDescription(description); + return this; + } + + @Override + public MgmtDistributionSetTypeRequestBodyPost setColour(final String colour) { + super.setColour(colour); + return this; + } + /** * @return the name */ @@ -53,24 +62,6 @@ public MgmtDistributionSetTypeRequestBodyPost setName(final String name) { return this; } - /** - * @return the description - */ - public String getDescription() { - return description; - } - - /** - * @param description - * the description to set - * - * @return updated body - */ - public MgmtDistributionSetTypeRequestBodyPost setDescription(final String description) { - this.description = description; - return this; - } - /** * @return the key */ diff --git a/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionsettype/MgmtDistributionSetTypeRequestBodyPut.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionsettype/MgmtDistributionSetTypeRequestBodyPut.java index 220f58e4d2..1d3d0feb60 100644 --- a/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionsettype/MgmtDistributionSetTypeRequestBodyPut.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionsettype/MgmtDistributionSetTypeRequestBodyPut.java @@ -19,22 +19,25 @@ public class MgmtDistributionSetTypeRequestBodyPut { @JsonProperty private String description; - /** - * @return the description - */ + @JsonProperty + private String colour; + public String getDescription() { return description; } - /** - * @param description - * the description to set - * - * @return updated body - */ public MgmtDistributionSetTypeRequestBodyPut setDescription(final String description) { this.description = description; return this; } + public String getColour() { + return colour; + } + + public MgmtDistributionSetTypeRequestBodyPut setColour(final String colour) { + this.colour = colour; + return this; + } + } diff --git a/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremoduletype/MgmtSoftwareModuleTypeRequestBodyPost.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremoduletype/MgmtSoftwareModuleTypeRequestBodyPost.java index 836c39d199..1727d70438 100644 --- a/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremoduletype/MgmtSoftwareModuleTypeRequestBodyPost.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremoduletype/MgmtSoftwareModuleTypeRequestBodyPost.java @@ -14,20 +14,29 @@ * Request Body for SoftwareModuleType POST. * */ -public class MgmtSoftwareModuleTypeRequestBodyPost { +public class MgmtSoftwareModuleTypeRequestBodyPost extends MgmtSoftwareModuleTypeRequestBodyPut { @JsonProperty(required = true) private String name; - @JsonProperty - private String description; - @JsonProperty private String key; @JsonProperty private int maxAssignments; + @Override + public MgmtSoftwareModuleTypeRequestBodyPost setDescription(final String description) { + super.setDescription(description); + return this; + } + + @Override + public MgmtSoftwareModuleTypeRequestBodyPost setColour(final String colour) { + super.setColour(colour); + return this; + } + /** * @return the name */ @@ -46,24 +55,6 @@ public MgmtSoftwareModuleTypeRequestBodyPost setName(final String name) { return this; } - /** - * @return the description - */ - public String getDescription() { - return description; - } - - /** - * @param description - * the description to set - * - * @return updated body - */ - public MgmtSoftwareModuleTypeRequestBodyPost setDescription(final String description) { - this.description = description; - return this; - } - /** * @return the key */ diff --git a/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremoduletype/MgmtSoftwareModuleTypeRequestBodyPut.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremoduletype/MgmtSoftwareModuleTypeRequestBodyPut.java index ecc8c9f65a..a899f7afa6 100644 --- a/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremoduletype/MgmtSoftwareModuleTypeRequestBodyPut.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremoduletype/MgmtSoftwareModuleTypeRequestBodyPut.java @@ -19,22 +19,25 @@ public class MgmtSoftwareModuleTypeRequestBodyPut { @JsonProperty private String description; - /** - * @return the description - */ + @JsonProperty + private String colour; + public String getDescription() { return description; } - /** - * @param description - * the description to set - * - * @return updated body - */ public MgmtSoftwareModuleTypeRequestBodyPut setDescription(final String description) { this.description = description; return this; } + public String getColour() { + return colour; + } + + public MgmtSoftwareModuleTypeRequestBodyPut setColour(final String colour) { + this.colour = colour; + return this; + } + } 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 bca7a8c780..5f836bb015 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 @@ -24,15 +24,12 @@ import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetRestApi; 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.EntityFactory; -import org.eclipse.hawkbit.repository.SoftwareManagement; -import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; +import org.eclipse.hawkbit.repository.builder.DistributionSetCreate; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetAssignmentResult; import org.eclipse.hawkbit.repository.model.DistributionSetMetadata; -import org.eclipse.hawkbit.repository.model.DistributionSetType; -import org.eclipse.hawkbit.repository.model.SoftwareModule; +import org.eclipse.hawkbit.repository.model.MetaData; /** * A mapper which maps repository model to RESTful model representation and @@ -43,45 +40,17 @@ private MgmtDistributionSetMapper() { // Utility class } - private static SoftwareModule findSoftwareModuleWithExceptionIfNotFound(final Long softwareModuleId, - final SoftwareManagement softwareManagement) { - final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId); - if (module == null) { - throw new EntityNotFoundException("SoftwareModule with Id {" + softwareModuleId + "} does not exist"); - } - - return module; - } - - private static DistributionSetType findDistributionSetTypeWithExceptionIfNotFound( - final String distributionSetTypekey, final DistributionSetManagement distributionSetManagement) { - - final DistributionSetType module = distributionSetManagement - .findDistributionSetTypeByKey(distributionSetTypekey); - if (module == null) { - throw new EntityNotFoundException( - "DistributionSetType with key {" + distributionSetTypekey + "} does not exist"); - } - return module; - } - /** * {@link MgmtDistributionSetRequestBodyPost}s to {@link DistributionSet}s. * * @param sets * to convert - * @param softwareManagement - * to use for conversion * @return converted list of {@link DistributionSet}s */ - static List dsFromRequest(final Collection sets, - final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement, + static List dsFromRequest(final Collection sets, final EntityFactory entityFactory) { - return sets.stream() - .map(dsRest -> fromRequest(dsRest, softwareManagement, distributionSetManagement, entityFactory)) - .collect(Collectors.toList()); - + return sets.stream().map(dsRest -> fromRequest(dsRest, entityFactory)).collect(Collectors.toList()); } /** @@ -89,59 +58,42 @@ static List dsFromRequest(final Collection modules = new ArrayList<>(); if (dsRest.getOs() != null) { - result.addModule(findSoftwareModuleWithExceptionIfNotFound(dsRest.getOs().getId(), softwareManagement)); + modules.add(dsRest.getOs().getId()); } if (dsRest.getApplication() != null) { - result.addModule( - findSoftwareModuleWithExceptionIfNotFound(dsRest.getApplication().getId(), softwareManagement)); + modules.add(dsRest.getApplication().getId()); } if (dsRest.getRuntime() != null) { - result.addModule( - findSoftwareModuleWithExceptionIfNotFound(dsRest.getRuntime().getId(), softwareManagement)); + modules.add(dsRest.getRuntime().getId()); } if (dsRest.getModules() != null) { - dsRest.getModules().forEach(module -> result - .addModule(findSoftwareModuleWithExceptionIfNotFound(module.getId(), softwareManagement))); + dsRest.getModules().forEach(module -> modules.add(module.getId())); } - return result; + return entityFactory.distributionSet().create().name(dsRest.getName()).version(dsRest.getVersion()) + .description(dsRest.getDescription()).type(dsRest.getType()).modules(modules) + .requiredMigrationStep(dsRest.isRequiredMigrationStep()); } - /** - * From {@link MgmtMetadata} to {@link DistributionSetMetadata}. - * - * @param ds - * @param metadata - * @return - */ - static List fromRequestDsMetadata(final DistributionSet ds, - final List metadata, final EntityFactory entityFactory) { + static List fromRequestDsMetadata(final List metadata, final EntityFactory entityFactory) { if (metadata == null) { return Collections.emptyList(); } - return metadata.stream().map(metadataRest -> entityFactory.generateDistributionSetMetadata(ds, - metadataRest.getKey(), metadataRest.getValue())).collect(Collectors.toList()); + return metadata.stream() + .map(metadataRest -> entityFactory.generateMetadata(metadataRest.getKey(), metadataRest.getValue())) + .collect(Collectors.toList()); } /** 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 f8588a3c3a..ccd2a7e8f0 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 @@ -9,9 +9,7 @@ package org.eclipse.hawkbit.mgmt.rest.resource; import java.util.Collection; -import java.util.HashSet; import java.util.List; -import java.util.Set; import java.util.stream.Collectors; import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata; @@ -102,10 +100,9 @@ public ResponseEntity> getDistributionSets( final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting); final Page findDsPage; if (rsqlParam != null) { - findDsPage = this.distributionSetManagement.findDistributionSetsAll(rsqlParam, pageable, false); + findDsPage = distributionSetManagement.findDistributionSetsAll(rsqlParam, pageable, false); } else { - findDsPage = this.distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageable, false, - null); + findDsPage = distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageable, false, null); } final List rest = MgmtDistributionSetMapper.toResponseFromDsList(findDsPage.getContent()); @@ -127,12 +124,11 @@ public ResponseEntity> createDistributionSets( LOG.debug("creating {} distribution sets", sets.size()); // set default Ds type if ds type is null final String defaultDsKey = systemSecurityContext - .runAsSystem(() -> this.systemManagement.getTenantMetadata().getDefaultDsType().getKey()); + .runAsSystem(systemManagement.getTenantMetadata().getDefaultDsType()::getKey); sets.stream().filter(ds -> ds.getType() == null).forEach(ds -> ds.setType(defaultDsKey)); - final Collection createdDSets = this.distributionSetManagement - .createDistributionSets(MgmtDistributionSetMapper.dsFromRequest(sets, this.softwareManagement, - this.distributionSetManagement, entityFactory)); + final Collection createdDSets = distributionSetManagement + .createDistributionSets(MgmtDistributionSetMapper.dsFromRequest(sets, entityFactory)); LOG.debug("{} distribution sets created, return status {}", sets.size(), HttpStatus.CREATED); return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDistributionSets(createdDSets), @@ -143,7 +139,7 @@ public ResponseEntity> createDistributionSets( public ResponseEntity deleteDistributionSet(@PathVariable("distributionSetId") final Long distributionSetId) { final DistributionSet set = findDistributionSetWithExceptionIfNotFound(distributionSetId); - this.distributionSetManagement.deleteDistributionSet(set); + distributionSetManagement.deleteDistributionSet(set); return new ResponseEntity<>(HttpStatus.OK); } @@ -152,21 +148,11 @@ public ResponseEntity deleteDistributionSet(@PathVariable("distributionSet public ResponseEntity updateDistributionSet( @PathVariable("distributionSetId") final Long distributionSetId, @RequestBody final MgmtDistributionSetRequestBodyPut toUpdate) { - final DistributionSet set = findDistributionSetWithExceptionIfNotFound(distributionSetId); - - if (toUpdate.getDescription() != null) { - set.setDescription(toUpdate.getDescription()); - } - if (toUpdate.getName() != null) { - set.setName(toUpdate.getName()); - } - - if (toUpdate.getVersion() != null) { - set.setVersion(toUpdate.getVersion()); - } return new ResponseEntity<>( - MgmtDistributionSetMapper.toResponse(this.distributionSetManagement.updateDistributionSet(set)), + MgmtDistributionSetMapper.toResponse(distributionSetManagement.updateDistributionSet( + entityFactory.distributionSet().update(distributionSetId).name(toUpdate.getName()) + .description(toUpdate.getDescription()).version(toUpdate.getVersion()))), HttpStatus.OK); } @@ -224,20 +210,18 @@ public ResponseEntity> getInstalledTargets( pageable); } - return new ResponseEntity<>( - new PagedList(MgmtTargetMapper.toResponse(targetsInstalledDS.getContent()), - targetsInstalledDS.getTotalElements()), - HttpStatus.OK); + return new ResponseEntity<>(new PagedList<>(MgmtTargetMapper.toResponse(targetsInstalledDS.getContent()), + targetsInstalledDS.getTotalElements()), HttpStatus.OK); } @Override public ResponseEntity> getAutoAssignTargetFilterQueries( - @PathVariable("distributionSetId") Long distributionSetId, - @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) int pagingOffsetParam, - @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) int pagingLimitParam, - @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) String sortParam, - @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) String rsqlParam) { - DistributionSet distributionSet = findDistributionSetWithExceptionIfNotFound(distributionSetId); + @PathVariable("distributionSetId") final Long distributionSetId, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { + final DistributionSet distributionSet = findDistributionSetWithExceptionIfNotFound(distributionSetId); final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam); final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); @@ -294,11 +278,11 @@ public ResponseEntity> getMetadata( final Page metaDataPage; if (rsqlParam != null) { - metaDataPage = this.distributionSetManagement - .findDistributionSetMetadataByDistributionSetId(distributionSetId, rsqlParam, pageable); + metaDataPage = distributionSetManagement.findDistributionSetMetadataByDistributionSetId(distributionSetId, + rsqlParam, pageable); } else { - metaDataPage = this.distributionSetManagement - .findDistributionSetMetadataByDistributionSetId(distributionSetId, pageable); + metaDataPage = distributionSetManagement.findDistributionSetMetadataByDistributionSetId(distributionSetId, + pageable); } return new ResponseEntity<>( @@ -314,8 +298,8 @@ public ResponseEntity getMetadataValue( @PathVariable("metadataKey") final String metadataKey) { // check if distribution set exists otherwise throw exception // immediately - final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId); - final DistributionSetMetadata findOne = this.distributionSetManagement.findOne(ds, metadataKey); + final DistributionSetMetadata findOne = distributionSetManagement.findDistributionSetMetadata(distributionSetId, + metadataKey); return ResponseEntity. ok(MgmtDistributionSetMapper.toResponseDsMetadata(findOne)); } @@ -324,9 +308,8 @@ public ResponseEntity updateMetadata(@PathVariable("distributionSe @PathVariable("metadataKey") final String metadataKey, @RequestBody final MgmtMetadata metadata) { // check if distribution set exists otherwise throw exception // immediately - final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId); - final DistributionSetMetadata updated = this.distributionSetManagement.updateDistributionSetMetadata( - entityFactory.generateDistributionSetMetadata(ds, metadataKey, metadata.getValue())); + final DistributionSetMetadata updated = distributionSetManagement.updateDistributionSetMetadata( + distributionSetId, entityFactory.generateMetadata(metadataKey, metadata.getValue())); return ResponseEntity.ok(MgmtDistributionSetMapper.toResponseDsMetadata(updated)); } @@ -335,8 +318,7 @@ public ResponseEntity deleteMetadata(@PathVariable("distributionSetId") fi @PathVariable("metadataKey") final String metadataKey) { // check if distribution set exists otherwise throw exception // immediately - final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId); - this.distributionSetManagement.deleteDistributionSetMetadata(ds, metadataKey); + distributionSetManagement.deleteDistributionSetMetadata(distributionSetId, metadataKey); return ResponseEntity.ok().build(); } @@ -346,10 +328,8 @@ public ResponseEntity> createMetadata( @RequestBody final List metadataRest) { // check if distribution set exists otherwise throw exception // immediately - final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId); - - final List created = this.distributionSetManagement.createDistributionSetMetadata( - MgmtDistributionSetMapper.fromRequestDsMetadata(ds, metadataRest, entityFactory)); + final List created = distributionSetManagement.createDistributionSetMetadata( + distributionSetId, MgmtDistributionSetMapper.fromRequestDsMetadata(metadataRest, entityFactory)); return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDsMetadata(created), HttpStatus.CREATED); } @@ -357,21 +337,9 @@ public ResponseEntity> createMetadata( @Override public ResponseEntity assignSoftwareModules(@PathVariable("distributionSetId") final Long distributionSetId, @RequestBody final List softwareModuleIDs) { - // check if distribution set exists otherwise throw exception - // immediately - final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId); - - final Set softwareModuleToBeAssigned = new HashSet<>(); - for (final MgmtSoftwareModuleAssigment sm : softwareModuleIDs) { - final SoftwareModule softwareModule = this.softwareManagement.findSoftwareModuleById(sm.getId()); - if (softwareModule != null) { - softwareModuleToBeAssigned.add(softwareModule); - } else { - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } - } - // Add Softwaremodules to DisSet only if all of them were found - this.distributionSetManagement.assignSoftwareModules(ds, softwareModuleToBeAssigned); + + distributionSetManagement.assignSoftwareModules(distributionSetId, + softwareModuleIDs.stream().map(module -> module.getId()).collect(Collectors.toList())); return new ResponseEntity<>(HttpStatus.OK); } @@ -379,11 +347,7 @@ public ResponseEntity assignSoftwareModules(@PathVariable("distributionSet public ResponseEntity deleteAssignSoftwareModules( @PathVariable("distributionSetId") final Long distributionSetId, @PathVariable("softwareModuleId") final Long softwareModuleId) { - // check if distribution set and software module exist otherwise throw - // exception immediately - final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId); - final SoftwareModule sm = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId); - this.distributionSetManagement.unassignSoftwareModule(ds, sm); + distributionSetManagement.unassignSoftwareModule(distributionSetId, softwareModuleId); return ResponseEntity.ok().build(); } @@ -400,26 +364,18 @@ public ResponseEntity> getAssignedSoftwareModules( final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); final Sort sorting = PagingUtility.sanitizeSoftwareModuleSortParam(sortParam); final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting); - final Page softwaremodules = this.softwareManagement.findSoftwareModuleByAssignedTo(pageable, + final Page softwaremodules = softwareManagement.findSoftwareModuleByAssignedTo(pageable, foundDs); return new ResponseEntity<>(new PagedList<>(MgmtSoftwareModuleMapper.toResponse(softwaremodules.getContent()), softwaremodules.getTotalElements()), HttpStatus.OK); } private DistributionSet findDistributionSetWithExceptionIfNotFound(final Long distributionSetId) { - final DistributionSet set = this.distributionSetManagement.findDistributionSetById(distributionSetId); + final DistributionSet set = distributionSetManagement.findDistributionSetById(distributionSetId); if (set == null) { throw new EntityNotFoundException("DistributionSet with Id {" + distributionSetId + "} does not exist"); } return set; } - - private SoftwareModule findSoftwareModuleWithExceptionIfNotFound(final Long softwareModuleId) { - final SoftwareModule sm = this.softwareManagement.findSoftwareModuleById(softwareModuleId); - if (sm == null) { - throw new EntityNotFoundException("SoftwareModule with Id {" + softwareModuleId + "} does not exist"); - } - return sm; - } } 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 18ec162cae..9e6b19471a 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 @@ -101,7 +101,7 @@ public ResponseEntity> createDistributionSetTags( LOG.debug("creating {} ds tags", tags.size()); final List createdTags = this.tagManagement - .createDistributionSetTags(MgmtTagMapper.mapDistributionSetTagFromRequest(entityFactory, tags)); + .createDistributionSetTags(MgmtTagMapper.mapTagFromRequest(entityFactory, tags)); return new ResponseEntity<>(MgmtTagMapper.toResponseDistributionSetTag(createdTags), HttpStatus.CREATED); } @@ -110,16 +110,12 @@ public ResponseEntity> createDistributionSetTags( public ResponseEntity updateDistributionSetTag( @PathVariable("distributionsetTagId") final Long distributionsetTagId, @RequestBody final MgmtTagRequestBodyPut restDSTagRest) { - LOG.debug("update {} ds tag", restDSTagRest); - final DistributionSetTag distributionSetTag = findDistributionTagById(distributionsetTagId); - MgmtTagMapper.updateTag(restDSTagRest, distributionSetTag); - final DistributionSetTag updateDistributionSetTag = this.tagManagement - .updateDistributionSetTag(distributionSetTag); - - LOG.debug("ds tag updated"); - - return new ResponseEntity<>(MgmtTagMapper.toResponse(updateDistributionSetTag), HttpStatus.OK); + return new ResponseEntity<>( + MgmtTagMapper.toResponse(tagManagement.updateDistributionSetTag( + entityFactory.tag().update(distributionsetTagId).name(restDSTagRest.getName()) + .description(restDSTagRest.getDescription()).colour(restDSTagRest.getColour()))), + HttpStatus.OK); } @Override @@ -213,7 +209,7 @@ private DistributionSetTag findDistributionTagById(final Long distributionsetTag return tag; } - private List findDistributionSetIds( + private static List findDistributionSetIds( final List assignedDistributionSetRequestBodies) { return assignedDistributionSetRequestBodies.stream().map(request -> request.getDistributionSetId()) .collect(Collectors.toList()); 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 33b81ab736..905a38fc02 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,18 +14,17 @@ import java.util.Collection; import java.util.Collections; import java.util.List; +import java.util.Optional; import java.util.stream.Collectors; 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.softwaremoduletype.MgmtSoftwareModuleTypeAssigment; 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.builder.DistributionSetTypeCreate; import org.eclipse.hawkbit.repository.model.DistributionSetType; -import org.eclipse.hawkbit.repository.model.SoftwareModuleType; -import org.springframework.util.CollectionUtils; /** * A mapper which maps repository model to RESTful model representation and @@ -39,57 +38,32 @@ private MgmtDistributionSetTypeMapper() { } - static List smFromRequest(final EntityFactory entityFactory, - final SoftwareManagement softwareManagement, + static List smFromRequest(final EntityFactory entityFactory, final Collection smTypesRest) { if (smTypesRest == null) { return Collections.emptyList(); } - return smTypesRest.stream().map(smRest -> fromRequest(entityFactory, softwareManagement, smRest)) - .collect(Collectors.toList()); + return smTypesRest.stream().map(smRest -> fromRequest(entityFactory, smRest)).collect(Collectors.toList()); } - static DistributionSetType fromRequest(final EntityFactory entityFactory, - final SoftwareManagement softwareManagement, final MgmtDistributionSetTypeRequestBodyPost smsRest) { - - final DistributionSetType result = entityFactory.generateDistributionSetType(smsRest.getKey(), - smsRest.getName(), smsRest.getDescription()); - - addMandatoryModules(softwareManagement, smsRest, result); - addOptionalModules(softwareManagement, smsRest, result); - - return result; + static DistributionSetTypeCreate fromRequest(final EntityFactory entityFactory, + final MgmtDistributionSetTypeRequestBodyPost smsRest) { + return entityFactory.distributionSetType().create().key(smsRest.getKey()).name(smsRest.getName()) + .description(smsRest.getDescription()).colour(smsRest.getColour()) + .mandatory(getMandatoryModules(smsRest)).optional(getOptionalmodules(smsRest)); } - private static void addOptionalModules(final SoftwareManagement softwareManagement, - final MgmtDistributionSetTypeRequestBodyPost smsRest, final DistributionSetType result) { - if (!CollectionUtils.isEmpty(smsRest.getOptionalmodules())) { - smsRest.getOptionalmodules().stream().map(opt -> { - final SoftwareModuleType smType = softwareManagement.findSoftwareModuleTypeById(opt.getId()); - - if (smType == null) { - throw new EntityNotFoundException("SoftwareModuleType with ID " + opt.getId() + " not found"); - } - - return smType; - }).forEach(result::addOptionalModuleType); - } + private static Collection getMandatoryModules(final MgmtDistributionSetTypeRequestBodyPost smsRest) { + return Optional.ofNullable(smsRest.getMandatorymodules()).map( + modules -> modules.stream().map(MgmtSoftwareModuleTypeAssigment::getId).collect(Collectors.toList())) + .orElse(Collections.emptyList()); } - private static void addMandatoryModules(final SoftwareManagement softwareManagement, - final MgmtDistributionSetTypeRequestBodyPost smsRest, final DistributionSetType result) { - if (!CollectionUtils.isEmpty(smsRest.getMandatorymodules())) { - smsRest.getMandatorymodules().stream().map(mand -> { - final SoftwareModuleType smType = softwareManagement.findSoftwareModuleTypeById(mand.getId()); - - if (smType == null) { - throw new EntityNotFoundException("SoftwareModuleType with ID " + mand.getId() + " not found"); - } - - return smType; - }).forEach(result::addMandatoryModuleType); - } + private static Collection getOptionalmodules(final MgmtDistributionSetTypeRequestBodyPost smsRest) { + return Optional.ofNullable(smsRest.getOptionalmodules()).map( + modules -> modules.stream().map(MgmtSoftwareModuleTypeAssigment::getId).collect(Collectors.toList())) + .orElse(Collections.emptyList()); } static List toTypesResponse(final List types) { 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 fe62ff3690..e1591b8b65 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 @@ -44,6 +44,8 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import com.google.common.collect.Lists; + /** * REST Resource handling for {@link SoftwareModule} and related * {@link Artifact} CRUD operations. @@ -110,17 +112,9 @@ public ResponseEntity updateDistributionSetType( @PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @RequestBody final MgmtDistributionSetTypeRequestBodyPut restDistributionSetType) { - final DistributionSetType type = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); - - // only description can be modified - if (restDistributionSetType.getDescription() != null) { - type.setDescription(restDistributionSetType.getDescription()); - } - - final DistributionSetType updatedDistributionSetType = distributionSetManagement - .updateDistributionSetType(type); - - return ResponseEntity.ok(toResponse(updatedDistributionSetType)); + return ResponseEntity.ok(toResponse(distributionSetManagement.updateDistributionSetType(entityFactory + .distributionSetType().update(distributionSetTypeId) + .description(restDistributionSetType.getDescription()).colour(restDistributionSetType.getColour())))); } @Override @@ -128,7 +122,7 @@ public ResponseEntity> createDistributionSetTypes( @RequestBody final List distributionSetTypes) { final List createdSoftwareModules = distributionSetManagement.createDistributionSetTypes( - MgmtDistributionSetTypeMapper.smFromRequest(entityFactory, softwareManagement, distributionSetTypes)); + MgmtDistributionSetTypeMapper.smFromRequest(entityFactory, distributionSetTypes)); return ResponseEntity.status(CREATED).body(toTypesResponse(createdSoftwareModules)); } @@ -196,17 +190,7 @@ public ResponseEntity> getOptionalModules( public ResponseEntity removeMandatoryModule( @PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) { - - final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); - final SoftwareModuleType foundSmType = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId); - - if (!foundType.containsMandatoryModuleType(foundSmType)) { - throw new EntityNotFoundException( - "Software module with given ID is not mandatory part of this distribution set type!"); - } - - foundType.removeModuleType(softwareModuleTypeId); - distributionSetManagement.updateDistributionSetType(foundType); + distributionSetManagement.unassignSoftwareModuleType(distributionSetTypeId, softwareModuleTypeId); return ResponseEntity.ok().build(); } @@ -216,28 +200,15 @@ public ResponseEntity removeOptionalModule( @PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) { - final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); - final SoftwareModuleType foundSmType = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId); - - if (!foundType.containsOptionalModuleType(foundSmType)) { - throw new EntityNotFoundException( - "Software module with given ID is not optional part of this distribution set type!"); - } - - foundType.removeModuleType(softwareModuleTypeId); - distributionSetManagement.updateDistributionSetType(foundType); - - return ResponseEntity.ok().build(); + return removeMandatoryModule(distributionSetTypeId, softwareModuleTypeId); } @Override public ResponseEntity addMandatoryModule( @PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @RequestBody final MgmtId smtId) { - final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); - final SoftwareModuleType smType = findSoftwareModuleTypeWithExceptionIfNotFound(smtId.getId()); - foundType.addMandatoryModuleType(smType); - distributionSetManagement.updateDistributionSetType(foundType); + distributionSetManagement.assignMandatorySoftwareModuleTypes(distributionSetTypeId, + Lists.newArrayList(smtId.getId())); return ResponseEntity.ok().build(); } @@ -246,11 +217,8 @@ public ResponseEntity addMandatoryModule( public ResponseEntity addOptionalModule( @PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @RequestBody final MgmtId smtId) { - final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); - final SoftwareModuleType smType = findSoftwareModuleTypeWithExceptionIfNotFound(smtId.getId()); - foundType.addOptionalModuleType(smType); - - distributionSetManagement.updateDistributionSetType(foundType); + distributionSetManagement.assignOptionalSoftwareModuleTypes(distributionSetTypeId, + Lists.newArrayList(smtId.getId())); return ResponseEntity.ok().build(); } 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 f817efa324..c7073bfd05 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 @@ -15,6 +15,7 @@ import java.util.List; import java.util.stream.Collectors; +import org.eclipse.hawkbit.mgmt.json.model.rollout.AbstractMgmtRolloutConditionsEntity; import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutCondition; import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutCondition.Condition; import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutErrorAction; @@ -28,8 +29,8 @@ 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.exception.ConstraintViolationException; -import org.eclipse.hawkbit.repository.model.Action.ActionType; +import org.eclipse.hawkbit.repository.builder.RolloutCreate; +import org.eclipse.hawkbit.repository.builder.RolloutGroupCreate; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.RolloutGroup; @@ -37,6 +38,8 @@ 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.TotalTargetCountStatus; /** @@ -91,60 +94,49 @@ static MgmtRolloutResponseBody toResponseRollout(final Rollout rollout) { return body; } - static Rollout fromRequest(final EntityFactory entityFactory, final MgmtRolloutRestRequestBody restRequest, + static RolloutCreate fromRequest(final EntityFactory entityFactory, final MgmtRolloutRestRequestBody restRequest, final DistributionSet distributionSet) { - final Rollout rollout = entityFactory.generateRollout(); - rollout.setName(restRequest.getName()); - rollout.setDescription(restRequest.getDescription()); - rollout.setDistributionSet(distributionSet); - rollout.setTargetFilterQuery(restRequest.getTargetFilterQuery()); - final ActionType convertActionType = MgmtRestModelMapper.convertActionType(restRequest.getType()); - if (convertActionType != null) { - rollout.setActionType(convertActionType); - } - if (restRequest.getForcetime() != null) { - rollout.setForcedTime(restRequest.getForcetime()); - } - return rollout; + return entityFactory.rollout().create().name(restRequest.getName()).description(restRequest.getDescription()) + .set(distributionSet).targetFilterQuery(restRequest.getTargetFilterQuery()) + .actionType(MgmtRestModelMapper.convertActionType(restRequest.getType())) + .forcedTime(restRequest.getForcetime()); } - static RolloutGroup fromRequest(final EntityFactory entityFactory, final MgmtRolloutGroup restRequest) { - final RolloutGroup group = entityFactory.generateRolloutGroup(); - group.setName(restRequest.getName()); - group.setDescription(restRequest.getDescription()); + static RolloutGroupCreate fromRequest(final EntityFactory entityFactory, final MgmtRolloutGroup restRequest) { - if (restRequest.getTargetFilterQuery() != null) { - group.setTargetFilterQuery(restRequest.getTargetFilterQuery()); - } + return entityFactory.rolloutGroup().create().name(restRequest.getName()) + .description(restRequest.getDescription()).targetFilterQuery(restRequest.getTargetFilterQuery()) + .targetPercentage(restRequest.getTargetPercentage()).conditions(fromRequest(restRequest, false)); + } + + static RolloutGroupConditions fromRequest(final AbstractMgmtRolloutConditionsEntity restRequest, + final boolean withDefaults) { + final RolloutGroupConditionBuilder conditions = new RolloutGroupConditionBuilder(); - final Float targetPercentage = restRequest.getTargetPercentage(); - if (targetPercentage == null) { - group.setTargetPercentage(100); - } else if (targetPercentage <= 0 || targetPercentage > 100) { - throw new ConstraintViolationException("Target percentage out of Range >0 - 100."); - } else { - group.setTargetPercentage(restRequest.getTargetPercentage()); + if (withDefaults) { + conditions.withDefaults(); } if (restRequest.getSuccessCondition() != null) { - group.setSuccessCondition(mapFinishCondition(restRequest.getSuccessCondition().getCondition())); - group.setSuccessConditionExp(restRequest.getSuccessCondition().getExpression()); + conditions.successCondition(mapFinishCondition(restRequest.getSuccessCondition().getCondition()), + restRequest.getSuccessCondition().getExpression()); } if (restRequest.getSuccessAction() != null) { - group.setSuccessAction(map(restRequest.getSuccessAction().getAction())); - group.setSuccessActionExp(restRequest.getSuccessAction().getExpression()); + conditions.successAction(map(restRequest.getSuccessAction().getAction()), + restRequest.getSuccessAction().getExpression()); } + if (restRequest.getErrorCondition() != null) { - group.setErrorCondition(mapErrorCondition(restRequest.getErrorCondition().getCondition())); - group.setErrorConditionExp(restRequest.getErrorCondition().getExpression()); + conditions.errorCondition(mapErrorCondition(restRequest.getErrorCondition().getCondition()), + restRequest.getErrorCondition().getExpression()); } if (restRequest.getErrorAction() != null) { - group.setErrorAction(map(restRequest.getErrorAction().getAction())); - group.setErrorActionExp(restRequest.getErrorAction().getExpression()); + conditions.errorAction(map(restRequest.getErrorAction().getAction()), + restRequest.getErrorAction().getExpression()); } - return group; + return conditions.build(); } static List toResponseRolloutGroup(final List rollouts) { 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 ea68b9753e..afc31eb814 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 @@ -24,16 +24,13 @@ import org.eclipse.hawkbit.repository.RolloutGroupManagement; import org.eclipse.hawkbit.repository.RolloutManagement; import org.eclipse.hawkbit.repository.TargetFilterQueryManagement; +import org.eclipse.hawkbit.repository.builder.RolloutCreate; +import org.eclipse.hawkbit.repository.builder.RolloutGroupCreate; +import org.eclipse.hawkbit.repository.exception.ConstraintViolationException; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; -import org.eclipse.hawkbit.repository.exception.RolloutVerificationException; 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.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.springframework.beans.factory.annotation.Autowired; @@ -110,56 +107,23 @@ public ResponseEntity create( targetFilterQueryManagement.verifyTargetFilterQuerySyntax(rolloutRequestBody.getTargetFilterQuery()); final DistributionSet distributionSet = findDistributionSetOrThrowException(rolloutRequestBody); + final RolloutGroupConditions rolloutGroupConditions = MgmtRolloutMapper.fromRequest(rolloutRequestBody, true); - // success condition - RolloutGroupSuccessCondition successCondition = null; - String successConditionExpr = null; - // success action - RolloutGroupSuccessAction successAction = null; - String successActionExpr = null; - // error condition - RolloutGroupErrorCondition errorCondition = null; - // error action - String errorConditionExpr = null; - RolloutGroupErrorAction errorAction = null; - String errorActionExpr = null; - if (rolloutRequestBody.getSuccessCondition() != null) { - successCondition = MgmtRolloutMapper - .mapFinishCondition(rolloutRequestBody.getSuccessCondition().getCondition()); - successConditionExpr = rolloutRequestBody.getSuccessCondition().getExpression(); - } - if (rolloutRequestBody.getSuccessAction() != null) { - successAction = MgmtRolloutMapper.map(rolloutRequestBody.getSuccessAction().getAction()); - successActionExpr = rolloutRequestBody.getSuccessAction().getExpression(); - } - if (rolloutRequestBody.getErrorCondition() != null) { - errorCondition = MgmtRolloutMapper.mapErrorCondition(rolloutRequestBody.getErrorCondition().getCondition()); - errorConditionExpr = rolloutRequestBody.getErrorCondition().getExpression(); - } - if (rolloutRequestBody.getErrorAction() != null) { - errorAction = MgmtRolloutMapper.map(rolloutRequestBody.getErrorAction().getAction()); - errorActionExpr = rolloutRequestBody.getErrorAction().getExpression(); - } - - final RolloutGroupConditions rolloutGroupConditions = new RolloutGroupConditionBuilder() - .successCondition(successCondition, successConditionExpr) - .successAction(successAction, successActionExpr).errorCondition(errorCondition, errorConditionExpr) - .errorAction(errorAction, errorActionExpr).build(); - - Rollout rollout = MgmtRolloutMapper.fromRequest(entityFactory, rolloutRequestBody, distributionSet); + final RolloutCreate create = MgmtRolloutMapper.fromRequest(entityFactory, rolloutRequestBody, distributionSet); + Rollout rollout; if (rolloutRequestBody.getGroups() != null) { - final List rolloutGroups = rolloutRequestBody.getGroups().stream() + final List rolloutGroups = rolloutRequestBody.getGroups().stream() .map(mgmtRolloutGroup -> MgmtRolloutMapper.fromRequest(entityFactory, mgmtRolloutGroup)) .collect(Collectors.toList()); - rollout = rolloutManagement.createRollout(rollout, rolloutGroups, rolloutGroupConditions); + rollout = rolloutManagement.createRollout(create, rolloutGroups, rolloutGroupConditions); } else if (rolloutRequestBody.getAmountGroups() != null) { - rollout = rolloutManagement.createRollout(rollout, rolloutRequestBody.getAmountGroups(), + rollout = rolloutManagement.createRollout(create, rolloutRequestBody.getAmountGroups(), rolloutGroupConditions); } else { - throw new RolloutVerificationException("Either 'amountGroups' or 'groups' must be defined in the request"); + throw new ConstraintViolationException("Either 'amountGroups' or 'groups' must be defined in the request"); } return ResponseEntity.status(HttpStatus.CREATED).body(MgmtRolloutMapper.toResponseRollout(rollout)); @@ -247,8 +211,7 @@ public ResponseEntity> getRolloutGroupTargets(@PathVariabl rolloutGroupTargets = pageTargets; } final List rest = MgmtTargetMapper.toResponse(rolloutGroupTargets.getContent()); - return new ResponseEntity<>(new PagedList(rest, rolloutGroupTargets.getTotalElements()), - HttpStatus.OK); + return new ResponseEntity<>(new PagedList<>(rest, rolloutGroupTargets.getTotalElements()), HttpStatus.OK); } private Rollout findRolloutOrThrowException(final Long rolloutId) { 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 d7f23a0191..d95a49fbb1 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 @@ -25,13 +25,11 @@ 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.ConstraintViolationException; -import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleCreate; import org.eclipse.hawkbit.repository.model.Artifact; +import org.eclipse.hawkbit.repository.model.MetaData; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; -import org.eclipse.hawkbit.repository.model.SoftwareModuleType; /** * A mapper which maps repository model to RESTful model representation and @@ -43,46 +41,30 @@ private MgmtSoftwareModuleMapper() { // Utility class } - private static SoftwareModuleType getSoftwareModuleTypeFromKeyString(final String type, - final SoftwareManagement softwareManagement) { - if (type == null) { - throw new ConstraintViolationException("type cannot be null"); - } - - final SoftwareModuleType smType = softwareManagement.findSoftwareModuleTypeByKey(type.trim()); - - if (smType == null) { - throw new EntityNotFoundException(type.trim()); - } - - return smType; + static SoftwareModuleCreate fromRequest(final EntityFactory entityFactory, + final MgmtSoftwareModuleRequestBodyPost smsRest) { + return entityFactory.softwareModule().create().type(smsRest.getType()).name(smsRest.getName()) + .version(smsRest.getVersion()).description(smsRest.getDescription()).vendor(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 EntityFactory entityFactory, - final SoftwareModule sw, final Collection metadata) { + static List fromRequestSwMetadata(final EntityFactory entityFactory, + final Collection metadata) { if (metadata == null) { return Collections.emptyList(); } - return metadata.stream().map(metadataRest -> entityFactory.generateSoftwareModuleMetadata(sw, - metadataRest.getKey(), metadataRest.getValue())).collect(Collectors.toList()); + return metadata.stream() + .map(metadataRest -> entityFactory.generateMetadata(metadataRest.getKey(), metadataRest.getValue())) + .collect(Collectors.toList()); } - static List smFromRequest(final EntityFactory entityFactory, - final Collection smsRest, final SoftwareManagement softwareManagement) { + static List smFromRequest(final EntityFactory entityFactory, + final Collection smsRest) { if (smsRest == null) { return Collections.emptyList(); } - return smsRest.stream().map(smRest -> fromRequest(entityFactory, smRest, softwareManagement)) - .collect(Collectors.toList()); + return smsRest.stream().map(smRest -> fromRequest(entityFactory, smRest)).collect(Collectors.toList()); } /** 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 972fd4863a..20f4eb41d0 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 @@ -170,8 +170,8 @@ public ResponseEntity> createSoftwareModules( @RequestBody final List softwareModules) { LOG.debug("creating {} softwareModules", softwareModules.size()); - final Collection createdSoftwareModules = softwareManagement.createSoftwareModule( - MgmtSoftwareModuleMapper.smFromRequest(entityFactory, softwareModules, softwareManagement)); + final Collection createdSoftwareModules = softwareManagement + .createSoftwareModule(MgmtSoftwareModuleMapper.smFromRequest(entityFactory, softwareModules)); LOG.debug("{} softwareModules created, return status {}", softwareModules.size(), HttpStatus.CREATED); return ResponseEntity.status(CREATED).body(toResponse(createdSoftwareModules)); @@ -182,18 +182,9 @@ public ResponseEntity updateSoftwareModule( @PathVariable("softwareModuleId") final Long softwareModuleId, @RequestBody final MgmtSoftwareModuleRequestBodyPut restSoftwareModule) { - final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null); - - // only description and vendor can be modified - if (restSoftwareModule.getDescription() != null) { - module.setDescription(restSoftwareModule.getDescription()); - } - if (restSoftwareModule.getVendor() != null) { - module.setVendor(restSoftwareModule.getVendor()); - } - - final SoftwareModule updateSoftwareModule = softwareManagement.updateSoftwareModule(module); - return ResponseEntity.ok(toResponse(updateSoftwareModule)); + return ResponseEntity.ok(toResponse( + softwareManagement.updateSoftwareModule(entityFactory.softwareModule().update(softwareModuleId) + .description(restSoftwareModule.getDescription()).vendor(restSoftwareModule.getVendor())))); } @Override @@ -238,8 +229,8 @@ public ResponseEntity> getMetadata( public ResponseEntity getMetadataValue(@PathVariable("softwareModuleId") final Long softwareModuleId, @PathVariable("metadataKey") final String metadataKey) { - final SoftwareModule sw = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null); - final SoftwareModuleMetadata findOne = softwareManagement.findSoftwareModuleMetadata(sw.getId(), metadataKey); + final SoftwareModuleMetadata findOne = softwareManagement.findSoftwareModuleMetadata(softwareModuleId, + metadataKey); return ResponseEntity.ok(toResponseSwMetadata(findOne)); } @@ -247,10 +238,8 @@ public ResponseEntity getMetadataValue(@PathVariable("softwareModu @Override 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( - entityFactory.generateSoftwareModuleMetadata(sw, metadataKey, metadata.getValue())); + final SoftwareModuleMetadata updated = softwareManagement.updateSoftwareModuleMetadata(softwareModuleId, + entityFactory.generateMetadata(metadataKey, metadata.getValue())); return ResponseEntity.ok(toResponseSwMetadata(updated)); } @@ -258,9 +247,7 @@ public ResponseEntity updateMetadata(@PathVariable("softwareModule @Override public ResponseEntity deleteMetadata(@PathVariable("softwareModuleId") final Long softwareModuleId, @PathVariable("metadataKey") final String metadataKey) { - - final SoftwareModule sw = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null); - softwareManagement.deleteSoftwareModuleMetadata(sw.getId(), metadataKey); + softwareManagement.deleteSoftwareModuleMetadata(softwareModuleId, metadataKey); return ResponseEntity.ok().build(); } @@ -270,9 +257,8 @@ public ResponseEntity> createMetadata( @PathVariable("softwareModuleId") final Long softwareModuleId, @RequestBody final List metadataRest) { - final SoftwareModule sw = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null); - final List created = softwareManagement.createSoftwareModuleMetadata( - MgmtSoftwareModuleMapper.fromRequestSwMetadata(entityFactory, sw, metadataRest)); + final List created = softwareManagement.createSoftwareModuleMetadata(softwareModuleId, + MgmtSoftwareModuleMapper.fromRequestSwMetadata(entityFactory, metadataRest)); return ResponseEntity.status(CREATED).body(toResponseSwMetadata(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 e14ed27fa2..550492c1ba 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 @@ -20,6 +20,7 @@ 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.builder.SoftwareModuleTypeCreate; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; /** @@ -34,7 +35,7 @@ private MgmtSoftwareModuleTypeMapper() { } - static List smFromRequest(final EntityFactory entityFactory, + static List smFromRequest(final EntityFactory entityFactory, final Collection smTypesRest) { if (smTypesRest == null) { return Collections.emptyList(); @@ -43,15 +44,11 @@ static List smFromRequest(final EntityFactory entityFactory, return smTypesRest.stream().map(smRest -> fromRequest(entityFactory, smRest)).collect(Collectors.toList()); } - static SoftwareModuleType fromRequest(final EntityFactory entityFactory, + static SoftwareModuleTypeCreate 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; + return entityFactory.softwareModuleType().create().key(smsRest.getKey()).name(smsRest.getName()) + .description(smsRest.getDescription()).colour(smsRest.getColour()) + .maxAssignments(smsRest.getMaxAssignments()); } static List toTypesResponse(final Collection 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 762dd7c1c4..704bf72dad 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 @@ -64,11 +64,11 @@ public ResponseEntity> getTypes( final Slice findModuleTypessAll; Long countModulesAll; if (rsqlParam != null) { - findModuleTypessAll = this.softwareManagement.findSoftwareModuleTypesAll(rsqlParam, pageable); + findModuleTypessAll = softwareManagement.findSoftwareModuleTypesAll(rsqlParam, pageable); countModulesAll = ((Page) findModuleTypessAll).getTotalElements(); } else { - findModuleTypessAll = this.softwareManagement.findSoftwareModuleTypesAll(pageable); - countModulesAll = this.softwareManagement.countSoftwareModuleTypesAll(); + findModuleTypessAll = softwareManagement.findSoftwareModuleTypesAll(pageable); + countModulesAll = softwareManagement.countSoftwareModuleTypesAll(); } final List rest = MgmtSoftwareModuleTypeMapper @@ -89,7 +89,7 @@ public ResponseEntity deleteSoftwareModuleType( @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) { final SoftwareModuleType module = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId); - this.softwareManagement.deleteSoftwareModuleType(module); + softwareManagement.deleteSoftwareModuleType(module); return new ResponseEntity<>(HttpStatus.OK); } @@ -98,14 +98,11 @@ public ResponseEntity deleteSoftwareModuleType( public ResponseEntity updateSoftwareModuleType( @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId, @RequestBody final MgmtSoftwareModuleTypeRequestBodyPut restSoftwareModuleType) { - final SoftwareModuleType type = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId); - // only description can be modified - if (restSoftwareModuleType.getDescription() != null) { - type.setDescription(restSoftwareModuleType.getDescription()); - } + final SoftwareModuleType updatedSoftwareModuleType = softwareManagement.updateSoftwareModuleType(entityFactory + .softwareModuleType().update(softwareModuleTypeId).description(restSoftwareModuleType.getDescription()) + .colour(restSoftwareModuleType.getColour())); - final SoftwareModuleType updatedSoftwareModuleType = this.softwareManagement.updateSoftwareModuleType(type); return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toResponse(updatedSoftwareModuleType), HttpStatus.OK); } @@ -113,7 +110,7 @@ public ResponseEntity updateSoftwareModuleType( public ResponseEntity> createSoftwareModuleTypes( @RequestBody final List softwareModuleTypes) { - final List createdSoftwareModules = this.softwareManagement.createSoftwareModuleType( + final List createdSoftwareModules = softwareManagement.createSoftwareModuleType( MgmtSoftwareModuleTypeMapper.smFromRequest(entityFactory, softwareModuleTypes)); return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toTypesResponse(createdSoftwareModules), @@ -121,7 +118,7 @@ public ResponseEntity> createSoftwareModuleTypes( } private SoftwareModuleType findSoftwareModuleTypeWithExceptionIfNotFound(final Long softwareModuleTypeId) { - final SoftwareModuleType module = this.softwareManagement.findSoftwareModuleTypeById(softwareModuleTypeId); + final SoftwareModuleType module = softwareManagement.findSoftwareModuleTypeById(softwareModuleTypeId); if (module == null) { throw new EntityNotFoundException( "SoftwareModuleType with Id {" + softwareModuleTypeId + "} does not exist"); 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 bac21c2a56..1c397b5d36 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 @@ -12,13 +12,16 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import java.util.ArrayList; +import java.util.Collection; import java.util.List; +import java.util.stream.Collectors; 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.builder.TagCreate; import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.repository.model.Tag; import org.eclipse.hawkbit.repository.model.TargetTag; @@ -96,24 +99,12 @@ static MgmtTag toResponse(final DistributionSetTag distributionSetTag) { return response; } - static List mapTargeTagFromRequest(final EntityFactory entityFactory, - final Iterable tags) { - final List mappedList = new ArrayList<>(); - for (final MgmtTagRequestBodyPut targetTagRest : tags) { - mappedList.add(entityFactory.generateTargetTag(targetTagRest.getName(), targetTagRest.getDescription(), - targetTagRest.getColour())); - } - return mappedList; - } - - static List mapDistributionSetTagFromRequest(final EntityFactory entityFactory, - final Iterable tags) { - final List mappedList = new ArrayList<>(); - for (final MgmtTagRequestBodyPut targetTagRest : tags) { - mappedList.add(entityFactory.generateDistributionSetTag(targetTagRest.getName(), - targetTagRest.getDescription(), targetTagRest.getColour())); - } - return mappedList; + static List mapTagFromRequest(final EntityFactory entityFactory, + final Collection tags) { + return tags.stream() + .map(tagRest -> entityFactory.tag().create().name(tagRest.getName()) + .description(tagRest.getDescription()).colour(tagRest.getColour())) + .collect(Collectors.toList()); } private static void mapTag(final MgmtTag response, final Tag tag) { @@ -121,18 +112,4 @@ private static void mapTag(final MgmtTag response, final Tag tag) { response.setTagId(tag.getId()); response.setColour(tag.getColour()); } - - static void updateTag(final MgmtTagRequestBodyPut response, final Tag tag) { - if (response.getDescription() != null) { - tag.setDescription(response.getDescription()); - } - - if (response.getColour() != null) { - tag.setColour(response.getColour()); - } - - if (response.getName() != null) { - tag.setName(response.getName()); - } - } } diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryMapper.java index b2a23e2597..8c8b4b3c75 100644 --- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryMapper.java @@ -19,6 +19,7 @@ import org.eclipse.hawkbit.mgmt.json.model.targetfilter.MgmtTargetFilterQueryRequestBody; import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetFilterQueryRestApi; import org.eclipse.hawkbit.repository.EntityFactory; +import org.eclipse.hawkbit.repository.builder.TargetFilterQueryCreate; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.springframework.util.CollectionUtils; @@ -55,7 +56,7 @@ public static List toResponse(final List getFilter(@PathVariable("filterId") Long filterId) { + public ResponseEntity getFilter(@PathVariable("filterId") final Long filterId) { final TargetFilterQuery findTarget = findFilterWithExceptionIfNotFound(filterId); // to single response include poll status final MgmtTargetFilterQuery response = MgmtTargetFilterQueryMapper.toResponse(findTarget); @@ -65,10 +61,10 @@ public ResponseEntity getFilter(@PathVariable("filterId") @Override public ResponseEntity> getFilters( - @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) int pagingOffsetParam, - @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) int pagingLimitParam, - @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) String sortParam, - @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) String rsqlParam) { + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam); final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); @@ -78,8 +74,8 @@ public ResponseEntity> getFilters( final Slice findTargetFiltersAll; final Long countTargetsAll; if (rsqlParam != null) { - final Page findFilterPage = filterManagement - .findTargetFilterQueryByFilter(pageable, rsqlParam); + final Page findFilterPage = filterManagement.findTargetFilterQueryByFilter(pageable, + rsqlParam); countTargetsAll = findFilterPage.getTotalElements(); findTargetFiltersAll = findFilterPage; } else { @@ -89,11 +85,12 @@ public ResponseEntity> getFilters( final List rest = MgmtTargetFilterQueryMapper .toResponse(findTargetFiltersAll.getContent()); - return new ResponseEntity<>(new PagedList(rest, countTargetsAll), HttpStatus.OK); + return new ResponseEntity<>(new PagedList<>(rest, countTargetsAll), HttpStatus.OK); } @Override - public ResponseEntity createFilter(@RequestBody MgmtTargetFilterQueryRequestBody filter) { + public ResponseEntity createFilter( + @RequestBody final MgmtTargetFilterQueryRequestBody filter) { final TargetFilterQuery createdTarget = filterManagement .createTargetFilterQuery(MgmtTargetFilterQueryMapper.fromRequest(entityFactory, filter)); @@ -101,65 +98,48 @@ public ResponseEntity createFilter(@RequestBody MgmtTarge } @Override - public ResponseEntity updateFilter(@PathVariable("filterId") Long filterId, - @RequestBody MgmtTargetFilterQueryRequestBody targetFilterRest) { + public ResponseEntity updateFilter(@PathVariable("filterId") final Long filterId, + @RequestBody final MgmtTargetFilterQueryRequestBody targetFilterRest) { + LOG.debug("updating target filter query {}", filterId); - final TargetFilterQuery existingFilter = findFilterWithExceptionIfNotFound(filterId); - LOG.debug("updating target filter query {}", existingFilter.getId()); - if (targetFilterRest.getName() != null) { - existingFilter.setName(targetFilterRest.getName()); - } - if (targetFilterRest.getQuery() != null) { - existingFilter.setQuery(targetFilterRest.getQuery()); - } - - final TargetFilterQuery updateFilter = filterManagement.updateTargetFilterQuery(existingFilter); + final TargetFilterQuery updateFilter = filterManagement + .updateTargetFilterQuery(entityFactory.targetFilterQuery().update(filterId) + .name(targetFilterRest.getName()).query(targetFilterRest.getQuery())); return new ResponseEntity<>(MgmtTargetFilterQueryMapper.toResponse(updateFilter), HttpStatus.OK); } @Override - public ResponseEntity deleteFilter(@PathVariable("filterId") Long filterId) { - final TargetFilterQuery filter = findFilterWithExceptionIfNotFound(filterId); - filterManagement.deleteTargetFilterQuery(filter.getId()); + public ResponseEntity deleteFilter(@PathVariable("filterId") final Long filterId) { + findFilterWithExceptionIfNotFound(filterId); + filterManagement.deleteTargetFilterQuery(filterId); LOG.debug("{} target filter query deleted, return status {}", filterId, HttpStatus.OK); return new ResponseEntity<>(HttpStatus.OK); } @Override - public ResponseEntity postAssignedDistributionSet(@PathVariable("filterId") Long filterId, - @RequestBody MgmtId dsId) { - final TargetFilterQuery filter = findFilterWithExceptionIfNotFound(filterId); + public ResponseEntity postAssignedDistributionSet( + @PathVariable("filterId") final Long filterId, @RequestBody final MgmtId dsId) { - DistributionSet distributionSet; - distributionSet = distributionSetManagement.findDistributionSetById(dsId.getId()); - if (distributionSet == null) { - throw new EntityNotFoundException("DistributionSet with Id {" + dsId + "} does not exist"); - } - - filter.setAutoAssignDistributionSet(distributionSet); - - final TargetFilterQuery updateFilter = filterManagement.updateTargetFilterQuery(filter); + final TargetFilterQuery updateFilter = filterManagement.updateTargetFilterQueryAutoAssignDS(filterId, + dsId.getId()); return new ResponseEntity<>(MgmtTargetFilterQueryMapper.toResponse(updateFilter), HttpStatus.OK); } @Override - public ResponseEntity getAssignedDistributionSet(@PathVariable("filterId") Long filterId) { + public ResponseEntity getAssignedDistributionSet( + @PathVariable("filterId") final Long filterId) { final TargetFilterQuery filter = findFilterWithExceptionIfNotFound(filterId); - DistributionSet autoAssignDistributionSet = filter.getAutoAssignDistributionSet(); - MgmtDistributionSet distributionSetRest = MgmtDistributionSetMapper.toResponse(autoAssignDistributionSet); + final DistributionSet autoAssignDistributionSet = filter.getAutoAssignDistributionSet(); + final MgmtDistributionSet distributionSetRest = MgmtDistributionSetMapper.toResponse(autoAssignDistributionSet); final HttpStatus retStatus = distributionSetRest == null ? HttpStatus.NO_CONTENT : HttpStatus.OK; return new ResponseEntity<>(distributionSetRest, retStatus); } @Override - public ResponseEntity deleteAssignedDistributionSet(@PathVariable("filterId") Long filterId) { - final TargetFilterQuery filter = findFilterWithExceptionIfNotFound(filterId); - - filter.setAutoAssignDistributionSet(null); - - filterManagement.updateTargetFilterQuery(filter); + public ResponseEntity deleteAssignedDistributionSet(@PathVariable("filterId") final Long filterId) { + filterManagement.updateTargetFilterQueryAutoAssignDS(filterId, null); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } 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 014d0e9e3a..11f99ae75a 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 @@ -28,6 +28,7 @@ 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.builder.TargetCreate; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.ActionStatus; import org.eclipse.hawkbit.repository.model.PollStatus; @@ -171,7 +172,7 @@ public static MgmtTarget toResponse(final Target target) { return targetRest; } - static List fromRequest(final EntityFactory entityFactory, + static List fromRequest(final EntityFactory entityFactory, final Collection targetsRest) { if (targetsRest == null) { return Collections.emptyList(); @@ -181,13 +182,10 @@ static List fromRequest(final EntityFactory entityFactory, .collect(Collectors.toList()); } - static Target fromRequest(final EntityFactory entityFactory, final MgmtTargetRequestBody targetRest) { - final Target target = entityFactory.generateTarget(targetRest.getControllerId(), targetRest.getSecurityToken()); - target.setDescription(targetRest.getDescription()); - target.setName(targetRest.getName()); - target.getTargetInfo().setAddress(targetRest.getAddress()); - - return target; + static TargetCreate fromRequest(final EntityFactory entityFactory, final MgmtTargetRequestBody targetRest) { + return entityFactory.target().create().controllerId(targetRest.getControllerId()).name(targetRest.getName()) + .description(targetRest.getDescription()).securityToken(targetRest.getSecurityToken()) + .address(targetRest.getAddress()); } static List toActionStatusRestResponse(final Collection actionStatus) { 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 d0d72be403..5a1e9471d6 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 @@ -52,6 +52,8 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import com.google.common.collect.Lists; + /** * REST Resource handling target CRUD operations. */ @@ -103,7 +105,7 @@ public ResponseEntity> getTargets( } final List rest = MgmtTargetMapper.toResponse(findTargetsAll.getContent()); - return new ResponseEntity<>(new PagedList(rest, countTargetsAll), HttpStatus.OK); + return new ResponseEntity<>(new PagedList<>(rest, countTargetsAll), HttpStatus.OK); } @Override @@ -118,22 +120,10 @@ public ResponseEntity> createTargets(@RequestBody final List updateTarget(@PathVariable("controllerId") final String controllerId, @RequestBody final MgmtTargetRequestBody targetRest) { - final Target existingTarget = findTargetWithExceptionIfNotFound(controllerId); - LOG.debug("updating target {}", existingTarget.getId()); - if (targetRest.getDescription() != null) { - existingTarget.setDescription(targetRest.getDescription()); - } - if (targetRest.getName() != null) { - existingTarget.setName(targetRest.getName()); - } - if (targetRest.getAddress() != null) { - existingTarget.getTargetInfo().setAddress(targetRest.getAddress()); - } - if (targetRest.getSecurityToken() != null) { - existingTarget.setSecurityToken(targetRest.getSecurityToken()); - } - final Target updateTarget = this.targetManagement.updateTarget(existingTarget); + final Target updateTarget = this.targetManagement.updateTarget(entityFactory.target().update(controllerId) + .name(targetRest.getName()).description(targetRest.getDescription()).address(targetRest.getAddress()) + .securityToken(targetRest.getSecurityToken())); return new ResponseEntity<>(MgmtTargetMapper.toResponse(updateTarget), HttpStatus.OK); } @@ -291,8 +281,8 @@ public ResponseEntity postAssignedDistributionSet(@PathVariable("controlle final ActionType type = (dsId.getType() != null) ? MgmtRestModelMapper.convertActionType(dsId.getType()) : ActionType.FORCED; final Iterator changed = this.deploymentManagement - .assignDistributionSet(dsId.getId(), type, dsId.getForcetime(), controllerId).getAssignedEntity() - .iterator(); + .assignDistributionSet(dsId.getId(), type, dsId.getForcetime(), Lists.newArrayList(controllerId)) + .getAssignedEntity().iterator(); if (changed.hasNext()) { return new ResponseEntity<>(HttpStatus.OK); } 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 c765c18cda..23fd45c9f5 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 @@ -97,7 +97,7 @@ public ResponseEntity getTargetTag(@PathVariable("targetTagId") final L public ResponseEntity> createTargetTags(@RequestBody final List tags) { LOG.debug("creating {} target tags", tags.size()); final List createdTargetTags = this.tagManagement - .createTargetTags(MgmtTagMapper.mapTargeTagFromRequest(entityFactory, tags)); + .createTargetTags(MgmtTagMapper.mapTagFromRequest(entityFactory, tags)); return new ResponseEntity<>(MgmtTagMapper.toResponse(createdTargetTags), HttpStatus.CREATED); } @@ -106,9 +106,9 @@ public ResponseEntity updateTagretTag(@PathVariable("targetTagId") fina @RequestBody final MgmtTagRequestBodyPut restTargetTagRest) { LOG.debug("update {} target tag", restTargetTagRest); - final TargetTag targetTag = findTargetTagById(targetTagId); - MgmtTagMapper.updateTag(restTargetTagRest, targetTag); - final TargetTag updateTargetTag = this.tagManagement.updateTargetTag(targetTag); + final TargetTag updateTargetTag = tagManagement + .updateTargetTag(entityFactory.tag().update(targetTagId).name(restTargetTagRest.getName()) + .description(restTargetTagRest.getDescription()).colour(restTargetTagRest.getColour())); LOG.debug("target tag updated"); 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 240fdd1531..e07db90e48 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 @@ -22,7 +22,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.ArrayList; -import java.util.HashSet; +import java.util.Collection; +import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; @@ -30,8 +31,11 @@ import org.apache.commons.lang3.RandomStringUtils; import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; -import org.eclipse.hawkbit.repository.model.*; 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.SoftwareModule; +import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.test.util.TestdataFactory; import org.eclipse.hawkbit.repository.test.util.WithUser; import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest; @@ -46,6 +50,7 @@ import org.springframework.test.web.servlet.MvcResult; import com.google.common.collect.Lists; +import com.google.common.collect.Sets; import com.jayway.jsonpath.JsonPath; import ru.yandex.qatools.allure.annotations.Features; @@ -72,8 +77,7 @@ public void deleteFailureWhenDistributionSetInUse() throws Exception { // create DisSet 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); + final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); smIDs.add(sm.getId()); final JSONArray smList = new JSONArray(); for (final Long smID : smIDs) { @@ -88,10 +92,10 @@ public void deleteFailureWhenDistributionSetInUse() throws Exception { final String[] knownTargetIds = new String[] { "1", "2" }; final JSONArray list = new JSONArray(); for (final String targetId : knownTargetIds) { - targetManagement.createTarget(entityFactory.generateTarget(targetId)); + testdataFactory.createTarget(targetId); list.put(new JSONObject().put("id", Long.valueOf(targetId))); } - deploymentManagement.assignDistributionSet(disSet.getId(), knownTargetIds[0]); + assignDistributionSet(disSet.getId(), knownTargetIds[0]); mvc.perform( post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedTargets") .contentType(MediaType.APPLICATION_JSON).content(list.toString())) @@ -104,8 +108,8 @@ public void deleteFailureWhenDistributionSetInUse() throws Exception { // to the target. mvc.perform(delete(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM/" + smIDs.get(0)).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) - .andExpect(status().isLocked()) - .andExpect(jsonPath("$.errorCode", equalTo("hawkbit.server.error.entitiylocked"))); + .andExpect(status().isForbidden()) + .andExpect(jsonPath("$.errorCode", equalTo("hawkbit.server.error.entityreadonly"))); } @Test @@ -115,8 +119,7 @@ public void assignmentFailureWhenAssigningToUsedDistributionSet() throws Excepti // create DisSet final DistributionSet disSet = testdataFactory.createDistributionSetWithNoSoftwareModules("Mars", "686,980"); final List smIDs = new ArrayList<>(); - SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "Phobos", "0,3189", null, null); - sm = softwareManagement.createSoftwareModule(sm); + final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); smIDs.add(sm.getId()); final JSONArray smList = new JSONArray(); for (final Long smID : smIDs) { @@ -131,11 +134,11 @@ public void assignmentFailureWhenAssigningToUsedDistributionSet() throws Excepti final String[] knownTargetIds = new String[] { "1", "2" }; final JSONArray list = new JSONArray(); for (final String targetId : knownTargetIds) { - targetManagement.createTarget(entityFactory.generateTarget(targetId)); + testdataFactory.createTarget(targetId); list.put(new JSONObject().put("id", Long.valueOf(targetId))); } // assign DisSet to target and test assignment - deploymentManagement.assignDistributionSet(disSet.getId(), knownTargetIds[0]); + assignDistributionSet(disSet.getId(), knownTargetIds[0]); mvc.perform( post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedTargets") .contentType(MediaType.APPLICATION_JSON).content(list.toString())) @@ -145,19 +148,14 @@ public void assignmentFailureWhenAssigningToUsedDistributionSet() throws Excepti .andExpect(jsonPath("$.total", equalTo(knownTargetIds.length))); // Create another SM and post assignment - final List smID2s = new ArrayList<>(); - SoftwareModule sm2 = entityFactory.generateSoftwareModule(appType, "Deimos", "1,262", null, null); - sm2 = softwareManagement.createSoftwareModule(sm2); - smID2s.add(sm2.getId()); + final SoftwareModule sm2 = testdataFactory.createSoftwareModuleApp(); final JSONArray smList2 = new JSONArray(); - for (final Long smID : smID2s) { - smList2.put(new JSONObject().put("id", Long.valueOf(smID))); - } + smList2.put(new JSONObject().put("id", sm2.getId())); mvc.perform(post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM") .contentType(MediaType.APPLICATION_JSON).content(smList2.toString())) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isLocked()) - .andExpect(jsonPath("$.errorCode", equalTo("hawkbit.server.error.entitiylocked"))); + .andDo(MockMvcResultPrinter.print()).andExpect(status().isForbidden()) + .andExpect(jsonPath("$.errorCode", equalTo("hawkbit.server.error.entityreadonly"))); } @Test @@ -171,16 +169,8 @@ public void assignSoftwaremoduleToDistributionSet() throws Exception { .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("$.size", equalTo(disSet.getModules().size()))); // create Software Modules - 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 = entityFactory.generateSoftwareModule(appType, "Ganymed", "7,155", null, null); - sm2 = softwareManagement.createSoftwareModule(sm2); - smIDs.add(sm2.getId()); - SoftwareModule sm3 = entityFactory.generateSoftwareModule(runtimeType, "Kallisto", "16,689", null, null); - sm3 = softwareManagement.createSoftwareModule(sm3); - smIDs.add(sm3.getId()); + final List smIDs = Lists.newArrayList(testdataFactory.createSoftwareModuleOs().getId(), + testdataFactory.createSoftwareModuleApp().getId()); final JSONArray list = new JSONArray(); for (final Long smID : smIDs) { list.put(new JSONObject().put("id", Long.valueOf(smID))); @@ -227,11 +217,11 @@ public void assignMultipleTargetsToDistributionSet() throws Exception { final String[] knownTargetIds = new String[] { "1", "2", "3", "4", "5" }; final JSONArray list = new JSONArray(); for (final String targetId : knownTargetIds) { - targetManagement.createTarget(entityFactory.generateTarget(targetId)); + testdataFactory.createTarget(targetId); list.put(new JSONObject().put("id", Long.valueOf(targetId))); } // assign already one target to DS - deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetIds[0]); + assignDistributionSet(createdDs.getId(), knownTargetIds[0]); mvc.perform(post( MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets") @@ -251,8 +241,8 @@ public void getAssignedTargetsOfDistributionSet() throws Exception { final String knownTargetId = "knownTargetId1"; final Set createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1); final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next(); - targetManagement.createTarget(entityFactory.generateTarget(knownTargetId)); - deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetId); + testdataFactory.createTarget(knownTargetId); + assignDistributionSet(createdDs.getId(), knownTargetId); mvc.perform(get( MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets")) @@ -278,15 +268,15 @@ public void getInstalledTargetsOfDistributionSet() throws Exception { final String knownTargetId = "knownTargetId1"; final Set createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1); final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next(); - final Target createTarget = targetManagement.createTarget(entityFactory.generateTarget(knownTargetId)); + final Target createTarget = testdataFactory.createTarget(knownTargetId); // create some dummy targets which are not assigned or installed - targetManagement.createTarget(entityFactory.generateTarget("dummy1")); - targetManagement.createTarget(entityFactory.generateTarget("dummy2")); + testdataFactory.createTarget("dummy1"); + testdataFactory.createTarget("dummy2"); // assign knownTargetId to distribution set - deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetId); + assignDistributionSet(createdDs.getId(), knownTargetId); // make it in install state testdataFactory.sendUpdateActionStatusToTargets(Lists.newArrayList(createTarget), Status.FINISHED, - "some message"); + Collections.singletonList("some message")); mvc.perform(get( MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/installedTargets")) @@ -302,11 +292,16 @@ public void getAutoAssignTargetFiltersOfDistributionSet() throws Exception { final Set createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1); final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next(); - targetFilterQueryManagement - .createTargetFilterQuery(entityFactory.generateTargetFilterQuery(knownFilterName, "x==y", createdDs)); + targetFilterQueryManagement.updateTargetFilterQueryAutoAssignDS( + targetFilterQueryManagement.createTargetFilterQuery( + entityFactory.targetFilterQuery().create().name(knownFilterName).query("x==y")).getId(), + createdDs.getId()); + // create some dummy target filter queries - targetFilterQueryManagement.createTargetFilterQuery(entityFactory.generateTargetFilterQuery("b", "x==y")); - targetFilterQueryManagement.createTargetFilterQuery(entityFactory.generateTargetFilterQuery("c", "x==y")); + targetFilterQueryManagement + .createTargetFilterQuery(entityFactory.targetFilterQuery().create().name("b").query("x==y")); + targetFilterQueryManagement + .createTargetFilterQuery(entityFactory.targetFilterQuery().create().name("c").query("x==y")); mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/autoAssignTargetFilters")).andExpect(status().isOk()).andExpect(jsonPath("$.size", equalTo(1))) @@ -334,14 +329,7 @@ public void getMultipleAutoAssignTargetFiltersOfDistributionSet() throws Excepti final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next(); final String query = "name==" + filterNamePrefix + "*"; - // create target filter queries that should be found - targetFilterQueryManagement.createTargetFilterQuery( - entityFactory.generateTargetFilterQuery(filterNamePrefix + "1", "x==y", createdDs)); - targetFilterQueryManagement.createTargetFilterQuery( - entityFactory.generateTargetFilterQuery(filterNamePrefix + "2", "x==z", createdDs)); - // create some dummy target filter queries - targetFilterQueryManagement.createTargetFilterQuery(entityFactory.generateTargetFilterQuery("b", "x==y")); - targetFilterQueryManagement.createTargetFilterQuery(entityFactory.generateTargetFilterQuery("c", "x==y")); + prepareTestFilters(filterNamePrefix, createdDs); mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/autoAssignTargetFilters").param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, query)) @@ -358,20 +346,32 @@ public void getEmptyAutoAssignTargetFiltersOfDistributionSet() throws Exception final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next(); final String query = "name==doesNotExist"; - // create target filter queries that should be found - targetFilterQueryManagement.createTargetFilterQuery( - entityFactory.generateTargetFilterQuery(filterNamePrefix + "1", "x==y", createdDs)); - targetFilterQueryManagement.createTargetFilterQuery( - entityFactory.generateTargetFilterQuery(filterNamePrefix + "2", "x==z", createdDs)); - // create some dummy target filter queries - targetFilterQueryManagement.createTargetFilterQuery(entityFactory.generateTargetFilterQuery("b", "x==y")); - targetFilterQueryManagement.createTargetFilterQuery(entityFactory.generateTargetFilterQuery("c", "x==y")); + prepareTestFilters(filterNamePrefix, createdDs); mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/autoAssignTargetFilters").param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, query)) .andExpect(status().isOk()).andExpect(jsonPath("$.size", equalTo(0))); } + private void prepareTestFilters(final String filterNamePrefix, final DistributionSet createdDs) { + // create target filter queries that should be found + targetFilterQueryManagement + .updateTargetFilterQueryAutoAssignDS(targetFilterQueryManagement + .createTargetFilterQuery( + entityFactory.targetFilterQuery().create().name(filterNamePrefix + "1").query("x==y")) + .getId(), createdDs.getId()); + targetFilterQueryManagement + .updateTargetFilterQueryAutoAssignDS(targetFilterQueryManagement + .createTargetFilterQuery( + entityFactory.targetFilterQuery().create().name(filterNamePrefix + "2").query("x==y")) + .getId(), createdDs.getId()); + // create some dummy target filter queries + targetFilterQueryManagement.createTargetFilterQuery( + entityFactory.targetFilterQuery().create().name(filterNamePrefix + "b").query("x==y")); + targetFilterQueryManagement.createTargetFilterQuery( + entityFactory.targetFilterQuery().create().name(filterNamePrefix + "c").query("x==y")); + } + @Test @Description("Ensures that DS in repository are listed with proper paging properties.") public void getDistributionSetsWithoutAddtionalRequestParameters() throws Exception { @@ -423,11 +423,8 @@ public void getDistributionSets() throws Exception { .hasSize(0); DistributionSet set = testdataFactory.createDistributionSet("one"); - set.setRequiredMigrationStep(set.isRequiredMigrationStep()); - set = distributionSetManagement.updateDistributionSet(set); - - set.setVersion("anotherVersion"); - set = distributionSetManagement.updateDistributionSet(set); + set = distributionSetManagement.updateDistributionSet(entityFactory.distributionSet().update(set.getId()) + .version("anotherVersion").requiredMigrationStep(true)); // load also lazy stuff set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()); @@ -443,7 +440,7 @@ public void getDistributionSets() throws Exception { equalTo("http://localhost/rest/v1/distributionsets/" + set.getId()))) .andExpect(jsonPath("$.content.[0].id", equalTo(set.getId().intValue()))) .andExpect(jsonPath("$.content.[0].name", equalTo(set.getName()))) - .andExpect(jsonPath("$.content.[0].requiredMigrationStep", equalTo(set.isRequiredMigrationStep()))) + .andExpect(jsonPath("$.content.[0].requiredMigrationStep", equalTo(Boolean.TRUE))) .andExpect(jsonPath("$.content.[0].description", equalTo(set.getDescription()))) .andExpect(jsonPath("$.content.[0].type", equalTo(set.getType().getKey()))) .andExpect(jsonPath("$.content.[0].createdBy", equalTo(set.getCreatedBy()))) @@ -457,7 +454,7 @@ public void getDistributionSets() throws Exception { .andExpect(jsonPath("$.content.[0].modules.[?(@.type==" + appType.getKey() + ")].id", contains(set.findFirstModuleByType(appType).getId().intValue()))) .andExpect(jsonPath("$.content.[0].modules.[?(@.type==" + osType.getKey() + ")].id", - contains(set.findFirstModuleByType(osType).getId().intValue()))); + contains(getOsModule(set).intValue()))); } @Test @@ -488,7 +485,7 @@ public void getDistributionSet() throws Exception { .andExpect(jsonPath("$.modules.[?(@.type==" + appType.getKey() + ")].id", contains(set.findFirstModuleByType(appType).getId().intValue()))) .andExpect(jsonPath("$.modules.[?(@.type==" + osType.getKey() + ")].id", - contains(set.findFirstModuleByType(osType).getId().intValue()))); + contains(getOsModule(set).intValue()))); } @@ -508,13 +505,9 @@ public void createDistributionSets() throws JSONException, Exception { 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); + Lists.newArrayList(os, jvm, ah), true); - final List sets = new ArrayList<>(); - sets.add(one); - sets.add(two); - sets.add(three); + final List sets = Lists.newArrayList(one, two, three); final long current = System.currentTimeMillis(); @@ -640,8 +633,8 @@ public void deleteAssignedDistributionSet() throws Exception { .hasSize(0); final DistributionSet set = testdataFactory.createDistributionSet("one"); - targetManagement.createTarget(entityFactory.generateTarget("test")); - deploymentManagement.assignDistributionSet(set.getId(), "test"); + testdataFactory.createTarget("test"); + assignDistributionSet(set.getId(), "test"); assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)) .hasSize(1); @@ -670,12 +663,7 @@ public void updateDistributionSet() throws Exception { assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)) .hasSize(1); - final DistributionSet update = entityFactory.generateDistributionSet(); - update.setVersion("anotherVersion"); - update.setName(null); - update.setType(standardDsType); - - mvc.perform(put("/rest/v1/distributionsets/{dsId}", set.getId()).content(JsonBuilder.distributionSet(update)) + mvc.perform(put("/rest/v1/distributionsets/{dsId}", set.getId()).content("{\"version\":\"anotherVersion\"}") .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); @@ -709,8 +697,7 @@ public void invalidRequestsOnDistributionSetsResource() throws Exception { .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isBadRequest()); - final DistributionSet missingName = testdataFactory.generateDistributionSet("missingName"); - missingName.setName(null); + final DistributionSet missingName = entityFactory.distributionSet().create().build(); mvc.perform( post("/rest/v1/distributionsets").content(JsonBuilder.distributionSets(Lists.newArrayList(missingName))) .contentType(MediaType.APPLICATION_JSON)) @@ -762,8 +749,10 @@ public void createMetadata() throws Exception { .andExpect(jsonPath("[1]key", equalTo(knownKey2))) .andExpect(jsonPath("[1]value", equalTo(knownValue2))); - final DistributionSetMetadata metaKey1 = distributionSetManagement.findOne(testDS, knownKey1); - final DistributionSetMetadata metaKey2 = distributionSetManagement.findOne(testDS, knownKey2); + final DistributionSetMetadata metaKey1 = distributionSetManagement.findDistributionSetMetadata(testDS.getId(), + knownKey1); + final DistributionSetMetadata metaKey2 = distributionSetManagement.findDistributionSetMetadata(testDS.getId(), + knownKey2); assertThat(metaKey1.getValue()).isEqualTo(knownValue1); assertThat(metaKey2.getValue()).isEqualTo(knownValue2); @@ -778,8 +767,7 @@ public void updateMetadata() throws Exception { final String updateValue = "valueForUpdate"; final DistributionSet testDS = testdataFactory.createDistributionSet("one"); - distributionSetManagement.createDistributionSetMetadata( - entityFactory.generateDistributionSetMetadata(testDS, knownKey, knownValue)); + createDistributionSetMetadata(testDS.getId(), entityFactory.generateMetadata(knownKey, knownValue)); final JSONObject jsonObject = new JSONObject().put("key", knownKey).put("value", updateValue); @@ -789,7 +777,8 @@ public void updateMetadata() throws Exception { .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("key", equalTo(knownKey))).andExpect(jsonPath("value", equalTo(updateValue))); - final DistributionSetMetadata assertDS = distributionSetManagement.findOne(testDS, knownKey); + final DistributionSetMetadata assertDS = distributionSetManagement.findDistributionSetMetadata(testDS.getId(), + knownKey); assertThat(assertDS.getValue()).isEqualTo(updateValue); } @@ -802,14 +791,13 @@ public void deleteMetadata() throws Exception { final String knownValue = "knownValue"; final DistributionSet testDS = testdataFactory.createDistributionSet("one"); - distributionSetManagement.createDistributionSetMetadata( - entityFactory.generateDistributionSetMetadata(testDS, knownKey, knownValue)); + createDistributionSetMetadata(testDS.getId(), entityFactory.generateMetadata(knownKey, knownValue)); mvc.perform(delete("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); try { - distributionSetManagement.findOne(testDS, knownKey); + distributionSetManagement.findDistributionSetMetadata(testDS.getId(), knownKey); fail("expected EntityNotFoundException but didn't throw"); } catch (final EntityNotFoundException e) { // ok as expected @@ -823,8 +811,7 @@ public void getSingleMetadata() throws Exception { final String knownKey = "knownKey"; final String knownValue = "knownValue"; final DistributionSet testDS = testdataFactory.createDistributionSet("one"); - distributionSetManagement.createDistributionSetMetadata( - entityFactory.generateDistributionSetMetadata(testDS, knownKey, knownValue)); + createDistributionSetMetadata(testDS.getId(), entityFactory.generateMetadata(knownKey, knownValue)); mvc.perform(get("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) @@ -842,9 +829,8 @@ public void getPagedListofMetadata() throws Exception { final String knownValuePrefix = "knownValue"; final DistributionSet testDS = testdataFactory.createDistributionSet("one"); for (int index = 0; index < totalMetadata; index++) { - distributionSetManagement.createDistributionSetMetadata(entityFactory.generateDistributionSetMetadata( - distributionSetManagement.findDistributionSetById(testDS.getId()), knownKeyPrefix + index, - knownValuePrefix + index)); + createDistributionSetMetadata(testDS.getId(), + entityFactory.generateMetadata(knownKeyPrefix + index, knownValuePrefix + index)); } mvc.perform(get("/rest/v1/distributionsets/{dsId}/metadata?offset=" + offsetParam + "&limit=" + limitParam, @@ -878,8 +864,8 @@ public void searchDistributionSetRsql() throws Exception { public void filterDistributionSetComplete() throws Exception { final int amount = 10; testdataFactory.createDistributionSets(amount); - distributionSetManagement.createDistributionSet(entityFactory.generateDistributionSet("incomplete", "2", - "incomplete", distributionSetManagement.findDistributionSetTypeByKey("os"), null)); + distributionSetManagement.createDistributionSet( + entityFactory.distributionSet().create().name("incomplete").version("2").type("os")); final String rsqlFindLikeDs1OrDs2 = "complete==" + Boolean.TRUE; @@ -895,21 +881,18 @@ public void searchDistributionSetAssignedTargetsRsql() throws Exception { final Set createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1); final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next(); // prepare targets - final String[] knownTargetIds = new String[] { "1", "2", "3", "4", "5" }; - final JSONArray list = new JSONArray(); - for (final String targetId : knownTargetIds) { - targetManagement.createTarget(entityFactory.generateTarget(targetId)); - list.put(new JSONObject().put("id", Long.valueOf(targetId))); - } + final Collection knownTargetIds = Lists.newArrayList("1", "2", "3", "4", "5"); + + knownTargetIds.forEach(controllerId -> targetManagement + .createTarget(entityFactory.target().create().controllerId(controllerId))); // assign already one target to DS - deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetIds[0]); + assignDistributionSet(createdDs.getId(), knownTargetIds.iterator().next()); final String rsqlFindTargetId1 = "controllerId==1"; mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() - + "/assignedTargets?q=" + rsqlFindTargetId1).contentType(MediaType.APPLICATION_JSON) - .content(list.toString())) + + "/assignedTargets?q=" + rsqlFindTargetId1).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andExpect(jsonPath("total", equalTo(1))) .andExpect(jsonPath("size", equalTo(1))).andExpect(jsonPath("content[0].controllerId", equalTo("1"))); } @@ -922,9 +905,8 @@ public void searchDistributionSetMetadataRsql() throws Exception { final String knownValuePrefix = "knownValue"; final DistributionSet testDS = testdataFactory.createDistributionSet("one"); for (int index = 0; index < totalMetadata; index++) { - distributionSetManagement.createDistributionSetMetadata(entityFactory.generateDistributionSetMetadata( - distributionSetManagement.findDistributionSetById(testDS.getId()), knownKeyPrefix + index, - knownValuePrefix + index)); + createDistributionSetMetadata(testDS.getId(), + entityFactory.generateMetadata(knownKeyPrefix + index, knownValuePrefix + index)); } final String rsqlSearchValue1 = "value==knownValue1"; @@ -937,7 +919,7 @@ public void searchDistributionSetMetadataRsql() throws Exception { private Set createDistributionSetsAlphabetical(final int amount) { char character = 'a'; - final Set created = new HashSet<>(); + final Set created = Sets.newHashSetWithExpectedSize(amount); for (int index = 0; index < amount; index++) { final String str = String.valueOf(character); created.add(testdataFactory.createDistributionSet(str)); 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 9a47d8483e..35257edea5 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 @@ -21,13 +21,13 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import java.util.ArrayList; +import java.io.UnsupportedEncodingException; +import java.util.Collections; import java.util.List; import org.apache.commons.lang3.RandomStringUtils; import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; 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.test.util.WithUser; import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest; @@ -44,6 +44,7 @@ import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; +import ru.yandex.qatools.allure.annotations.Step; import ru.yandex.qatools.allure.annotations.Stories; /** @@ -59,10 +60,11 @@ 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( - entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")); - testType.setDescription("Desc1234"); - testType = distributionSetManagement.updateDistributionSetType(testType); + DistributionSetType testType = distributionSetManagement + .createDistributionSetType(entityFactory.distributionSetType().create().key("test123") + .name("TestName123").description("Desc123").colour("col12")); + testType = distributionSetManagement.updateDistributionSetType( + entityFactory.distributionSetType().update(testType.getId()).description("Desc1234")); // 4 types overall (2 hawkbit tenant default, 1 test default and 1 // generated in this test) @@ -99,10 +101,11 @@ public void getDistributionSetTypes() throws Exception { @Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests with sorting by KEY.") public void getDistributionSetTypesSortedByKey() throws Exception { - DistributionSetType testType = distributionSetManagement.createDistributionSetType( - entityFactory.generateDistributionSetType("zzzzz", "TestName123", "Desc123")); - testType.setDescription("Desc1234"); - testType = distributionSetManagement.updateDistributionSetType(testType); + DistributionSetType testType = distributionSetManagement + .createDistributionSetType(entityFactory.distributionSetType().create().key("zzzzz").name("TestName123") + .description("Desc123").colour("col12")); + testType = distributionSetManagement.updateDistributionSetType( + entityFactory.distributionSetType().update(testType.getId()).description("Desc1234")); // descending mvc.perform(get("/rest/v1/distributionsettypes").accept(MediaType.APPLICATION_JSON) @@ -138,35 +141,18 @@ public void getDistributionSetTypesSortedByKey() throws Exception { @Description("Checks the correct behaviour of /rest/v1/distributionsettypes POST requests.") public void createDistributionSetTypes() throws JSONException, Exception { - assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES); + final List types = createTestDistributionSetTestTypes(); - final List types = new ArrayList<>(); - 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 = runPostDistributionSetType(types); - final MvcResult mvcResult = mvc - .perform(post("/rest/v1/distributionsettypes/").content(JsonBuilder.distributionSetTypes(types)) - .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("[0].name", equalTo("TestName1"))).andExpect(jsonPath("[0].key", equalTo("test1"))) - .andExpect(jsonPath("[0].description", equalTo("Desc1"))) - .andExpect(jsonPath("[0].createdBy", equalTo("uploadTester"))) - .andExpect(jsonPath("[1].name", equalTo("TestName2"))).andExpect(jsonPath("[1].key", equalTo("test2"))) - .andExpect(jsonPath("[1].description", equalTo("Desc2"))) - .andExpect(jsonPath("[1].createdBy", equalTo("uploadTester"))) - .andExpect(jsonPath("[2].name", equalTo("TestName3"))).andExpect(jsonPath("[2].key", equalTo("test3"))) - .andExpect(jsonPath("[2].description", equalTo("Desc3"))) - .andExpect(jsonPath("[2].createdBy", equalTo("uploadTester"))) - .andExpect(jsonPath("[2].createdAt", not(equalTo(0)))).andReturn(); + verifyCreatedDistributionSetTypes(mvcResult); + } - final DistributionSetType created1 = distributionSetManagement.findDistributionSetTypeByKey("test1"); - final DistributionSetType created2 = distributionSetManagement.findDistributionSetTypeByKey("test2"); - final DistributionSetType created3 = distributionSetManagement.findDistributionSetTypeByKey("test3"); + @Step + private void verifyCreatedDistributionSetTypes(final MvcResult mvcResult) throws UnsupportedEncodingException { + final DistributionSetType created1 = distributionSetManagement.findDistributionSetTypeByKey("testKey1"); + final DistributionSetType created2 = distributionSetManagement.findDistributionSetTypeByKey("testKey2"); + final DistributionSetType created3 = distributionSetManagement.findDistributionSetTypeByKey("testKey3"); assertThat(created1.getMandatoryModuleTypes()).containsOnly(osType); assertThat(created1.getOptionalModuleTypes()).containsOnly(runtimeType); @@ -206,12 +192,50 @@ public void createDistributionSetTypes() throws JSONException, Exception { assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(6); } + @Step + private MvcResult runPostDistributionSetType(final List types) throws Exception { + return mvc + .perform(post("/rest/v1/distributionsettypes/").content(JsonBuilder.distributionSetTypes(types)) + .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) + .andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("[0].name", equalTo("TestName1"))) + .andExpect(jsonPath("[0].key", equalTo("testKey1"))) + .andExpect(jsonPath("[0].description", equalTo("Desc1"))) + .andExpect(jsonPath("[0].createdBy", equalTo("uploadTester"))) + .andExpect(jsonPath("[1].name", equalTo("TestName2"))) + .andExpect(jsonPath("[1].key", equalTo("testKey2"))) + .andExpect(jsonPath("[1].description", equalTo("Desc2"))) + .andExpect(jsonPath("[1].createdBy", equalTo("uploadTester"))) + .andExpect(jsonPath("[2].name", equalTo("TestName3"))) + .andExpect(jsonPath("[2].key", equalTo("testKey3"))) + .andExpect(jsonPath("[2].description", equalTo("Desc3"))) + .andExpect(jsonPath("[2].createdBy", equalTo("uploadTester"))) + .andExpect(jsonPath("[2].createdAt", not(equalTo(0)))).andReturn(); + } + + @Step + private List createTestDistributionSetTestTypes() { + assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES); + + return Lists.newArrayList( + entityFactory.distributionSetType().create().key("testKey1").name("TestName1").description("Desc1") + .colour("col").mandatory(Lists.newArrayList(osType.getId())) + .optional(Lists.newArrayList(runtimeType.getId())).build(), + entityFactory.distributionSetType().create().key("testKey2").name("TestName2").description("Desc2") + .colour("col") + .optional(Lists.newArrayList(runtimeType.getId(), osType.getId(), appType.getId())).build(), + entityFactory.distributionSetType().create().key("testKey3").name("TestName3").description("Desc3") + .colour("col").mandatory(Lists.newArrayList(runtimeType.getId(), osType.getId())).build()); + } + @Test @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( - entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")); + DistributionSetType testType = distributionSetManagement + .createDistributionSetType(entityFactory.distributionSetType().create().key("test123") + .name("TestName123").description("Desc123").colour("col12")); assertThat(testType.getOptLockRevision()).isEqualTo(1); mvc.perform(post("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes", testType.getId()) @@ -229,8 +253,9 @@ public void addMandatoryModuleToDistributionSetType() throws JSONException, Exce @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( - entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")); + DistributionSetType testType = distributionSetManagement + .createDistributionSetType(entityFactory.distributionSetType().create().key("test123") + .name("TestName123").description("Desc123").colour("col12")); assertThat(testType.getOptLockRevision()).isEqualTo(1); mvc.perform(post("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes", testType.getId()) @@ -249,12 +274,7 @@ public void addOptionalModuleToDistributionSetType() throws JSONException, Excep @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( - entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123") - .addMandatoryModuleType(osType).addOptionalModuleType(appType)); - assertThat(testType.getOptLockRevision()).isEqualTo(1); - assertThat(testType.getOptionalModuleTypes()).containsExactly(appType); - assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType); + final DistributionSetType testType = generateTestType(); mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes", testType.getId()) .accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) @@ -268,12 +288,7 @@ public void getMandatoryModulesOfDistributionSetType() throws JSONException, Exc @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( - entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123") - .addMandatoryModuleType(osType).addOptionalModuleType(appType)); - assertThat(testType.getOptLockRevision()).isEqualTo(1); - assertThat(testType.getOptionalModuleTypes()).containsExactly(appType); - assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType); + final DistributionSetType testType = generateTestType(); mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes", testType.getId()) .accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) @@ -288,12 +303,7 @@ public void getOptionalModulesOfDistributionSetType() throws JSONException, Exce @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( - entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123") - .addMandatoryModuleType(osType).addOptionalModuleType(appType)); - assertThat(testType.getOptLockRevision()).isEqualTo(1); - assertThat(testType.getOptionalModuleTypes()).containsExactly(appType); - assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType); + final DistributionSetType testType = generateTestType(); mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes/{smtId}", testType.getId(), osType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) @@ -306,16 +316,21 @@ public void getMandatoryModuleOfDistributionSetType() throws JSONException, Exce .andExpect(jsonPath("$.lastModifiedAt", equalTo(osType.getLastModifiedAt()))); } + private DistributionSetType generateTestType() { + final DistributionSetType testType = distributionSetManagement.createDistributionSetType(entityFactory + .distributionSetType().create().key("test123").name("TestName123").description("Desc123").colour("col") + .mandatory(Lists.newArrayList(osType.getId())).optional(Lists.newArrayList(appType.getId()))); + assertThat(testType.getOptLockRevision()).isEqualTo(1); + assertThat(testType.getOptionalModuleTypes()).containsExactly(appType); + assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType); + return testType; + } + @Test @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( - entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123") - .addMandatoryModuleType(osType).addOptionalModuleType(appType)); - assertThat(testType.getOptLockRevision()).isEqualTo(1); - assertThat(testType.getOptionalModuleTypes()).containsExactly(appType); - assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType); + final DistributionSetType testType = generateTestType(); mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes/{smtId}", testType.getId(), appType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) @@ -332,12 +347,7 @@ public void getOptionalModuleOfDistributionSetType() throws JSONException, Excep @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( - entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123") - .addMandatoryModuleType(osType).addOptionalModuleType(appType)); - assertThat(testType.getOptLockRevision()).isEqualTo(1); - assertThat(testType.getOptionalModuleTypes()).containsExactly(appType); - assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType); + DistributionSetType testType = generateTestType(); mvc.perform(delete("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes/{smtId}", testType.getId(), osType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) @@ -354,12 +364,7 @@ public void removeMandatoryModuleToDistributionSetType() throws JSONException, E @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( - entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123") - .addMandatoryModuleType(osType).addOptionalModuleType(appType)); - assertThat(testType.getOptLockRevision()).isEqualTo(1); - assertThat(testType.getOptionalModuleTypes()).containsExactly(appType); - assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType); + DistributionSetType testType = generateTestType(); mvc.perform(delete("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes/{smtId}", testType.getId(), appType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) @@ -377,10 +382,11 @@ public void removeOptionalModuleToDistributionSetType() throws JSONException, Ex @Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID} GET requests.") public void getDistributionSetType() throws Exception { - DistributionSetType testType = distributionSetManagement.createDistributionSetType( - entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")); - testType.setDescription("Desc1234"); - testType = distributionSetManagement.updateDistributionSetType(testType); + DistributionSetType testType = distributionSetManagement + .createDistributionSetType(entityFactory.distributionSetType().create().key("test123") + .name("TestName123").description("Desc123").colour("col12")); + testType = distributionSetManagement.updateDistributionSetType( + entityFactory.distributionSetType().update(testType.getId()).description("Desc1234")); mvc.perform(get("/rest/v1/distributionsettypes/{dstId}", testType.getId()).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) @@ -396,8 +402,9 @@ public void getDistributionSetType() throws Exception { @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( - entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")); + final DistributionSetType testType = distributionSetManagement + .createDistributionSetType(entityFactory.distributionSetType().create().key("test123") + .name("TestName123").description("Desc123").colour("col12")); assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES + 1); @@ -411,10 +418,12 @@ public void deleteDistributionSetTypeUnused() throws Exception { @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( - entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")); - distributionSetManagement.createDistributionSet( - entityFactory.generateDistributionSet("sdfsd", "dsfsdf", "sdfsdf", testType, null)); + final DistributionSetType testType = distributionSetManagement + .createDistributionSetType(entityFactory.distributionSetType().create().key("test123") + .name("TestName123").description("Desc123").colour("col12")); + + distributionSetManagement.createDistributionSet(entityFactory.distributionSet().create().name("sdfsd") + .description("dsfsdf").version("1").type(testType)); assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES + 1); assertThat(distributionSetManagement.countDistributionSetsAll()).isEqualTo(1); @@ -429,8 +438,9 @@ public void deleteDistributionSetTypeUsed() throws Exception { @Test @Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID} PUT requests.") public void updateDistributionSetTypeOnlyDescriptionAndNameUntouched() throws Exception { - final DistributionSetType testType = distributionSetManagement.createDistributionSetType( - entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")); + final DistributionSetType testType = distributionSetManagement + .createDistributionSetType(entityFactory.distributionSetType().create().key("test123") + .name("TestName123").description("Desc123").colour("col")); final String body = new JSONObject().put("id", testType.getId()).put("description", "foobardesc") .put("name", "nameShouldNotBeChanged").toString(); @@ -488,11 +498,12 @@ public void getDistributionSetTypesWithPagingLimitAndOffsetRequestParameter() th @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( - entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")); + // final DistributionSetType testDsType = distributionSetManagement + // .createDistributionSetType(entityFactory.distributionSetType().create().key("test123") + // .name("TestName123").description("Desc123").colour("col")); final SoftwareModuleType testSmType = softwareManagement.createSoftwareModuleType( - entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5)); + entityFactory.softwareModuleType().create().key("test123").name("TestName123")); // DST does not exist mvc.perform(get("/rest/v1/distributionsettypes/12345678")).andDo(MockMvcResultPrinter.print()) @@ -532,10 +543,9 @@ public void invalidRequestsOnDistributionSetTypesResource() throws Exception { // Modules types at creation time invalid - final DistributionSetType testNewType = entityFactory.generateDistributionSetType("test123", "TestName123", - "Desc123"); - testNewType.addMandatoryModuleType( - entityFactory.generateSoftwareModuleType("foo", "bar", "test", Integer.MAX_VALUE)); + final DistributionSetType testNewType = entityFactory.distributionSetType().create().key("test123") + .name("TestName123").description("Desc123").colour("col").mandatory(Lists.newArrayList(osType.getId())) + .optional(Collections.emptyList()).build(); mvc.perform(post("/rest/v1/distributionsettypes") .content(JsonBuilder.distributionSetTypes(Lists.newArrayList(testNewType))) @@ -556,8 +566,8 @@ public void invalidRequestsOnDistributionSetTypesResource() throws Exception { .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isBadRequest()); - final DistributionSetType toLongName = entityFactory.generateDistributionSetType("test123", - RandomStringUtils.randomAscii(80), "Desc123"); + final DistributionSetType toLongName = entityFactory.distributionSetType().create().key("test123") + .name(RandomStringUtils.randomAscii(80)).build(); mvc.perform(post("/rest/v1/distributionsettypes") .content(JsonBuilder.distributionSetTypes(Lists.newArrayList(toLongName))) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) @@ -580,10 +590,10 @@ public void invalidRequestsOnDistributionSetTypesResource() throws Exception { @Test @Description("Search erquest of software module types.") public void searchDistributionSetTypeRsql() throws Exception { - final DistributionSetType testType = distributionSetManagement.createDistributionSetType( - entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")); - final DistributionSetType testType2 = distributionSetManagement.createDistributionSetType( - entityFactory.generateDistributionSetType("test1234", "TestName1234", "Desc123")); + distributionSetManagement.createDistributionSetType( + entityFactory.distributionSetType().create().key("test123").name("TestName123")); + distributionSetManagement.createDistributionSetType( + entityFactory.distributionSetType().create().key("test1234").name("TestName1234")); final String rsqlFindLikeDs1OrDs2 = "name==TestName123,name==TestName1234"; @@ -597,9 +607,8 @@ private void createSoftwareModulesAlphabetical(final int amount) { char character = 'a'; for (int index = 0; index < amount; index++) { final String str = String.valueOf(character); - final SoftwareModule softwareModule = entityFactory.generateSoftwareModule(osType, str, str, str, str); - - softwareManagement.createSoftwareModule(softwareModule); + softwareManagement.createSoftwareModule( + entityFactory.softwareModule().create().name(str).description(str).vendor(str).version(str)); character++; } } 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 091861a61d..abea4f28f1 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 @@ -18,7 +18,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; @@ -45,6 +44,8 @@ import org.springframework.data.domain.Sort.Direction; import org.springframework.http.MediaType; +import com.google.common.collect.Lists; + import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; @@ -119,7 +120,7 @@ public void missingTargetFilterQueryInRollout() throws Exception { @Test @Description("Testing that rollout can be created") public void createRollout() throws Exception { - targetManagement.createTargets(testdataFactory.generateTargets(20, "target", "rollout")); + testdataFactory.createTargets(20, "target", "rollout"); final DistributionSet dsA = testdataFactory.createDistributionSet(""); postRollout("rollout1", 10, dsA.getId(), "id==target*"); @@ -131,25 +132,18 @@ public void createRolloutWithGroupsDefinitions() throws Exception { final DistributionSet dsA = testdataFactory.createDistributionSet("ro"); final int amountTargets = 10; - targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "ro-target", "rollout")); - - List rolloutGroups = new ArrayList<>(2); - final int percentTargetsInGroup1 = 20; - final int percentTargetsInGroup2 = 100; + testdataFactory.createTargets(amountTargets, "ro-target", "rollout"); - RolloutGroup group1 = entityFactory.generateRolloutGroup(); - group1.setName("Group1"); - group1.setDescription("Group1desc"); - group1.setTargetPercentage(percentTargetsInGroup1); - rolloutGroups.add(group1); + final float percentTargetsInGroup1 = 20; + final float percentTargetsInGroup2 = 100; - RolloutGroup group2 = entityFactory.generateRolloutGroup(); - group2.setName("Group2"); - group2.setDescription("Group2desc"); - group2.setTargetPercentage(percentTargetsInGroup2); - rolloutGroups.add(group2); + final List rolloutGroups = Lists.newArrayList( + entityFactory.rolloutGroup().create().name("Group1").description("Group1desc") + .targetPercentage(percentTargetsInGroup1).build(), + entityFactory.rolloutGroup().create().name("Group2").description("Group2desc") + .targetPercentage(percentTargetsInGroup2).build()); - RolloutGroupConditions rolloutGroupConditions = new RolloutGroupConditionBuilder().build(); + final RolloutGroupConditions rolloutGroupConditions = new RolloutGroupConditionBuilder().withDefaults().build(); mvc.perform(post("/rest/v1/rollouts") .content(JsonBuilder.rollout("rollout2", "desc", null, dsA.getId(), "id==ro-target*", @@ -161,41 +155,50 @@ public void createRolloutWithGroupsDefinitions() throws Exception { @Test @Description("Testing that no rollout with groups that have illegal percentages can be created") - public void createRolloutWithIllegalPercentages() throws Exception { + public void createRolloutWithToLowlPercentage() throws Exception { final DistributionSet dsA = testdataFactory.createDistributionSet("ro2"); final int amountTargets = 10; - targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "ro-target", "rollout")); - - List rolloutGroups = new ArrayList<>(2); - - RolloutGroup group1 = entityFactory.generateRolloutGroup(); - group1.setName("Group1"); - group1.setDescription("Group1desc"); - group1.setTargetPercentage(0); - rolloutGroups.add(group1); + testdataFactory.createTargets(amountTargets, "ro-target", "rollout"); - RolloutGroup group2 = entityFactory.generateRolloutGroup(); - group2.setName("Group2"); - group2.setDescription("Group2desc"); - group2.setTargetPercentage(100); - rolloutGroups.add(group2); + final List rolloutGroups = Lists.newArrayList( + entityFactory.rolloutGroup().create().name("Group1").description("Group1desc").targetPercentage(0F) + .build(), + entityFactory.rolloutGroup().create().name("Group2").description("Group2desc").targetPercentage(100F) + .build()); - RolloutGroupConditions rolloutGroupConditions = new RolloutGroupConditionBuilder().build(); + final RolloutGroupConditions rolloutGroupConditions = new RolloutGroupConditionBuilder().withDefaults().build(); mvc.perform(post("/rest/v1/rollouts") .content(JsonBuilder.rollout("rollout4", "desc", null, dsA.getId(), "id==ro-target*", rolloutGroupConditions, rolloutGroups)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isInternalServerError()) + .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()) .andExpect(jsonPath("$.errorCode", equalTo("hawkbit.server.error.repo.constraintViolation"))); - group1.setTargetPercentage(101); + } + + @Test + @Description("Testing that no rollout with groups that have illegal percentages can be created") + public void createRolloutWithToHighPercentage() throws Exception { + final DistributionSet dsA = testdataFactory.createDistributionSet("ro2"); + + final int amountTargets = 10; + testdataFactory.createTargets(amountTargets, "ro-target", "rollout"); + + final List rolloutGroups = Lists.newArrayList( + entityFactory.rolloutGroup().create().name("Group1").description("Group1desc").targetPercentage(1F) + .build(), + entityFactory.rolloutGroup().create().name("Group2").description("Group2desc").targetPercentage(101F) + .build()); + + final RolloutGroupConditions rolloutGroupConditions = new RolloutGroupConditionBuilder().withDefaults().build(); + mvc.perform(post("/rest/v1/rollouts") .content(JsonBuilder.rollout("rollout4", "desc", null, dsA.getId(), "id==ro-target*", rolloutGroupConditions, rolloutGroups)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isInternalServerError()) + .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()) .andExpect(jsonPath("$.errorCode", equalTo("hawkbit.server.error.repo.constraintViolation"))); } @@ -213,7 +216,7 @@ public void noRolloutReturnsEmptyList() throws Exception { public void rolloutPagedListContainsAllRollouts() throws Exception { final DistributionSet dsA = testdataFactory.createDistributionSet(""); - targetManagement.createTargets(testdataFactory.generateTargets(20, "target", "rollout")); + testdataFactory.createTargets(20, "target", "rollout"); // setup - create 2 rollouts postRollout("rollout1", 10, dsA.getId(), "id==target*"); @@ -240,7 +243,7 @@ public void rolloutPagedListContainsAllRollouts() throws Exception { public void rolloutPagedListIsLimitedToQueryParam() throws Exception { final DistributionSet dsA = testdataFactory.createDistributionSet(""); - targetManagement.createTargets(testdataFactory.generateTargets(20, "target", "rollout")); + testdataFactory.createTargets(20, "target", "rollout"); // setup - create 2 rollouts postRollout("rollout1", 10, dsA.getId(), "id==target*"); @@ -259,7 +262,7 @@ public void rolloutPagedListIsLimitedToQueryParam() throws Exception { public void retrieveRolloutGroupsForSpecificRollout() throws Exception { // setup final int amountTargets = 20; - targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); + testdataFactory.createTargets(amountTargets, "rollout", "rollout"); final DistributionSet dsA = testdataFactory.createDistributionSet(""); // create rollout including the created targets with prefix 'rollout' @@ -281,7 +284,7 @@ public void retrieveRolloutGroupsForSpecificRollout() throws Exception { public void startingRolloutSwitchesIntoRunningState() throws Exception { // setup final int amountTargets = 20; - targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); + testdataFactory.createTargets(amountTargets, "rollout", "rollout"); final DistributionSet dsA = testdataFactory.createDistributionSet(""); // create rollout including the created targets with prefix 'rollout' @@ -312,7 +315,7 @@ public void startingRolloutSwitchesIntoRunningState() throws Exception { public void pausingRolloutSwitchesIntoPausedState() throws Exception { // setup final int amountTargets = 20; - targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); + testdataFactory.createTargets(amountTargets, "rollout", "rollout"); final DistributionSet dsA = testdataFactory.createDistributionSet(""); // create rollout including the created targets with prefix 'rollout' @@ -341,7 +344,7 @@ public void pausingRolloutSwitchesIntoPausedState() throws Exception { public void resumingRolloutSwitchesIntoRunningState() throws Exception { // setup final int amountTargets = 20; - targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); + testdataFactory.createTargets(amountTargets, "rollout", "rollout"); final DistributionSet dsA = testdataFactory.createDistributionSet(""); // create rollout including the created targets with prefix 'rollout' @@ -374,7 +377,7 @@ public void resumingRolloutSwitchesIntoRunningState() throws Exception { public void startingAlreadyStartedRolloutReturnsBadRequest() throws Exception { // setup final int amountTargets = 20; - targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); + testdataFactory.createTargets(amountTargets, "rollout", "rollout"); final DistributionSet dsA = testdataFactory.createDistributionSet(""); // create rollout including the created targets with prefix 'rollout' @@ -398,7 +401,7 @@ public void startingAlreadyStartedRolloutReturnsBadRequest() throws Exception { public void resumingNotStartedRolloutReturnsBadRequest() throws Exception { // setup final int amountTargets = 20; - targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); + testdataFactory.createTargets(amountTargets, "rollout", "rollout"); final DistributionSet dsA = testdataFactory.createDistributionSet(""); // create rollout including the created targets with prefix 'rollout' @@ -415,7 +418,7 @@ public void resumingNotStartedRolloutReturnsBadRequest() throws Exception { public void startingRolloutFirstRolloutGroupIsInRunningState() throws Exception { // setup final int amountTargets = 10; - targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); + testdataFactory.createTargets(amountTargets, "rollout", "rollout"); final DistributionSet dsA = testdataFactory.createDistributionSet(""); // create rollout including the created targets with prefix 'rollout' @@ -443,7 +446,7 @@ public void startingRolloutFirstRolloutGroupIsInRunningState() throws Exception public void retrieveSingleRolloutGroup() throws Exception { // setup final int amountTargets = 10; - targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); + testdataFactory.createTargets(amountTargets, "rollout", "rollout"); final DistributionSet dsA = testdataFactory.createDistributionSet(""); // create rollout including the created targets with prefix 'rollout' @@ -466,7 +469,7 @@ public void retrieveSingleRolloutGroup() throws Exception { public void retrieveTargetsFromRolloutGroup() throws Exception { // setup final int amountTargets = 10; - targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); + testdataFactory.createTargets(amountTargets, "rollout", "rollout"); final DistributionSet dsA = testdataFactory.createDistributionSet(""); // create rollout including the created targets with prefix 'rollout' @@ -488,8 +491,7 @@ public void retrieveTargetsFromRolloutGroup() throws Exception { public void retrieveTargetsFromRolloutGroupWithQuery() throws Exception { // setup final int amountTargets = 10; - final List targets = targetManagement - .createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); + final List targets = testdataFactory.createTargets(amountTargets, "rollout", "rollout"); final DistributionSet dsA = testdataFactory.createDistributionSet(""); // create rollout including the created targets with prefix 'rollout' @@ -513,7 +515,7 @@ public void retrieveTargetsFromRolloutGroupWithQuery() throws Exception { public void retrieveTargetsFromRolloutGroupAfterRolloutIsStarted() throws Exception { // setup final int amountTargets = 10; - targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); + testdataFactory.createTargets(amountTargets, "rollout", "rollout"); final DistributionSet dsA = testdataFactory.createDistributionSet(""); // create rollout including the created targets with prefix 'rollout' @@ -540,7 +542,7 @@ public void retrieveTargetsFromRolloutGroupAfterRolloutIsStarted() throws Except public void startingRolloutSwitchesIntoRunningStateAsync() throws Exception { final int amountTargets = 1000; - targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); + testdataFactory.createTargets(amountTargets, "rollout", "rollout"); final DistributionSet dsA = testdataFactory.createDistributionSet(""); // create rollout including the created targets with prefix 'rollout' @@ -554,8 +556,7 @@ public void startingRolloutSwitchesIntoRunningStateAsync() throws Exception { rolloutManagement.checkStartingRollouts(0); // check if running - assertThat(doWithTimeout(() -> getRollout(rollout.getId()), result -> success(result), 60_000, 100)) - .isNotNull(); + assertThat(doWithTimeout(() -> getRollout(rollout.getId()), this::success, 60_000, 100)).isNotNull(); } @Test @@ -566,10 +567,10 @@ public void getRolloutWithRSQLParam() throws Exception { final int amountTargetsRollout2 = 25; final int amountTargetsRollout3 = 25; final int amountTargetsOther = 25; - 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")); + testdataFactory.createTargets(amountTargetsRollout1, "rollout1", "rollout1"); + testdataFactory.createTargets(amountTargetsRollout2, "rollout2", "rollout2"); + testdataFactory.createTargets(amountTargetsRollout3, "rollout3", "rollout3"); + testdataFactory.createTargets(amountTargetsOther, "other1", "other1"); final DistributionSet dsA = testdataFactory.createDistributionSet(""); createRollout("rollout1", 5, dsA.getId(), "controllerId==rollout1*"); @@ -600,7 +601,7 @@ public void getRolloutWithRSQLParam() throws Exception { public void retrieveRolloutGroupsForSpecificRolloutWithRSQLParam() throws Exception { // setup final int amountTargets = 20; - targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); + testdataFactory.createTargets(amountTargets, "rollout", "rollout"); final DistributionSet dsA = testdataFactory.createDistributionSet(""); // create rollout including the created targets with prefix 'rollout' @@ -667,22 +668,20 @@ private void postRollout(final String name, final int groupSize, final long dist final String targetFilterQuery) throws Exception { mvc.perform(post("/rest/v1/rollouts") .content(JsonBuilder.rollout(name, "desc", groupSize, distributionSetId, targetFilterQuery, - new RolloutGroupConditionBuilder().build())) + new RolloutGroupConditionBuilder().withDefaults().build())) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated()).andReturn(); } private Rollout createRollout(final String name, final int amountGroups, final long distributionSetId, final String targetFilterQuery) { - Rollout rollout = entityFactory.generateRollout(); - rollout.setDistributionSet(distributionSetManagement.findDistributionSetById(distributionSetId)); - rollout.setName(name); - rollout.setTargetFilterQuery(targetFilterQuery); - rollout = rolloutManagement.createRollout(rollout, amountGroups, new RolloutGroupConditionBuilder() - .successCondition(RolloutGroupSuccessCondition.THRESHOLD, "100").build()); + final Rollout rollout = rolloutManagement.createRollout( + entityFactory.rollout().create().name(name).set(distributionSetId).targetFilterQuery(targetFilterQuery), + amountGroups, new RolloutGroupConditionBuilder().withDefaults() + .successCondition(RolloutGroupSuccessCondition.THRESHOLD, "100").build()); // Run here, because Scheduler is disabled during tests - rolloutManagement.fillRolloutGroupsWithTargets(rolloutManagement.findRolloutById(rollout.getId())); + rolloutManagement.fillRolloutGroupsWithTargets(rollout.getId()); return rolloutManagement.findRolloutById(rollout.getId()); } 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 7c3099ecba..1f1af61fea 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 @@ -28,7 +28,6 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -37,6 +36,7 @@ import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact; import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; +import org.eclipse.hawkbit.repository.Constants; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.DistributionSet; @@ -91,16 +91,8 @@ public void updateSoftwareModuleOnlyDescriptionAndVendorNameUntouched() throws E final String updateVendor = "newVendor1"; final String updateDescription = "newDescription1"; - 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 = entityFactory.generateSoftwareModule(osType, knownSWName, knownSWVersion, - knownSWDescription, knownSWVendor); - sm = softwareManagement.createSoftwareModule(sm); + SoftwareModule sm = softwareManagement.createSoftwareModule(entityFactory.softwareModule().create().type(osType) + .name(knownSWName).version(knownSWVersion).description(knownSWDescription).vendor(knownSWVendor)); assertThat(sm.getName()).as("Wrong name of the software module").isEqualTo(knownSWName); @@ -120,13 +112,18 @@ public void updateSoftwareModuleOnlyDescriptionAndVendorNameUntouched() throws E .andExpect(jsonPath("$.description", equalTo(updateDescription))) .andExpect(jsonPath("$.name", equalTo(knownSWName))).andReturn(); + sm = softwareManagement.findSoftwareModuleById(sm.getId()); + assertThat(sm.getName()).isEqualTo(knownSWName); + assertThat(sm.getVendor()).isEqualTo(updateVendor); + assertThat(sm.getLastModifiedBy()).isEqualTo("smUpdateTester"); + assertThat(sm.getDescription()).isEqualTo(updateDescription); + } @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 = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); - sm = softwareManagement.createSoftwareModule(sm); + final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); // create test file final byte random[] = RandomStringUtils.random(5 * 1024).getBytes(); @@ -191,8 +188,7 @@ public void emptyUploadArtifact() throws Exception { assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); assertThat(artifactManagement.countArtifactsAll()).isEqualTo(0); - SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); - sm = softwareManagement.createSoftwareModule(sm); + final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); final MockMultipartFile file = new MockMultipartFile("file", "orig", null, new byte[0]); @@ -204,8 +200,7 @@ public void emptyUploadArtifact() throws Exception { @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 = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); - sm = softwareManagement.createSoftwareModule(sm); + final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); final byte random[] = RandomStringUtils.random(5 * 1024).getBytes(); final String md5sum = HashGeneratorUtils.generateMD5(random); @@ -226,8 +221,7 @@ public void duplicateUploadArtifact() throws Exception { @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 = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); - sm = softwareManagement.createSoftwareModule(sm); + final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); assertThat(artifactManagement.countArtifactsAll()).isEqualTo(0); // create test file @@ -253,8 +247,7 @@ public void uploadArtifactWithCustomName() throws Exception { @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 = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); - sm = softwareManagement.createSoftwareModule(sm); + final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); assertThat(artifactManagement.countArtifactsAll()).isEqualTo(0); // create test file @@ -297,8 +290,7 @@ public void uploadArtifactWithHashCheck() throws Exception { @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 = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); - sm = softwareManagement.createSoftwareModule(sm); + final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); final byte random[] = RandomStringUtils.random(5 * 1024).getBytes(); @@ -332,8 +324,7 @@ public void downloadArtifact() throws Exception { @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 = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); - sm = softwareManagement.createSoftwareModule(sm); + final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); final byte random[] = RandomStringUtils.random(5 * 1024).getBytes(); final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), sm.getId(), @@ -358,8 +349,7 @@ public void getArtifact() throws Exception { @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 = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); - sm = softwareManagement.createSoftwareModule(sm); + final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); final byte random[] = RandomStringUtils.random(5 * 1024).getBytes(); @@ -399,8 +389,7 @@ public void invalidRequestsOnArtifactResource() throws Exception { final byte random[] = RandomStringUtils.random(5 * 1024).getBytes(); final MockMultipartFile file = new MockMultipartFile("file", "orig", null, random); - SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); - sm = softwareManagement.createSoftwareModule(sm); + final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); // no artifact available mvc.perform(get("/rest/v1/softwaremodules/{smId}/artifacts/1234567/download", sm.getId())) @@ -432,8 +421,7 @@ public void invalidRequestsOnArtifactResource() throws Exception { @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 = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); - sm = softwareManagement.createSoftwareModule(sm); + final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); final List modules = Lists.newArrayList(sm); @@ -458,8 +446,8 @@ public void invalidRequestsOnSoftwaremodulesResource() throws Exception { .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isBadRequest()); - final SoftwareModule toLongName = entityFactory.generateSoftwareModule(osType, - RandomStringUtils.randomAscii(80), "version 1", null, null); + final SoftwareModule toLongName = entityFactory.softwareModule().create().type(osType) + .name(RandomStringUtils.randomAscii(80)).build(); mvc.perform( post("/rest/v1/softwaremodules").content(JsonBuilder.softwareModules(Lists.newArrayList(toLongName))) .contentType(MediaType.APPLICATION_JSON)) @@ -525,25 +513,17 @@ public void getSoftwareModulesWithPagingLimitAndOffsetRequestParameter() throws @WithUser(principal = "uploadTester", allSpPermissions = true) @Description("Test retrieval of all software modules the user has access to.") public void getSoftwareModules() throws Exception { - SoftwareModule os = entityFactory.generateSoftwareModule(osType, "name1", "version1", "description1", - "vendor1"); - os = softwareManagement.createSoftwareModule(os); - - SoftwareModule jvm = entityFactory.generateSoftwareModule(runtimeType, "name1", "version1", "description1", - "vendor1"); - jvm = softwareManagement.createSoftwareModule(jvm); - - SoftwareModule ah = entityFactory.generateSoftwareModule(appType, "name1", "version1", "description1", - "vendor1"); - ah = softwareManagement.createSoftwareModule(ah); + final SoftwareModule os = testdataFactory.createSoftwareModuleOs(); + final SoftwareModule app = testdataFactory.createSoftwareModuleApp(); mvc.perform(get("/rest/v1/softwaremodules").accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].name", contains("name1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].version", contains("version1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].description", contains("description1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].vendor", contains("vendor1"))) + .andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].name", contains(os.getName()))) + .andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].version", contains(os.getVersion()))) + .andExpect( + jsonPath("$.content.[?(@.id==" + os.getId() + ")].description", contains(os.getDescription()))) + .andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].vendor", contains(os.getVendor()))) .andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].type", contains("os"))) .andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].createdBy", contains("uploadTester"))) .andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].createdAt", contains(os.getCreatedAt()))) @@ -556,121 +536,83 @@ public void getSoftwareModules() throws Exception { .andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")]._links.metadata.href", contains("http://localhost/rest/v1/softwaremodules/" + os.getId() + "/metadata?offset=0&limit=50"))) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm.getId() + ")].name", contains("name1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm.getId() + ")].version", contains("version1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm.getId() + ")].description", contains("description1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm.getId() + ")].vendor", contains("vendor1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm.getId() + ")].type", contains("runtime"))) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm.getId() + ")].createdBy", contains("uploadTester"))) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm.getId() + ")].createdAt", contains(jvm.getCreatedAt()))) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm.getId() + ")]._links.type.href", - contains("http://localhost/rest/v1/softwaremoduletypes/" + runtimeType.getId()))) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm.getId() + ")]._links.self.href", - contains("http://localhost/rest/v1/softwaremodules/" + jvm.getId()))) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm.getId() + ")]._links.artifacts.href", - contains("http://localhost/rest/v1/softwaremodules/" + jvm.getId() + "/artifacts"))) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm.getId() + ")]._links.metadata.href", - contains("http://localhost/rest/v1/softwaremodules/" + jvm.getId() - + "/metadata?offset=0&limit=50"))) - .andExpect(jsonPath("$.content.[?(@.id==" + ah.getId() + ")].name", contains("name1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + ah.getId() + ")].version", contains("version1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + ah.getId() + ")].description", contains("description1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + ah.getId() + ")].vendor", contains("vendor1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + ah.getId() + ")].type", contains("application"))) - .andExpect(jsonPath("$.content.[?(@.id==" + ah.getId() + ")].createdBy", contains("uploadTester"))) - .andExpect(jsonPath("$.content.[?(@.id==" + ah.getId() + ")].createdAt", contains(ah.getCreatedAt()))) - .andExpect(jsonPath("$.content.[?(@.id==" + ah.getId() + ")]._links.artifacts.href", - contains("http://localhost/rest/v1/softwaremodules/" + ah.getId() + "/artifacts"))) - .andExpect(jsonPath("$.content.[?(@.id==" + ah.getId() + ")]._links.metadata.href", - contains("http://localhost/rest/v1/softwaremodules/" + ah.getId() + .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")].name", contains(app.getName()))) + .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")].version", contains(app.getVersion()))) + .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")].description", + contains(app.getDescription()))) + .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")].vendor", contains(app.getVendor()))) + .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")].type", contains("application"))) + .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")].createdBy", contains("uploadTester"))) + .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")].createdAt", contains(app.getCreatedAt()))) + .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")]._links.artifacts.href", + contains("http://localhost/rest/v1/softwaremodules/" + app.getId() + "/artifacts"))) + .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")]._links.metadata.href", + contains("http://localhost/rest/v1/softwaremodules/" + app.getId() + "/metadata?offset=0&limit=50"))) - .andExpect(jsonPath("$.content.[?(@.id==" + ah.getId() + ")]._links.type.href", + .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")]._links.type.href", contains("http://localhost/rest/v1/softwaremoduletypes/" + appType.getId()))) - .andExpect(jsonPath("$.content.[?(@.id==" + ah.getId() + ")]._links.self.href", - contains("http://localhost/rest/v1/softwaremodules/" + ah.getId()))); + .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")]._links.self.href", + contains("http://localhost/rest/v1/softwaremodules/" + app.getId()))); - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Softwaremodule size is wrong").hasSize(3); + assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Softwaremodule size is wrong").hasSize(2); } @Test @Description("Test the various filter parameters, e.g. filter by name or type of the module.") public void getSoftwareModulesWithFilterParameters() throws Exception { - SoftwareModule os1 = entityFactory.generateSoftwareModule(osType, "osName1", "1.0.0", "description1", - "vendor1"); - os1 = softwareManagement.createSoftwareModule(os1); - - SoftwareModule jvm1 = entityFactory.generateSoftwareModule(runtimeType, "runtimeName1", "2.0.0", "description1", - "vendor1"); - jvm1 = softwareManagement.createSoftwareModule(jvm1); + final SoftwareModule os1 = testdataFactory.createSoftwareModuleOs("1"); + final SoftwareModule app1 = testdataFactory.createSoftwareModuleApp("1"); + testdataFactory.createSoftwareModuleOs("2"); + final SoftwareModule app2 = testdataFactory.createSoftwareModuleApp("2"); - SoftwareModule ah1 = entityFactory.generateSoftwareModule(appType, "appName1", "3.0.0", "description1", - "vendor1"); - ah1 = softwareManagement.createSoftwareModule(ah1); - - SoftwareModule os2 = entityFactory.generateSoftwareModule(osType, "osName2", "1.0.1", "description2", - "vendor2"); - os2 = softwareManagement.createSoftwareModule(os2); - - SoftwareModule jvm2 = entityFactory.generateSoftwareModule(runtimeType, "runtimeName2", "2.0.1", "description2", - "vendor2"); - jvm2 = softwareManagement.createSoftwareModule(jvm2); - - SoftwareModule ah2 = entityFactory.generateSoftwareModule(appType, "appName2", "3.0.1", "description2", - "vendor2"); - ah2 = softwareManagement.createSoftwareModule(ah2); - - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(6); + assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(4); // only by name, only one exists per name - mvc.perform(get("/rest/v1/softwaremodules?q=name==osName1").accept(MediaType.APPLICATION_JSON)) + mvc.perform(get("/rest/v1/softwaremodules?q=name==" + os1.getName()).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.content.[?(@.id==" + os1.getId() + ")].name", contains("osName1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + os1.getId() + ")].version", contains("1.0.0"))) - .andExpect(jsonPath("$.content.[?(@.id==" + os1.getId() + ")].description", contains("description1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + os1.getId() + ")].vendor", contains("vendor1"))) + .andExpect(jsonPath("$.content.[?(@.id==" + os1.getId() + ")].name", contains(os1.getName()))) + .andExpect(jsonPath("$.content.[?(@.id==" + os1.getId() + ")].version", contains(os1.getVersion()))) + .andExpect(jsonPath("$.content.[?(@.id==" + os1.getId() + ")].description", + contains(os1.getDescription()))) + .andExpect(jsonPath("$.content.[?(@.id==" + os1.getId() + ")].vendor", contains(os1.getVendor()))) .andExpect(jsonPath("$.content.[?(@.id==" + os1.getId() + ")].type", contains("os"))) .andExpect(jsonPath("$.content", hasSize(1))).andExpect(jsonPath("$.total", equalTo(1))); // by type, 2 software modules per type exists - mvc.perform(get("/rest/v1/softwaremodules?q=type==application").accept(MediaType.APPLICATION_JSON)) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + mvc.perform(get("/rest/v1/softwaremodules?q=type==" + Constants.SMT_DEFAULT_APP_KEY) + .accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.content.[?(@.id==" + ah1.getId() + ")].name", contains("appName1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + ah1.getId() + ")].version", contains("3.0.0"))) - .andExpect(jsonPath("$.content.[?(@.id==" + ah1.getId() + ")].description", contains("description1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + ah1.getId() + ")].vendor", contains("vendor1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + ah1.getId() + ")].type", contains("application"))) - .andExpect(jsonPath("$.content.[?(@.id==" + ah2.getId() + ")].name", contains("appName2"))) - .andExpect(jsonPath("$.content.[?(@.id==" + ah2.getId() + ")].version", contains("3.0.1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + ah2.getId() + ")].description", contains("description2"))) - .andExpect(jsonPath("$.content.[?(@.id==" + ah2.getId() + ")].vendor", contains("vendor2"))) - .andExpect(jsonPath("$.content.[?(@.id==" + ah2.getId() + ")].type", contains("application"))) + .andExpect(jsonPath("$.content.[?(@.id==" + app1.getId() + ")].name", contains(app1.getName()))) + .andExpect(jsonPath("$.content.[?(@.id==" + app1.getId() + ")].version", contains(app1.getVersion()))) + .andExpect(jsonPath("$.content.[?(@.id==" + app1.getId() + ")].description", + contains(app1.getDescription()))) + .andExpect(jsonPath("$.content.[?(@.id==" + app1.getId() + ")].vendor", contains(app1.getVendor()))) + .andExpect(jsonPath("$.content.[?(@.id==" + app1.getId() + ")].type", + contains(Constants.SMT_DEFAULT_APP_KEY))) + .andExpect(jsonPath("$.content.[?(@.id==" + app2.getId() + ")].name", contains(app2.getName()))) + .andExpect(jsonPath("$.content.[?(@.id==" + app2.getId() + ")].version", contains(app2.getVersion()))) + .andExpect(jsonPath("$.content.[?(@.id==" + app2.getId() + ")].description", + contains(app2.getDescription()))) + .andExpect(jsonPath("$.content.[?(@.id==" + app2.getId() + ")].vendor", contains(app2.getVendor()))) + .andExpect(jsonPath("$.content.[?(@.id==" + app2.getId() + ")].type", + contains(Constants.SMT_DEFAULT_APP_KEY))) .andExpect(jsonPath("$.content", hasSize(2))).andExpect(jsonPath("$.total", equalTo(2))); // by type and version=2.0.0 -> only one result - mvc.perform(get("/rest/v1/softwaremodules?q=type==runtime;version==2.0.0").accept(MediaType.APPLICATION_JSON)) + mvc.perform(get( + "/rest/v1/softwaremodules?q=type==" + Constants.SMT_DEFAULT_APP_KEY + ";version==" + app1.getVersion()) + .accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm1.getId() + ")].name", contains("runtimeName1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm1.getId() + ")].version", contains("2.0.0"))) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm1.getId() + ")].description", contains("description1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm1.getId() + ")].vendor", contains("vendor1"))) + .andExpect(jsonPath("$.content.[?(@.id==" + app1.getId() + ")].name", contains(app1.getName()))) + .andExpect(jsonPath("$.content.[?(@.id==" + app1.getId() + ")].version", contains(app1.getVersion()))) + .andExpect(jsonPath("$.content.[?(@.id==" + app1.getId() + ")].description", + contains(app1.getDescription()))) + .andExpect(jsonPath("$.content.[?(@.id==" + app1.getId() + ")].vendor", contains(app1.getVendor()))) + .andExpect(jsonPath("$.content.[?(@.id==" + app1.getId() + ")].type", + contains(Constants.SMT_DEFAULT_APP_KEY))) .andExpect(jsonPath("$.content", hasSize(1))).andExpect(jsonPath("$.total", equalTo(1))); - - // by type and version range >=2.0.0 -> 2 result - mvc.perform(get("/rest/v1/softwaremodules?q=type==runtime;version=ge=2.0.0").accept(MediaType.APPLICATION_JSON)) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm1.getId() + ")].name", contains("runtimeName1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm1.getId() + ")].version", contains("2.0.0"))) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm1.getId() + ")].description", contains("description1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm1.getId() + ")].vendor", contains("vendor1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm2.getId() + ")].name", contains("runtimeName2"))) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm2.getId() + ")].version", contains("2.0.1"))) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm2.getId() + ")].description", contains("description2"))) - .andExpect(jsonPath("$.content.[?(@.id==" + jvm2.getId() + ")].vendor", contains("vendor2"))) - .andExpect(jsonPath("$.content", hasSize(2))).andExpect(jsonPath("$.total", equalTo(2))); } @Test @@ -693,16 +635,16 @@ public void getSoftwareModulesWithUnknownFieldErrorFilterParameter() throws Exce @WithUser(principal = "uploadTester", allSpPermissions = true) @Description("Tests GET request on /rest/v1/softwaremodules/{smId}.") public void getSoftwareModule() throws Exception { - SoftwareModule os = entityFactory.generateSoftwareModule(osType, "name1", "version1", "description1", - "vendor1"); - os = softwareManagement.createSoftwareModule(os); + final SoftwareModule os = testdataFactory.createSoftwareModuleOs(); mvc.perform(get("/rest/v1/softwaremodules/{smId}", os.getId()).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.name", equalTo("name1"))).andExpect(jsonPath("$.version", equalTo("version1"))) - .andExpect(jsonPath("$.description", equalTo("description1"))) - .andExpect(jsonPath("$.vendor", equalTo("vendor1"))).andExpect(jsonPath("$.type", equalTo("os"))) + .andExpect(jsonPath("$.name", equalTo(os.getName()))) + .andExpect(jsonPath("$.version", equalTo(os.getVersion()))) + .andExpect(jsonPath("$.description", equalTo(os.getDescription()))) + .andExpect(jsonPath("$.vendor", equalTo(os.getVendor()))) + .andExpect(jsonPath("$.type", equalTo(os.getType().getKey()))) .andExpect(jsonPath("$.createdBy", equalTo("uploadTester"))) .andExpect(jsonPath("$.createdAt", equalTo(os.getCreatedAt()))) .andExpect(jsonPath("$._links.metadata.href", @@ -713,65 +655,19 @@ public void getSoftwareModule() throws Exception { .andExpect(jsonPath("$._links.artifacts.href", equalTo("http://localhost/rest/v1/softwaremodules/" + os.getId() + "/artifacts"))); - 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)) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.name", equalTo("name1"))).andExpect(jsonPath("$.version", equalTo("version1"))) - .andExpect(jsonPath("$.description", equalTo("description1"))) - .andExpect(jsonPath("$.vendor", equalTo("vendor1"))).andExpect(jsonPath("$.type", equalTo("runtime"))) - .andExpect(jsonPath("$.createdBy", equalTo("uploadTester"))) - .andExpect(jsonPath("$.createdAt", equalTo(jvm.getCreatedAt()))) - .andExpect(jsonPath("$._links.metadata.href", - equalTo("http://localhost/rest/v1/softwaremodules/" + jvm.getId() - + "/metadata?offset=0&limit=50"))) - .andExpect(jsonPath("$._links.type.href", - equalTo("http://localhost/rest/v1/softwaremoduletypes/" + runtimeType.getId()))) - .andExpect(jsonPath("$._links.artifacts.href", - equalTo("http://localhost/rest/v1/softwaremodules/" + jvm.getId() + "/artifacts"))); - - 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)) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.name", equalTo("name1"))).andExpect(jsonPath("$.version", equalTo("version1"))) - .andExpect(jsonPath("$.description", equalTo("description1"))) - .andExpect(jsonPath("$.vendor", equalTo("vendor1"))) - .andExpect(jsonPath("$.type", equalTo("application"))) - .andExpect(jsonPath("$.createdBy", equalTo("uploadTester"))) - .andExpect(jsonPath("$.createdAt", equalTo(ah.getCreatedAt()))) - .andExpect(jsonPath("$._links.metadata.href", - equalTo("http://localhost/rest/v1/softwaremodules/" + ah.getId() - + "/metadata?offset=0&limit=50"))) - .andExpect(jsonPath("$._links.type.href", - equalTo("http://localhost/rest/v1/softwaremoduletypes/" + appType.getId()))) - .andExpect(jsonPath("$._links.artifacts.href", - equalTo("http://localhost/rest/v1/softwaremodules/" + ah.getId() + "/artifacts"))); - - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Softwaremodule size is wrong").hasSize(3); + assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Softwaremodule size is wrong").hasSize(1); } @Test @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 = 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); - modules.add(jvm); - modules.add(ah); + final SoftwareModule os = entityFactory.softwareModule().create().name("name1").type(osType).version("version1") + .vendor("vendor1").description("description1").build(); + final SoftwareModule ah = entityFactory.softwareModule().create().name("name3").type(appType) + .version("version3").vendor("vendor3").description("description3").build(); + + final List modules = Lists.newArrayList(os, ah); final long current = System.currentTimeMillis(); @@ -785,25 +681,17 @@ public void createSoftwareModules() throws JSONException, Exception { .andExpect(jsonPath("[0].description", equalTo("description1"))) .andExpect(jsonPath("[0].vendor", equalTo("vendor1"))).andExpect(jsonPath("[0].type", equalTo("os"))) .andExpect(jsonPath("[0].createdBy", equalTo("uploadTester"))) - .andExpect(jsonPath("[1].name", equalTo("name2"))) - .andExpect(jsonPath("[1].version", equalTo("version1"))) - .andExpect(jsonPath("[1].description", equalTo("description1"))) - .andExpect(jsonPath("[1].vendor", equalTo("vendor1"))) - .andExpect(jsonPath("[1].type", equalTo("runtime"))) + .andExpect(jsonPath("[1].name", equalTo("name3"))) + .andExpect(jsonPath("[1].version", equalTo("version3"))) + .andExpect(jsonPath("[1].description", equalTo("description3"))) + .andExpect(jsonPath("[1].vendor", equalTo("vendor3"))) + .andExpect(jsonPath("[1].type", equalTo("application"))) .andExpect(jsonPath("[1].createdBy", equalTo("uploadTester"))) - .andExpect(jsonPath("[2].name", equalTo("name3"))) - .andExpect(jsonPath("[2].version", equalTo("version1"))) - .andExpect(jsonPath("[2].description", equalTo("description1"))) - .andExpect(jsonPath("[2].vendor", equalTo("vendor1"))) - .andExpect(jsonPath("[2].type", equalTo("application"))) - .andExpect(jsonPath("[2].createdBy", equalTo("uploadTester"))) - .andExpect(jsonPath("[2].createdAt", not(equalTo(0)))).andReturn(); + .andExpect(jsonPath("[1].createdAt", not(equalTo(0)))).andReturn(); final SoftwareModule osCreated = softwareManagement.findSoftwareModuleByNameAndVersion("name1", "version1", osType); - final SoftwareModule jvmCreated = softwareManagement.findSoftwareModuleByNameAndVersion("name2", "version1", - runtimeType); - final SoftwareModule ahCreated = softwareManagement.findSoftwareModuleByNameAndVersion("name3", "version1", + final SoftwareModule appCreated = softwareManagement.findSoftwareModuleByNameAndVersion("name3", "version3", appType); assertThat( @@ -816,29 +704,19 @@ public void createSoftwareModules() throws JSONException, Exception { assertThat( JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString()) - .as("Response contains invalid self href") - .isEqualTo("http://localhost/rest/v1/softwaremodules/" + jvmCreated.getId()); - assertThat(JsonPath.compile("[1]_links.artifacts.href").read(mvcResult.getResponse().getContentAsString()) - .toString()).as("Response contains invalid artfacts href") - .isEqualTo("http://localhost/rest/v1/softwaremodules/" + jvmCreated.getId() + "/artifacts"); - - assertThat( - JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString()) .as("Response contains links self href") - .isEqualTo("http://localhost/rest/v1/softwaremodules/" + ahCreated.getId()); - assertThat(JsonPath.compile("[2]_links.artifacts.href").read(mvcResult.getResponse().getContentAsString()) + .isEqualTo("http://localhost/rest/v1/softwaremodules/" + appCreated.getId()); + assertThat(JsonPath.compile("[1]_links.artifacts.href").read(mvcResult.getResponse().getContentAsString()) .toString()).as("Response contains invalid artifacts href") - .isEqualTo("http://localhost/rest/v1/softwaremodules/" + ahCreated.getId() + "/artifacts"); + .isEqualTo("http://localhost/rest/v1/softwaremodules/" + appCreated.getId() + "/artifacts"); - assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Wrong softwaremodule size").hasSize(3); + assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Wrong softwaremodule size").hasSize(2); assertThat(softwareManagement.findSoftwareModulesByType(pageReq, osType.getId()).getContent().get(0).getName()) .as("Softwaremoudle name is wrong").isEqualTo(os.getName()); assertThat(softwareManagement.findSoftwareModulesByType(pageReq, osType.getId()).getContent().get(0) .getCreatedBy()).as("Softwaremoudle created by is wrong").isEqualTo("uploadTester"); assertThat(softwareManagement.findSoftwareModulesByType(pageReq, osType.getId()).getContent().get(0) .getCreatedAt()).as("Softwaremoudle created at is wrong").isGreaterThanOrEqualTo(current); - assertThat(softwareManagement.findSoftwareModulesByType(pageReq, runtimeType.getId()).getContent().get(0) - .getName()).as("Softwaremoudle name is wrong").isEqualTo(jvm.getName()); assertThat(softwareManagement.findSoftwareModulesByType(pageReq, appType.getId()).getContent().get(0).getName()) .as("Softwaremoudle name is wrong").isEqualTo(ah.getName()); } @@ -847,8 +725,7 @@ public void createSoftwareModules() throws JSONException, Exception { @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 = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); - sm = softwareManagement.createSoftwareModule(sm); + final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); final byte random[] = RandomStringUtils.random(5 * 1024).getBytes(); @@ -895,8 +772,7 @@ public void deleteAssignedSoftwareModule() throws Exception { @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 = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); - sm = softwareManagement.createSoftwareModule(sm); + final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); final byte random[] = RandomStringUtils.random(5 * 1024).getBytes(); @@ -933,8 +809,7 @@ public void createMetadata() throws Exception { final String knownKey2 = "knownKey1"; final String knownValue2 = "knownValue1"; - final SoftwareModule sm = softwareManagement - .createSoftwareModule(entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null)); + final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); final JSONArray jsonArray = new JSONArray(); jsonArray.put(new JSONObject().put("key", knownKey1).put("value", knownValue1)); @@ -962,10 +837,9 @@ public void updateMetadata() throws Exception { final String knownValue = "knownValue"; final String updateValue = "valueForUpdate"; - final SoftwareModule sm = softwareManagement - .createSoftwareModule(entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null)); - softwareManagement - .createSoftwareModuleMetadata(entityFactory.generateSoftwareModuleMetadata(sm, knownKey, knownValue)); + final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); + softwareManagement.createSoftwareModuleMetadata(sm.getId(), + entityFactory.generateMetadata(knownKey, knownValue)); final JSONObject jsonObject = new JSONObject().put("key", knownKey).put("value", updateValue); @@ -986,10 +860,9 @@ public void deleteMetadata() throws Exception { final String knownKey = "knownKey"; final String knownValue = "knownValue"; - final SoftwareModule sm = softwareManagement - .createSoftwareModule(entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null)); - softwareManagement - .createSoftwareModuleMetadata(entityFactory.generateSoftwareModuleMetadata(sm, knownKey, knownValue)); + final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); + softwareManagement.createSoftwareModuleMetadata(sm.getId(), + entityFactory.generateMetadata(knownKey, knownValue)); mvc.perform(delete("/rest/v1/softwaremodules/{swId}/metadata/{key}", sm.getId(), knownKey)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); @@ -1008,13 +881,11 @@ public void searchSoftwareModuleMetadataRsql() throws Exception { final int totalMetadata = 10; final String knownKeyPrefix = "knownKey"; final String knownValuePrefix = "knownValue"; - final SoftwareModule sm = softwareManagement - .createSoftwareModule(entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null)); + final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); for (int index = 0; index < totalMetadata; index++) { - softwareManagement.createSoftwareModuleMetadata( - entityFactory.generateSoftwareModuleMetadata(softwareManagement.findSoftwareModuleById(sm.getId()), - knownKeyPrefix + index, knownValuePrefix + index)); + softwareManagement.createSoftwareModuleMetadata(sm.getId(), + entityFactory.generateMetadata(knownKeyPrefix + index, knownValuePrefix + index)); } final String rsqlSearchValue1 = "value==knownValue1"; @@ -1029,9 +900,8 @@ private void createSoftwareModulesAlphabetical(final int amount) { char character = 'a'; for (int index = 0; index < amount; index++) { final String str = String.valueOf(character); - final SoftwareModule softwareModule = entityFactory.generateSoftwareModule(osType, str, str, str, str); - - softwareManagement.createSoftwareModule(softwareModule); + softwareManagement.createSoftwareModule(entityFactory.softwareModule().create().type(osType).name(str) + .description(str).vendor(str).version(str)); 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 893164a530..79cf18a478 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 @@ -26,7 +26,6 @@ import org.apache.commons.lang3.RandomStringUtils; 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.test.util.WithUser; import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest; @@ -57,10 +56,7 @@ 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( - entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5)); - testType.setDescription("Desc1234"); - testType = softwareManagement.updateSoftwareModuleType(testType); + final SoftwareModuleType testType = createTestType(); mvc.perform(get("/rest/v1/softwaremoduletypes").accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) @@ -95,14 +91,19 @@ public void getSoftwareModuleTypes() throws Exception { .andExpect(jsonPath("$.total", equalTo(4))); } + private SoftwareModuleType createTestType() { + SoftwareModuleType testType = softwareManagement.createSoftwareModuleType(entityFactory.softwareModuleType() + .create().key("test123").name("TestName123").description("Desc123").maxAssignments(5)); + testType = softwareManagement.updateSoftwareModuleType( + entityFactory.softwareModuleType().update(testType.getId()).description("Desc1234")); + return testType; + } + @Test @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( - entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5)); - testType.setDescription("Desc1234"); - testType = softwareManagement.updateSoftwareModuleType(testType); + final SoftwareModuleType testType = createTestType(); // descending mvc.perform(get("/rest/v1/softwaremoduletypes").accept(MediaType.APPLICATION_JSON) @@ -143,14 +144,15 @@ public void getSoftwareModuleTypesSortedByMaxAssignments() throws Exception { public void createSoftwareModuleTypesInvalidAssignmentBadRequest() throws JSONException, Exception { final List types = new ArrayList<>(); - types.add(entityFactory.generateSoftwareModuleType("test-1", "TestName-1", "Desc-1", -1)); + types.add(entityFactory.softwareModuleType().create().key("test-1").name("TestName-1").maxAssignments(-1) + .build()); mvc.perform(post("/rest/v1/softwaremoduletypes/").content(JsonBuilder.softwareModuleTypes(types)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()); types.clear(); - types.add(entityFactory.generateSoftwareModuleType("test0", "TestName0", "Desc0", 0)); + types.add(entityFactory.softwareModuleType().create().key("test0").name("TestName0").maxAssignments(0).build()); mvc.perform(post("/rest/v1/softwaremoduletypes/").content(JsonBuilder.softwareModuleTypes(types)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) @@ -162,10 +164,13 @@ public void createSoftwareModuleTypesInvalidAssignmentBadRequest() throws JSONEx @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes POST requests.") public void createSoftwareModuleTypes() throws JSONException, Exception { - final List types = new ArrayList<>(); - 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 List types = Lists.newArrayList( + entityFactory.softwareModuleType().create().key("test1").name("TestName1").description("Desc1") + .colour("col1‚").maxAssignments(1).build(), + entityFactory.softwareModuleType().create().key("test2").name("TestName2").description("Desc2") + .colour("col2‚").maxAssignments(2).build(), + entityFactory.softwareModuleType().create().key("test3").name("TestName3").description("Desc3") + .colour("col3‚").maxAssignments(3).build()); final MvcResult mvcResult = mvc .perform(post("/rest/v1/softwaremoduletypes/").content(JsonBuilder.softwareModuleTypes(types)) @@ -207,10 +212,7 @@ public void createSoftwareModuleTypes() throws JSONException, Exception { @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( - entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5)); - testType.setDescription("Desc1234"); - testType = softwareManagement.updateSoftwareModuleType(testType); + final SoftwareModuleType testType = createTestType(); mvc.perform(get("/rest/v1/softwaremoduletypes/{smtId}", testType.getId()).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) @@ -228,8 +230,7 @@ public void getSoftwareModuleType() throws Exception { @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( - entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5)); + final SoftwareModuleType testType = createTestType(); assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(4); @@ -243,10 +244,9 @@ public void deleteSoftwareModuleTypeUnused() throws Exception { @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( - entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5)); + final SoftwareModuleType testType = createTestType(); softwareManagement.createSoftwareModule( - entityFactory.generateSoftwareModule(testType, "name", "version", "description", "vendor")); + entityFactory.softwareModule().create().type(testType).name("name").version("version")); assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(4); @@ -259,8 +259,7 @@ public void deleteSoftwareModuleTypeUsed() throws Exception { @Test @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} PUT requests.") public void updateSoftwareModuleTypeOnlyDescriptionAndNameUntouched() throws Exception { - final SoftwareModuleType testType = softwareManagement.createSoftwareModuleType( - entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5)); + final SoftwareModuleType testType = createTestType(); final String body = new JSONObject().put("id", testType.getId()).put("description", "foobardesc") .put("name", "nameShouldNotBeChanged").toString(); @@ -315,8 +314,7 @@ public void getSoftwareModuleTypesWithPagingLimitAndOffsetRequestParameter() thr @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( - entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5)); + final SoftwareModuleType testType = createTestType(); final List types = Lists.newArrayList(testType); @@ -342,8 +340,8 @@ public void invalidRequestsOnSoftwaremoduleTypesResource() throws Exception { .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isBadRequest()); - final SoftwareModuleType toLongName = entityFactory.generateSoftwareModuleType("test123", - RandomStringUtils.randomAscii(80), "Desc123", 5); + final SoftwareModuleType toLongName = entityFactory.softwareModuleType().create().key("test123") + .name(RandomStringUtils.randomAscii(80)).build(); mvc.perform(post("/rest/v1/softwaremoduletypes") .content(JsonBuilder.softwareModuleTypes(Lists.newArrayList(toLongName))) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) @@ -366,10 +364,10 @@ public void invalidRequestsOnSoftwaremoduleTypesResource() throws Exception { @Test @Description("Search erquest of software module types.") public void searchSoftwareModuleTypeRsql() throws Exception { - final SoftwareModuleType testType = softwareManagement.createSoftwareModuleType( - entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5)); - final SoftwareModuleType testType2 = softwareManagement.createSoftwareModuleType( - entityFactory.generateSoftwareModuleType("test1234", "TestName1234", "Desc123", 5)); + softwareManagement.createSoftwareModuleType(entityFactory.softwareModuleType().create().key("test123") + .name("TestName123").description("Desc123").maxAssignments(5)); + softwareManagement.createSoftwareModuleType(entityFactory.softwareModuleType().create().key("test1234") + .name("TestName1234").description("Desc1234").maxAssignments(5)); final String rsqlFindLikeDs1OrDs2 = "name==TestName123,name==TestName1234"; @@ -384,9 +382,8 @@ private void createSoftwareModulesAlphabetical(final int amount) { char character = 'a'; for (int index = 0; index < amount; index++) { final String str = String.valueOf(character); - final SoftwareModule softwareModule = entityFactory.generateSoftwareModule(osType, str, str, str, str); - - softwareManagement.createSoftwareModule(softwareModule); + softwareManagement.createSoftwareModule(entityFactory.softwareModule().create().type(osType).name(str) + .description(str).vendor(str).version(str)); character++; } } diff --git a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryResourceTest.java index c020f087c5..2b7247caa0 100644 --- a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryResourceTest.java +++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryResourceTest.java @@ -128,10 +128,8 @@ public void updateTargetFilterQueryName() throws Exception { final String body = new JSONObject().put("name", filterName2).toString(); // prepare - TargetFilterQuery tfq = entityFactory.generateTargetFilterQuery(); - tfq.setName(filterName); - tfq.setQuery(filterQuery); - tfq = targetFilterQueryManagement.createTargetFilterQuery(tfq); + final TargetFilterQuery tfq = targetFilterQueryManagement.createTargetFilterQuery( + entityFactory.targetFilterQuery().create().name(filterName).query(filterQuery)); mvc.perform(put(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + tfq.getId()).content(body) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) @@ -319,11 +317,8 @@ public void deleteAutoAssignDistributionSetOfTargetFilterQuery() throws Exceptio final String dsName = "testDS"; final DistributionSet set = testdataFactory.createDistributionSet(dsName); - TargetFilterQuery tfq = entityFactory.generateTargetFilterQuery(); - tfq.setName(knownName); - tfq.setQuery(knownQuery); - tfq.setAutoAssignDistributionSet(set); - tfq = targetFilterQueryManagement.createTargetFilterQuery(tfq); + final TargetFilterQuery tfq = createSingleTargetFilterQuery(knownName, knownQuery); + targetFilterQueryManagement.updateTargetFilterQueryAutoAssignDS(tfq.getId(), set.getId()); assertThat(targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).getAutoAssignDistributionSet()) .isEqualTo(set); @@ -343,10 +338,8 @@ public void deleteAutoAssignDistributionSetOfTargetFilterQuery() throws Exceptio } private TargetFilterQuery createSingleTargetFilterQuery(final String name, final String query) { - final TargetFilterQuery target = entityFactory.generateTargetFilterQuery(); - target.setName(name); - target.setQuery(query); - return targetFilterQueryManagement.createTargetFilterQuery(target); + return targetFilterQueryManagement + .createTargetFilterQuery(entityFactory.targetFilterQuery().create().name(name).query(query)); } } 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 b35a211755..beb2d2e15f 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 @@ -8,7 +8,6 @@ */ package org.eclipse.hawkbit.mgmt.rest.resource; -import static com.google.common.collect.Lists.newArrayList; import static org.fest.assertions.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; @@ -25,7 +24,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -39,8 +37,6 @@ import org.eclipse.hawkbit.repository.ActionFields; import org.eclipse.hawkbit.repository.exception.ConstraintViolationException; 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; @@ -111,9 +107,8 @@ public void getActionStatusReturnsCorrectType() throws Exception { final int limitSize = 2; final String knownTargetId = "targetId"; final List actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId); - actions.get(0).setStatus(Status.FINISHED); - controllerManagament.addUpdateActionStatus(entityFactory.generateActionStatus(actions.get(0), Status.FINISHED, - System.currentTimeMillis(), "testmessage")); + controllerManagament.addUpdateActionStatus( + entityFactory.actionStatus().create(actions.get(0).getId()).status(Status.FINISHED).message("test")); final PageRequest pageRequest = new PageRequest(0, 1000, Direction.ASC, ActionFields.ID.getFieldName()); final ActionStatus status = deploymentManagement @@ -142,7 +137,7 @@ public void getActionStatusReturnsCorrectType() throws Exception { public void securityTokenIsNotInResponseIfMissingPermission() throws Exception { final String knownControllerId = "knownControllerId"; - targetManagement.createTarget(entityFactory.generateTarget(knownControllerId)); + testdataFactory.createTarget(knownControllerId); mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}", knownControllerId)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("securityToken").doesNotExist()); @@ -155,7 +150,7 @@ public void securityTokenIsNotInResponseIfMissingPermission() throws Exception { public void securityTokenIsInResponseWithCorrectPermission() throws Exception { final String knownControllerId = "knownControllerId"; - final Target createTarget = targetManagement.createTarget(entityFactory.generateTarget(knownControllerId)); + final Target createTarget = testdataFactory.createTarget(knownControllerId); mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}", knownControllerId)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("securityToken", equalTo(createTarget.getSecurityToken()))); @@ -186,11 +181,8 @@ public void addressAndIpAddressInTargetResult() throws Exception { } private void createTarget(final String controllerId) { - 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); + targetManagement.createTarget(entityFactory.target().create().controllerId(controllerId) + .address(IpUtil.createHttpUri("127.0.0.1").toString())); } @Test @@ -199,9 +191,9 @@ public void searchActionsRsql() throws Exception { // prepare test final DistributionSet dsA = testdataFactory.createDistributionSet(""); - final Target createTarget = targetManagement.createTarget(entityFactory.generateTarget("knownTargetId")); + final Target createTarget = testdataFactory.createTarget("knownTargetId"); - deploymentManagement.assignDistributionSet(dsA, Lists.newArrayList(createTarget)); + assignDistributionSet(dsA, Lists.newArrayList(createTarget)); final String rsqlPendingStatus = "status==pending"; final String rsqlFinishedStatus = "status==finished"; @@ -279,8 +271,8 @@ public void forceQuitAnCanceledActionReturnsOk() throws Exception { deploymentManagement.cancelAction(tA.getActions().get(0), tA); // find the current active action - final List cancelActions = deploymentManagement.findActionsByTarget(new PageRequest(0, 100), tA) - .getContent().stream().filter(action -> action.isCancelingOrCanceled()).collect(Collectors.toList()); + final List cancelActions = deploymentManagement.findActionsByTarget(pageReq, tA).getContent().stream() + .filter(Action::isCancelingOrCanceled).collect(Collectors.toList()); assertThat(cancelActions).hasSize(1); assertThat(cancelActions.get(0).isCancelingOrCanceled()).isTrue(); @@ -306,7 +298,7 @@ public void forceQuitAnNotCanceledActionReturnsMethodNotAllowed() throws Excepti @Description("Ensures that deletion is executed if permitted.") public void deleteTargetReturnsOK() throws Exception { final String knownControllerId = "knownControllerIdDelete"; - targetManagement.createTarget(entityFactory.generateTarget(knownControllerId)); + testdataFactory.createTarget(knownControllerId); mvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId)) .andExpect(status().isOk()); @@ -342,10 +334,8 @@ public void updateTargetDescription() throws Exception { final String body = new JSONObject().put("description", knownNewDescription).toString(); // prepare - final Target t = entityFactory.generateTarget(knownControllerId); - t.setDescription("old description"); - t.setName(knownNameNotModiy); - targetManagement.createTarget(t); + targetManagement.createTarget(entityFactory.target().create().controllerId(knownControllerId) + .name(knownNameNotModiy).description("old description")); mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content(body) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) @@ -367,9 +357,8 @@ public void updateTargetSecurityToken() throws Exception { final String body = new JSONObject().put("securityToken", knownNewToken).toString(); // prepare - final Target t = entityFactory.generateTarget(knownControllerId); - t.setName(knownNameNotModiy); - targetManagement.createTarget(t); + targetManagement + .createTarget(entityFactory.target().create().controllerId(knownControllerId).name(knownNameNotModiy)); mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content(body) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) @@ -391,9 +380,8 @@ public void updateTargetAddress() throws Exception { final String body = new JSONObject().put("address", knownNewAddress).toString(); // prepare - final Target t = entityFactory.generateTarget(knownControllerId); - t.setName(knownNameNotModiy); - targetManagement.createTarget(t); + targetManagement.createTarget(entityFactory.target().create().controllerId(knownControllerId) + .name(knownNameNotModiy).address(knownNewAddress)); mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content(body) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) @@ -578,7 +566,7 @@ public void getAssignedDistributionSetOfTarget() throws Exception { final String knownName = "someName"; createSingleTarget(knownControllerId, knownName); final DistributionSet ds = testdataFactory.createDistributionSet(""); - deploymentManagement.assignDistributionSet(ds.getId(), knownControllerId); + assignDistributionSet(ds.getId(), knownControllerId); // test @@ -674,12 +662,8 @@ public void createTargetWithBadPayloadBadRequest() throws Exception { @Test @Description("Verfies that a mandatory properties of new targets are validated as not null.") public void createTargetWithMissingMandatoryPropertyBadRequest() throws Exception { - final Target test1 = entityFactory.generateTarget("id1", "token"); - test1.setName(null); - final MvcResult mvcResult = mvc - .perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING) - .content(JsonBuilder.targets(Lists.newArrayList(test1), true)) + .perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING).content("[{\"name\":\"id1\"}]") .contentType(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()).andReturn(); @@ -695,13 +679,11 @@ public void createTargetWithMissingMandatoryPropertyBadRequest() throws Exceptio @Test @Description("Verfies that a properties of new targets are validated as in allowed size range.") public void createTargetWithInvalidPropertyBadRequest() throws Exception { - final Target test1 = entityFactory.generateTarget("id1", "token"); - test1.setName(RandomStringUtils.randomAscii(80)); + final Target test1 = entityFactory.target().create().controllerId("id1").name(RandomStringUtils.randomAscii(80)) + .build(); - final MvcResult mvcResult = mvc - .perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING) - .content(JsonBuilder.targets(Lists.newArrayList(test1), true)) - .contentType(MediaType.APPLICATION_JSON)) + final MvcResult mvcResult = mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING) + .content(JsonBuilder.targets(Lists.newArrayList(test1), true)).contentType(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()).andReturn(); assertThat(targetManagement.countTargetsAll()).isEqualTo(0); @@ -715,21 +697,14 @@ public void createTargetWithInvalidPropertyBadRequest() throws Exception { @Test public void createTargetsListReturnsSuccessful() throws Exception { - final Target test1 = entityFactory.generateTarget("id1", "token"); - test1.setDescription("testid1"); - test1.setName("testname1"); - test1.getTargetInfo().setAddress("amqp://test123/foobar"); - final Target test2 = entityFactory.generateTarget("id2"); - test2.setDescription("testid2"); - test2.setName("testname2"); - final Target test3 = entityFactory.generateTarget("id3"); - test3.setName("testname3"); - test3.setDescription("testid3"); - - final List targets = new ArrayList<>(); - targets.add(test1); - targets.add(test2); - targets.add(test3); + final Target test1 = entityFactory.target().create().controllerId("id1").name("testname1") + .securityToken("token").address("amqp://test123/foobar").description("testid1").build(); + final Target test2 = entityFactory.target().create().controllerId("id2").name("testname2") + .description("testid2").build(); + final Target test3 = entityFactory.target().create().controllerId("id3").name("testname3") + .description("testid3").build(); + + final List targets = Lists.newArrayList(test1, test2, test3); final MvcResult mvcResult = mvc .perform(post("/rest/v1/targets/").content(JsonBuilder.targets(targets, true)) @@ -850,8 +825,7 @@ public void createTargetsSingleEntryListWithAdditionalNotExistingTargetAttribute @Test public void getActionWithEmptyResult() throws Exception { final String knownTargetId = "targetId"; - final Target target = entityFactory.generateTarget(knownTargetId); - targetManagement.createTarget(target); + final Target target = testdataFactory.createTarget(knownTargetId); mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + MgmtRestConstants.TARGET_V1_ACTIONS)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) @@ -1063,22 +1037,19 @@ private String generateStatusreferenceLink(final String knownTargetId, final Act private List generateTargetWithTwoUpdatesWithOneOverride(final String knownTargetId) throws InterruptedException { - Target target = entityFactory.generateTarget(knownTargetId); - target = targetManagement.createTarget(target); - final List targets = new ArrayList<>(); - targets.add(target); + final Target target = testdataFactory.createTarget(knownTargetId); + final List targets = Lists.newArrayList(target); final Iterator sets = testdataFactory.createDistributionSets(2).iterator(); final DistributionSet one = sets.next(); final DistributionSet two = sets.next(); // Update - final List updatedTargets = deploymentManagement.assignDistributionSet(one, targets) - .getAssignedEntity(); + final List updatedTargets = assignDistributionSet(one, targets).getAssignedEntity(); // 2nd update // sleep 10ms to ensure that we can sort by reportedAt Thread.sleep(10); - deploymentManagement.assignDistributionSet(two, updatedTargets); + assignDistributionSet(two, updatedTargets); // two updates, one cancellation final List actions = deploymentManagement.findActionsByTarget(target); @@ -1108,7 +1079,7 @@ public void getUpdateAction() throws Exception { @Test public void assignDistributionSetToTarget() throws Exception { - targetManagement.createTarget(entityFactory.generateTarget("fsdfsd")); + testdataFactory.createTarget("fsdfsd"); final DistributionSet set = testdataFactory.createDistributionSet("one"); mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS") @@ -1121,7 +1092,7 @@ public void assignDistributionSetToTarget() throws Exception { @Test public void assignDistributionSetToTargetWithActionTimeForcedAndTime() throws Exception { - final Target target = targetManagement.createTarget(entityFactory.generateTarget("fsdfsd")); + final Target target = testdataFactory.createTarget("fsdfsd"); final DistributionSet set = testdataFactory.createDistributionSet("one"); final long forceTime = System.currentTimeMillis(); @@ -1148,7 +1119,7 @@ public void invalidRequestsOnAssignDistributionSetToTarget() throws Exception { .content("{\"id\":" + set.getId() + "}").contentType(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound()); - targetManagement.createTarget(entityFactory.generateTarget("fsdfsd")); + testdataFactory.createTarget("fsdfsd"); mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS") .content("{\"id\":" + set.getId() + "}").contentType(MediaType.APPLICATION_JSON)) @@ -1238,8 +1209,7 @@ public void getControllerAttributesViaTargetResourceReturnsAttributesWithOk() th final Map knownControllerAttrs = new HashMap<>(); knownControllerAttrs.put("a", "1"); knownControllerAttrs.put("b", "2"); - final Target target = entityFactory.generateTarget(knownTargetId); - targetManagement.createTarget(target); + final Target target = testdataFactory.createTarget(knownTargetId); controllerManagament.updateControllerAttributes(knownTargetId, knownControllerAttrs); // test query target over rest resource @@ -1252,8 +1222,7 @@ public void getControllerAttributesViaTargetResourceReturnsAttributesWithOk() th public void getControllerEmptyAttributesReturnsNoContent() throws Exception { // create target with attributes final String knownTargetId = "targetIdWithAttributes"; - final Target target = entityFactory.generateTarget(knownTargetId); - targetManagement.createTarget(target); + final Target target = testdataFactory.createTarget(knownTargetId); // test query target over rest resource mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/attributes")) @@ -1286,10 +1255,8 @@ private String getCreateTargetsListJsonStringWithAdditionalNotExistingAttribute( } private Target createSingleTarget(final String controllerId, final String name) { - final Target target = entityFactory.generateTarget(controllerId); - target.setName(name); - target.setDescription(TARGET_DESCRIPTION_TEST); - targetManagement.createTarget(target); + targetManagement.createTarget(entityFactory.target().create().controllerId(controllerId).name(name) + .description(TARGET_DESCRIPTION_TEST)); return controllerManagament.updateLastTargetQuery(controllerId, null); } @@ -1304,10 +1271,7 @@ private void createTargetsAlphabetical(final int amount) { char character = 'a'; for (int index = 0; index < amount; index++) { final String str = String.valueOf(character); - final Target target = entityFactory.generateTarget(str); - target.setName(str); - target.setDescription(str); - targetManagement.createTarget(target); + targetManagement.createTarget(entityFactory.target().create().controllerId(str).name(str).description(str)); controllerManagament.updateLastTargetQuery(str, null); character++; } @@ -1318,10 +1282,8 @@ private void createTargetsAlphabetical(final int amount) { * */ private void feedbackToByInSync(final Long actionId) { - final Action action = deploymentManagement.findAction(actionId); - - final ActionStatus actionStatus = entityFactory.generateActionStatus(action, Status.FINISHED, 0L); - controllerManagement.addUpdateActionStatus(actionStatus); + controllerManagement + .addUpdateActionStatus(entityFactory.actionStatus().create(actionId).status(Status.FINISHED)); } /** @@ -1332,10 +1294,9 @@ private void feedbackToByInSync(final Long actionId) { private Target createTargetAndStartAction() { // prepare test final DistributionSet dsA = testdataFactory.createDistributionSet(""); - final Target tA = targetManagement - .createTarget(testdataFactory.generateTarget("target-id-A", "first description")); + final Target tA = testdataFactory.createTarget("target-id-A"); // assign a distribution set so we get an active update action - deploymentManagement.assignDistributionSet(dsA, newArrayList(tA)); + assignDistributionSet(dsA, Lists.newArrayList(tA)); // verify active action final Slice actionsByTarget = deploymentManagement.findActionsByTarget(new PageRequest(0, 100), tA); assertThat(actionsByTarget.getContent()).hasSize(1); diff --git a/hawkbit-mgmt-resource/src/test/resources/application-test.properties b/hawkbit-mgmt-resource/src/test/resources/application-test.properties index 3b4a31adf8..c03a084d73 100644 --- a/hawkbit-mgmt-resource/src/test/resources/application-test.properties +++ b/hawkbit-mgmt-resource/src/test/resources/application-test.properties @@ -7,6 +7,7 @@ # http://www.eclipse.org/legal/epl-v10.html # +#logging.level.org.eclipse.hawkbit.rest.util.MockMvcResultPrinter=DEBUG logging.level.=INFO logging.level.org.eclipse.persistence=ERROR 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 index 93ac1a7d65..a1740c8792 100644 --- 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 @@ -64,30 +64,6 @@ public interface ArtifactManagement { Artifact createArtifact(@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 Artifact} - * - * @throw ArtifactUploadFailedException if upload fails - */ - @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - Artifact createArtifact(@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}. @@ -103,7 +79,7 @@ Artifact createArtifact(@NotNull InputStream inputStream, @NotNull Long moduleId * @param providedMd5Sum * optional md5 checksum to check the new file against * @param overrideExisting - * to true if the artifact binary can be overdiden + * to true if the artifact binary can be overridden * if it already exists * @param contentType * the contentType of the file 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 index b5b39ff595..f4e382909f 100644 --- 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 @@ -9,13 +9,13 @@ package org.eclipse.hawkbit.repository; import java.net.URI; -import java.util.List; import java.util.Map; import java.util.Optional; import javax.validation.constraints.NotNull; import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; +import org.eclipse.hawkbit.repository.builder.ActionStatusCreate; import org.eclipse.hawkbit.repository.event.remote.DownloadProgressEvent; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; @@ -44,16 +44,22 @@ 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 + * @param create * to be added - * @return the persisted {@link Action} + * @return the updated {@link Action} * * @throws EntityAlreadyExistsException * if a given entity already exists * + * @throws TooManyStatusEntriesException + * if more than the allowed number of status entries are + * inserted + * @throws EntityNotFoundException + * if given action does not exist + * */ @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) - Action addCancelActionStatus(@NotNull ActionStatus actionStatus); + Action addCancelActionStatus(@NotNull ActionStatusCreate create); /** * Sends the download progress and notifies the event publisher with a @@ -75,19 +81,25 @@ public interface ControllerManagement { * Simple addition of a new {@link ActionStatus} entry to the {@link Action} * . No state changes. * - * @param statusMessage + * @param create * to add to the action * - * @return create {@link ActionStatus} entity + * @return created {@link ActionStatus} entity + * + * @throws TooManyStatusEntriesException + * if more than the allowed number of status entries are + * inserted + * @throws EntityNotFoundException + * if given action does not exist */ @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) - ActionStatus addInformationalActionStatus(@NotNull ActionStatus statusMessage); + ActionStatus addInformationalActionStatus(@NotNull ActionStatusCreate create); /** * Adds an {@link ActionStatus} entry for an update {@link Action} including * potential state changes for the target and the {@link Action} itself. * - * @param actionStatus + * @param create * to be added * @return the updated {@link Action} * @@ -96,20 +108,12 @@ public interface ControllerManagement { * @throws TooManyStatusEntriesException * if more than the allowed number of status entries are * inserted + * @throws TooManyStatusEntriesException + * 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 findActiveActionByTarget(@NotNull Target target); + Action addUpdateActionStatus(@NotNull ActionStatusCreate create); /** * Retrieves oldest {@link Action} that is active and assigned to a 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 index 36ba6df24e..53f3a07b3f 100644 --- 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 @@ -44,26 +44,6 @@ */ 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}. @@ -75,17 +55,20 @@ DistributionSetAssignmentResult assignDistributionSet(@NotNull DistributionSet p * @param forcedTimestamp * the time when the action should be forced, only necessary for * {@link ActionType#TIMEFORCED} - * @param targetIDs + * @param controllerIDs * 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}. + * + * @throw {@link EntityNotFoundException} if either provided + * {@link DistributionSet} or {@link Target}s do not exist */ @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); + DistributionSetAssignmentResult assignDistributionSet(@NotNull Long dsID, @NotNull ActionType actionType, + long forcedTimestamp, @NotEmpty Collection controllerIDs); /** * method assigns the {@link DistributionSet} to all {@link Target}s by @@ -100,6 +83,9 @@ DistributionSetAssignmentResult assignDistributionSet(@NotNull final Long dsID, * @throw IncompleteDistributionSetException if mandatory * {@link SoftwareModuleType} are not assigned as define by the * {@link DistributionSetType}. + * + * @throw {@link EntityNotFoundException} if either provided + * {@link DistributionSet} or {@link Target}s do not exist */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET) DistributionSetAssignmentResult assignDistributionSet(@NotNull Long dsID, @@ -120,11 +106,13 @@ DistributionSetAssignmentResult assignDistributionSet(@NotNull Long dsID, * @throw IncompleteDistributionSetException if mandatory * {@link SoftwareModuleType} are not assigned as define by the * {@link DistributionSetType}. + * + * @throw {@link EntityNotFoundException} if either provided + * {@link DistributionSet} or {@link Target}s do not exist */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET) DistributionSetAssignmentResult assignDistributionSet(@NotNull Long dsID, - @NotEmpty Collection targets, - String actionMessage); + @NotEmpty Collection targets, String actionMessage); /** * method assigns the {@link DistributionSet} to all {@link Target}s by @@ -143,34 +131,14 @@ DistributionSetAssignmentResult assignDistributionSet(@NotNull Long dsID, * @throw IncompleteDistributionSetException if mandatory * {@link SoftwareModuleType} are not assigned as define by the * {@link DistributionSetType}. + * + * @throw {@link EntityNotFoundException} if either provided + * {@link DistributionSet} or {@link Target}s do not exist */ @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, @@ -275,7 +243,7 @@ void createScheduledAction(@NotEmpty Collection targets, @NotNull Distri */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) List findActionsByRolloutAndStatus(@NotNull Rollout rollout, @NotNull Action.Status actionStatus); - + /** * Retrieves all {@link Action}s of a specific target. * @@ -407,19 +375,6 @@ void createScheduledAction(@NotEmpty Collection targets, @NotNull Distri @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. @@ -431,19 +386,6 @@ void createScheduledAction(@NotEmpty Collection targets, @NotNull Distri @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. 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 index 1de51fad9c..6744ce5d5c 100644 --- 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 @@ -10,17 +10,21 @@ 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.builder.DistributionSetCreate; +import org.eclipse.hawkbit.repository.builder.DistributionSetTypeCreate; +import org.eclipse.hawkbit.repository.builder.DistributionSetTypeUpdate; +import org.eclipse.hawkbit.repository.builder.DistributionSetUpdate; 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.exception.UnsupportedSoftwareModuleForThisDistributionSetException; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetFilter; @@ -29,10 +33,12 @@ 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.MetaData; 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.TargetInfo; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -47,14 +53,27 @@ public interface DistributionSetManagement { /** * Assigns {@link SoftwareModule} to existing {@link DistributionSet}. * - * @param ds + * @param setId * to assign and update - * @param softwareModules + * @param moduleIds * to get assigned * @return the updated {@link DistributionSet}. + * + * @throws EntityNotFoundException + * if given module does not exist + * + * @throws EntityReadOnlyException + * if use tries to change the {@link DistributionSet} s while + * the DS is already in use. + * + * @throws UnsupportedSoftwareModuleForThisDistributionSetException + * is {@link SoftwareModule#getType()} is not supported by this + * {@link DistributionSet#getType()}. + * + * */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - DistributionSet assignSoftwareModules(@NotNull DistributionSet ds, Set softwareModules); + DistributionSet assignSoftwareModules(@NotNull Long setId, @NotEmpty Collection moduleIds); /** * Assign a {@link DistributionSetTag} assignment to given @@ -99,84 +118,92 @@ public interface DistributionSetManagement { /** * Creates a new {@link DistributionSet}. * - * @param dSet + * @param create * {@link DistributionSet} to be created * @return the new persisted {@link DistributionSet} * - * @throws EntityAlreadyExistsException - * if a given entity already exists + * @throws EntityNotFoundException + * if a provided linked entity does not exists + * ({@link DistributionSet#getModules()} or + * {@link DistributionSet#getType()}) * @throws DistributionSetCreationFailedMissingMandatoryModuleException * is {@link DistributionSet} does not contain mandatory * {@link SoftwareModule}s. */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - DistributionSet createDistributionSet(@NotNull DistributionSet dSet); + DistributionSet createDistributionSet(@NotNull DistributionSetCreate create); /** * creates a list of distribution set meta data entries. * + * @param dsId + * if the {@link DistributionSet} the metadata has to be created + * for * @param metadata * the meta data entries to create or update * @return the updated or created distribution set meta data entries + * + * @throws EntityNotFoundException + * if given set does not exist * @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); + List createDistributionSetMetadata(@NotNull Long dsId, + @NotEmpty Collection metadata); /** * Creates multiple {@link DistributionSet}s. * - * @param distributionSets + * @param creates * to be created * @return the new {@link DistributionSet}s - * @throws EntityAlreadyExistsException - * if a given entity already exists + * @throws EntityNotFoundException + * if a provided linked entity does not exists + * ({@link DistributionSet#getModules()} or + * {@link DistributionSet#getType()}) * @throws DistributionSetCreationFailedMissingMandatoryModuleException * is {@link DistributionSet} does not contain mandatory * {@link SoftwareModule}s. */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - List createDistributionSets(@NotNull Collection distributionSets); + List createDistributionSets(@NotNull Collection creates); /** * Creates new {@link DistributionSetType}. * - * @param type + * @param create * to create - * @return created {@link Entity} + * @return created entity + * + * @throws EntityNotFoundException + * if a provided linked entity does not exists + * ({@link DistributionSetType#getMandatoryModuleTypes()} or + * {@link DistributionSetType#getOptionalModuleTypes()} */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - DistributionSetType createDistributionSetType(@NotNull DistributionSetType type); + DistributionSetType createDistributionSetType(@NotNull DistributionSetTypeCreate create); /** * Creates multiple {@link DistributionSetType}s. * - * @param types + * @param creates * to create - * @return created {@link Entity} + * @return created entity + * + * @throws EntityNotFoundException + * if a provided linked entity does not exists + * ({@link DistributionSetType#getMandatoryModuleTypes()} or + * {@link DistributionSetType#getOptionalModuleTypes()} */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - List createDistributionSetTypes(@NotNull Collection types); + List createDistributionSetTypes(@NotNull Collection creates); /** *

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

* *

@@ -193,8 +220,8 @@ public interface DistributionSetManagement { /** * 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. + * delete of the entities have been linked to an {@link Action} before or a + * hard delete if not. * * @param distributionSetIDs * to be deleted @@ -205,13 +232,16 @@ public interface DistributionSetManagement { /** * deletes a distribution set meta data entry. * - * @param distributionSet + * @param dsId * where meta data has to be deleted * @param key * of the meta data element + * + * @throws EntityNotFoundException + * if given set does not exist */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - void deleteDistributionSetMetadata(@NotNull final DistributionSet distributionSet, @NotNull final String key); + void deleteDistributionSetMetadata(@NotNull final Long dsId, @NotNull final String key); /** * Deletes or mark as delete in case the type is in use. @@ -234,7 +264,7 @@ public interface DistributionSetManagement { /** * Find {@link DistributionSet} based on given ID without details, e.g. - * {@link DistributionSet#getAgentHub()}. + * {@link DistributionSet#getModules()}. * * @param distid * to look for. @@ -245,7 +275,7 @@ public interface DistributionSetManagement { /** * Find {@link DistributionSet} based on given ID including (lazy loaded) - * details, e.g. {@link DistributionSet#getAgentHub()}. + * details, e.g. {@link DistributionSet#getModules()}. * * Note: for performance reasons it is recommended to use * {@link #findDistributionSetById(Long)} if details are not necessary. @@ -319,9 +349,6 @@ Page findDistributionSetMetadataByDistributionSetId(@No * 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 @@ -343,9 +370,6 @@ Page findDistributionSetMetadataByDistributionSetId(@No * 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 @@ -363,9 +387,9 @@ Page findDistributionSetsByDeletedAndOrCompleted(@NotNull Pagea * 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 + * returned. If FALSE, on {@link DistributionSet}s not marked as + * deleted are returned. null if both are to be + * returned * @return all found {@link DistributionSet}s * * @throws RSQLParameterUnsupportedFieldException @@ -383,7 +407,7 @@ Page findDistributionSetsAll(@NotNull String rsqlParam, @NotNul * following order: *

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

* 2) {@link DistributionSet}s which have the given {@link Target} as * {@link Target#getAssignedDistributionSet()} @@ -397,7 +421,7 @@ Page findDistributionSetsAll(@NotNull String rsqlParam, @NotNul * has details of filters to be applied * @param assignedOrInstalled * the controllerID of the Target to be ordered by - * @return + * @return {@link DistributionSet}s */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) Page findDistributionSetsAllOrderedByLinkTarget(@NotNull Pageable pageable, @@ -471,8 +495,8 @@ Page findDistributionSetsByFilters(@NotNull Pageable pageable, /** * finds a single distribution set meta data by its id. * - * @param distributionSet - * where meta data has to rind + * @param setId + * of the {@link DistributionSet} * @param key * of the meta data element * @return the found DistributionSetMetadata or {@code null} if not exits @@ -480,7 +504,7 @@ Page findDistributionSetsByFilters(@NotNull Pageable pageable, * in case the meta data does not exists for the given key */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - DistributionSetMetadata findOne(@NotNull DistributionSet distributionSet, @NotEmpty String key); + DistributionSetMetadata findDistributionSetMetadata(@NotNull Long setId, @NotEmpty String key); /** * Checks if a {@link DistributionSet} is currently in use by a target in @@ -495,7 +519,7 @@ Page findDistributionSetsByFilters(@NotNull Pageable pageable, boolean isDistributionSetInUse(@NotNull DistributionSet distributionSet); /** - * {@link Entity} based method call for + * entity based method call for * {@link #toggleTagAssignment(Collection, String)}. * * @param sets @@ -540,14 +564,21 @@ DistributionSetTagAssignmentResult toggleTagAssignment(@NotEmpty Collectionnull - * @throw DataDependencyViolationException in case of illegal update + * + * @return the saved entity. + * + * @throws EntityNotFoundException + * if given set does not exist + * @throws EntityReadOnlyException + * if user tries to change requiredMigrationStep or type on a DS + * that is already assigned to targets */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - DistributionSet updateDistributionSet(@NotNull DistributionSet ds); + DistributionSet updateDistributionSet(@NotNull DistributionSetUpdate update); /** * updates a distribution set meta data value if corresponding entry exists. * - * @param metadata - * the meta data entry to be updated + * @param dsId + * {@link DistributionSet} of the meta data entry to be updated + * @param md + * 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); + DistributionSetMetadata updateDistributionSetMetadata(@NotNull Long dsId, @NotNull MetaData md); /** - * 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. + * Updates existing {@link DistributionSetType}. Resets assigned + * {@link SoftwareModuleType}s as well and sets as provided. * - * @param dsType + * @param update * to update - * @return updated {@link Entity} - * + * + * @return updated entity + * + * @throws EntityNotFoundException + * in case the {@link DistributionSetType} does not exists and + * cannot be updated + * + * @throws EntityReadOnlyException + * if the {@link DistributionSetType} is already in use by a + * {@link DistributionSet} and user tries to change list of + * {@link SoftwareModuleType}s + */ + @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) + DistributionSetType updateDistributionSetType(@NotNull DistributionSetTypeUpdate update); + + /** + * Unassigns a {@link SoftwareModuleType} from the + * {@link DistributionSetType}. Does nothing if {@link SoftwareModuleType} + * has not been assigned in the first place. + * + * @param dsTypeId + * to update + * @param softwareModuleId + * to unassign + * @return updated {@link DistributionSetType} + * + * @throws EntityNotFoundException + * in case the {@link DistributionSetType} does not exist + * + * @throws EntityReadOnlyException + * if the {@link DistributionSetType} while it is already in use + * by a {@link DistributionSet} + */ + @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) + DistributionSetType unassignSoftwareModuleType(@NotNull Long dsTypeId, @NotNull Long softwareModuleId); + + /** + * Assigns {@link DistributionSetType#getMandatoryModuleTypes()}. + * + * @param dsTypeId + * to update + * @param softwareModuleTypeIds + * to assign + * @return updated {@link DistributionSetType} + * + * @throws EntityNotFoundException + * in case the {@link DistributionSetType} or at least one of + * the {@link SoftwareModuleType}s do not exist + * + * @throws EntityReadOnlyException + * if the {@link DistributionSetType} while it is already in use + * by a {@link DistributionSet} + */ + @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) + DistributionSetType assignOptionalSoftwareModuleTypes(@NotNull Long dsTypeId, + @NotEmpty Collection softwareModuleTypeIds); + + /** + * Assigns {@link DistributionSetType#getOptionalModuleTypes()}. + * + * @param dsTypeId + * to update + * @param softwareModuleTypes + * to assign + * @return updated {@link DistributionSetType} + * + * @throws EntityNotFoundException + * in case the {@link DistributionSetType} or at least one of + * the {@link SoftwareModuleType}s do not exist + * * @throws EntityReadOnlyException - * if use tries to change the {@link DistributionSetTypeElement} - * s while the DS type is already in use. + * if the {@link DistributionSetType} while it is already in use + * by a {@link DistributionSet} */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - DistributionSetType updateDistributionSetType(@NotNull DistributionSetType dsType); + DistributionSetType assignMandatorySoftwareModuleTypes(@NotNull Long dsTypeId, + @NotEmpty Collection softwareModuleTypes); } 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 index 0bbdcbcee7..d0036c4d25 100644 --- 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 @@ -8,28 +8,20 @@ */ package org.eclipse.hawkbit.repository; -import java.util.Collection; -import java.util.concurrent.TimeUnit; - import javax.validation.constraints.NotNull; -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.builder.ActionStatusBuilder; +import org.eclipse.hawkbit.repository.builder.DistributionSetBuilder; +import org.eclipse.hawkbit.repository.builder.DistributionSetTypeBuilder; +import org.eclipse.hawkbit.repository.builder.RolloutBuilder; +import org.eclipse.hawkbit.repository.builder.RolloutGroupBuilder; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleBuilder; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeBuilder; +import org.eclipse.hawkbit.repository.builder.TagBuilder; +import org.eclipse.hawkbit.repository.builder.TargetBuilder; +import org.eclipse.hawkbit.repository.builder.TargetFilterQueryBuilder; 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.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.eclipse.hawkbit.repository.model.MetaData; import org.hibernate.validator.constraints.NotEmpty; /** @@ -40,346 +32,65 @@ 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(@NotNull Action action, @NotNull 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(@NotNull Action action, @NotNull 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(@NotNull Action action, @NotNull 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(@NotNull String name, @NotNull String version, String description, - @NotNull 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(@NotNull DistributionSet distributionSet, - @NotNull 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(@NotNull 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 + * @return {@link ActionStatusBuilder} object */ - DistributionSetTag generateDistributionSetTag(@NotNull String name, String description, String colour); + ActionStatusBuilder actionStatus(); /** - * Generates an empty {@link DistributionSetType} without persisting it. - * - * @return {@link DistributionSetType} object + * @return {@link DistributionSetBuilder} object */ - DistributionSetType generateDistributionSetType(); + DistributionSetBuilder distributionSet(); /** - * Generates a {@link DistributionSetType} without persisting it. + * Generates an {@link MetaData} element without persisting it. * * @param key - * {@link DistributionSetType#getKey()} - * @param name - * {@link DistributionSetType#getName()} - * @param description - * {@link DistributionSetType#getDescription()} - * - * @return {@link DistributionSetType} object - */ - DistributionSetType generateDistributionSetType(@NotNull String key, @NotNull 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(@NotNull SoftwareModuleType type, @NotNull String name, - @NotNull 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()} + * {@link MetaData#getKey()} * @param value - * {@link SoftwareModuleMetadata#getValue()} + * {@link MetaData#getValue()} * - * @return {@link SoftwareModuleMetadata} object + * @return {@link MetaData} object */ - SoftwareModuleMetadata generateSoftwareModuleMetadata(@NotNull SoftwareModule softwareModule, @NotNull String key, - String value); + MetaData generateMetadata(@NotEmpty String key, @NotNull String value); /** - * Generates an empty {@link SoftwareModuleType} without persisting it. - * - * @return {@link SoftwareModuleType} object + * @return {@link TagBuilder} object */ - SoftwareModuleType generateSoftwareModuleType(); + TagBuilder tag(); /** - * 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 + * @return {@link RolloutGroupBuilder} object */ - SoftwareModuleType generateSoftwareModuleType(@NotNull String key, @NotNull String name, String description, - int maxAssignments); + RolloutGroupBuilder rolloutGroup(); /** - * Generates an empty {@link Target} without persisting it. - * {@link Target#getSecurityToken()} is generated. - * - * @param controllerID - * of the {@link Target} - * - * @return {@link Target} object + * @return {@link DistributionSetTypeBuilder} object */ - Target generateTarget(@NotEmpty String controllerID); + DistributionSetTypeBuilder distributionSetType(); /** - * Generates an empty {@link Target} without persisting it. - * - * @param controllerID - * of the {@link Target} - * @param securityToken - * of the {@link Target} for authentication if enabled on tenant. - * Generates one if empty or null. - * - * @return {@link Target} object + * @return {@link RolloutBuilder} object */ - Target generateTarget(@NotEmpty String controllerID, String securityToken); + RolloutBuilder rollout(); /** - * Generates an empty {@link TargetFilterQuery} without persisting it. - * - * @return {@link TargetFilterQuery} object + * @return {@link SoftwareModuleBuilder} object */ - TargetFilterQuery generateTargetFilterQuery(); + SoftwareModuleBuilder softwareModule(); /** - * Generates an {@link TargetFilterQuery} without persisting it. - * - * @param name - * name for the filter - * @param query - * query of the filter - * @return {@link TargetFilterQuery} object + * @return {@link SoftwareModuleTypeBuilder} object */ - TargetFilterQuery generateTargetFilterQuery(String name, String query); + SoftwareModuleTypeBuilder softwareModuleType(); /** - * Generates an {@link TargetFilterQuery} without persisting it. - * - * @param name - * name for the filter - * @param query - * query of the filter - * @param autoAssignDS - * auto assign distribution set - * @return {@link TargetFilterQuery} object + * @return {@link TargetBuilder} object */ - TargetFilterQuery generateTargetFilterQuery(String name, String query, DistributionSet autoAssignDS); + TargetBuilder target(); /** - * 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(@NotNull 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(@NotNull String name, String description, String colour); - - /** - * Generates an empty {@link Artifact} without persisting it. - * - * @return {@link Artifact} object + * @return {@link TargetFilterQueryBuilder} object */ - Artifact generateArtifact(); + TargetFilterQueryBuilder targetFilterQuery(); } diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/OffsetBasedPageRequest.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/OffsetBasedPageRequest.java index bf7807db08..2617f292ec 100644 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/OffsetBasedPageRequest.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/OffsetBasedPageRequest.java @@ -83,10 +83,7 @@ public boolean equals(final Object obj) { return false; } final OffsetBasedPageRequest other = (OffsetBasedPageRequest) obj; - if (offset != other.offset) { - return false; - } - return true; + return offset == other.offset; } } 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 index 127e9565d4..732d5644f8 100644 --- 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 @@ -8,12 +8,20 @@ */ 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.builder.RolloutCreate; +import org.eclipse.hawkbit.repository.builder.RolloutGroupCreate; +import org.eclipse.hawkbit.repository.builder.RolloutUpdate; +import org.eclipse.hawkbit.repository.exception.ConstraintViolationException; +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.exception.RolloutIllegalStateException; +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; @@ -25,8 +33,6 @@ import org.springframework.data.domain.Slice; import org.springframework.security.access.prepost.PreAuthorize; -import java.util.List; - /** * RolloutManagement to control rollouts e.g. like creating, starting, resuming * and pausing rollouts. This service secures all the functionality based on the @@ -123,7 +129,7 @@ public interface RolloutManagement { * to {@link RolloutStatus#READY} so it can be started with * {@link #startRollout(Rollout)}. * - * @param rollout + * @param create * the rollout entity to create * @param amountGroup * the amount of groups to split the rollout into @@ -132,11 +138,13 @@ public interface RolloutManagement { * applied for each {@link RolloutGroup} * @return the persisted rollout. * - * @throws IllegalArgumentException - * in case the given groupSize is zero or lower. + * @throws EntityNotFoundException + * if given {@link DistributionSet} does not exist + * @throws ConstraintViolationException + * if rollout or group parameters are invalid */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE) - Rollout createRollout(@NotNull Rollout rollout, int amountGroup, @NotNull RolloutGroupConditions conditions); + Rollout createRollout(@NotNull RolloutCreate create, int amountGroup, @NotNull RolloutGroupConditions conditions); /** * Persists a new rollout entity. The filter within the @@ -164,11 +172,14 @@ public interface RolloutManagement { * RolloutGroup itself * @return the persisted rollout. * - * @throws IllegalArgumentException - * in case the given groupSize is zero or lower. + * @throws EntityNotFoundException + * if given {@link DistributionSet} does not exist + * @throws ConstraintViolationException + * if rollout or group parameters are invalid */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE) - Rollout createRollout(@NotNull Rollout rollout, @NotNull List groups, RolloutGroupConditions conditions); + Rollout createRollout(@NotNull RolloutCreate rollout, @NotNull List groups, + RolloutGroupConditions conditions); /** * Can be called on a Rollout in {@link RolloutStatus#CREATING} to @@ -184,8 +195,8 @@ public interface RolloutManagement { * @param rollout * the rollout */ - void fillRolloutGroupsWithTargets(final Rollout rollout); - + @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE) + void fillRolloutGroupsWithTargets(@NotNull Long rollout); /** * Retrieves all rollouts. @@ -344,12 +355,16 @@ public interface RolloutManagement { /** * Update rollout details. * - * @param rollout + * @param update * rollout to be updated + * @param name + * to update or null + * @param description + * to update or null * * @return Rollout updated rollout */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE) - Rollout updateRollout(@NotNull Rollout rollout); + Rollout updateRollout(@NotNull RolloutUpdate update); } 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 index d65411a59a..20cf7e7bdc 100644 --- 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 @@ -14,12 +14,17 @@ import javax.validation.constraints.NotNull; import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleCreate; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeCreate; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeUpdate; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleUpdate; 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.MetaData; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; @@ -67,29 +72,31 @@ public interface SoftwareManagement { /** * Create {@link SoftwareModule}s in the repository. * - * @param swModules + * @param creates * {@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); + List createSoftwareModule(@NotNull Collection creates); /** * - * @param swModule + * @param create * SoftwareModule to create * @return SoftwareModule * @throws EntityAlreadyExistsException * if a given entity already exists */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - SoftwareModule createSoftwareModule(@NotNull SoftwareModule swModule); + SoftwareModule createSoftwareModule(@NotNull SoftwareModuleCreate create); /** * creates a list of software module meta data entries. - * + * + * @param moduleId + * the metadata belongs to * @param metadata * the meta data entries to create or update * @return the updated or created software module meta data entries @@ -98,11 +105,14 @@ public interface SoftwareManagement { * specific key */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - List createSoftwareModuleMetadata(@NotNull Collection metadata); + List createSoftwareModuleMetadata(@NotNull Long moduleId, + @NotNull Collection metadata); /** * creates or updates a single software module meta data entry. - * + * + * @param moduleId + * the metadata belongs to * @param metadata * the meta data entry to create or update * @return the updated or created software module meta data entry @@ -111,27 +121,27 @@ public interface SoftwareManagement { * key */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - SoftwareModuleMetadata createSoftwareModuleMetadata(@NotNull SoftwareModuleMetadata metadata); + SoftwareModuleMetadata createSoftwareModuleMetadata(@NotNull Long moduleId, @NotNull MetaData metadata); /** * Creates multiple {@link SoftwareModuleType}s. * - * @param types + * @param creates * to create * @return created Entity */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - List createSoftwareModuleType(@NotNull Collection types); + List createSoftwareModuleType(@NotNull Collection creates); /** * Creates new {@link SoftwareModuleType}. * - * @param type + * @param create * to create * @return created Entity */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - SoftwareModuleType createSoftwareModuleType(@NotNull SoftwareModuleType type); + SoftwareModuleType createSoftwareModuleType(@NotNull SoftwareModuleTypeCreate create); /** * Deletes the given {@link SoftwareModule} Entity. @@ -198,6 +208,17 @@ public interface SoftwareManagement { @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) Slice findSoftwareModuleByFilters(@NotNull Pageable pageable, String searchText, Long typeId); + /** + * Finds {@link SoftwareModuleType} by given id. + * + * @param ids + * to search for + * @return the found {@link SoftwareModuleType}s + */ + @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR + + SpringEvalExpressions.IS_CONTROLLER) + List findSoftwareModuleTypesById(@NotEmpty Collection ids); + /** * Finds {@link SoftwareModule} by given id. * @@ -412,46 +433,57 @@ Slice findSoftwareModuleOrderBySetAssignmentAndModuleNam * {@link SoftwareModule#getDescription()} * {@link SoftwareModule#getVendor()}. * - * @param sm + * @param moduleId * to update + * @param description + * to update or null + * @param vendor + * to update or null + * + * @throws EntityNotFoundException + * if given module does not exist * * @return the saved Entity. - * - * @throws NullPointerException - * of {@link SoftwareModule#getId()} is null */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - SoftwareModule updateSoftwareModule(@NotNull SoftwareModule sm); + SoftwareModule updateSoftwareModule(@NotNull SoftwareModuleUpdate update); /** * updates a distribution set meta data value if corresponding entry exists. - * + * + * @param moduleId + * the metadata belongs to * @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); + SoftwareModuleMetadata updateSoftwareModuleMetadata(@NotNull Long moduleId, @NotNull MetaData metadata); /** - * Updates existing {@link SoftwareModuleType}. Update-able value is - * {@link SoftwareModuleType#getDescription()} and - * {@link SoftwareModuleType#getColour()}. + * Updates existing {@link SoftwareModuleType}. * - * @param sm + * @param update * to update + * * @return updated Entity + * + * @throws EntityNotFoundException + * in case the {@link SoftwareModuleType} does not exists and + * cannot be updated */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - SoftwareModuleType updateSoftwareModuleType(@NotNull SoftwareModuleType sm); + SoftwareModuleType updateSoftwareModuleType(@NotNull SoftwareModuleTypeUpdate update); /** * Finds all meta data by the given software module id. * - * @param softwareModuleId + * @param moduleId * the software module id to retrieve the meta data from * * 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 index 131f63107a..d07316868b 100644 --- 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 @@ -85,14 +85,14 @@ public interface SystemManagement { TenantMetaData getTenantMetadata(@NotNull String tenant); /** - * Update call for {@link TenantMetaData}. + * Update call for {@link TenantMetaData} of the current tenant. * - * @param metaData + * @param defaultDsType * to update * @return updated {@link TenantMetaData} entity */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_TENANT_CONFIGURATION) - TenantMetaData updateTenantMetadata(@NotNull TenantMetaData metaData); + TenantMetaData updateTenantMetadata(@NotNull Long defaultDsType); /** * Returns {@link TenantMetaData} of given tenant ID. 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 index 1b80444b5e..e6c69a4c72 100644 --- 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 @@ -14,7 +14,10 @@ import javax.validation.constraints.NotNull; import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; +import org.eclipse.hawkbit.repository.builder.TagCreate; +import org.eclipse.hawkbit.repository.builder.TagUpdate; 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.DistributionSet; @@ -44,7 +47,7 @@ public interface TagManagement { /** * Creates a {@link DistributionSet}. * - * @param distributionSetTag + * @param create * to be created. * @return the new {@link DistributionSet} * @throws EntityAlreadyExistsException @@ -52,24 +55,24 @@ public interface TagManagement { * */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - DistributionSetTag createDistributionSetTag(@NotNull DistributionSetTag distributionSetTag); + DistributionSetTag createDistributionSetTag(@NotNull TagCreate create); /** * Creates multiple {@link DistributionSetTag}s. * - * @param distributionSetTags + * @param creates * 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); + List createDistributionSetTags(@NotNull Collection creates); /** * Creates a new {@link TargetTag}. * - * @param targetTag + * @param create * to be created * * @return the new created {@link TargetTag} @@ -78,12 +81,12 @@ public interface TagManagement { * if given object already exists */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET) - TargetTag createTargetTag(@NotNull TargetTag targetTag); + TargetTag createTargetTag(@NotNull TagCreate create); /** * created multiple {@link TargetTag}s. * - * @param targetTags + * @param creates * to be created * @return the new created {@link TargetTag}s * @@ -91,7 +94,7 @@ public interface TagManagement { * if given object has already an ID. */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET) - List createTargetTags(@NotNull Collection targetTags); + List createTargetTags(@NotNull Collection creates); /** * Deletes {@link DistributionSetTag} by given @@ -226,23 +229,30 @@ public interface TagManagement { /** * Updates an existing {@link DistributionSetTag}. * - * @param distributionSetTag + * @param update * to be updated + * * @return the updated {@link DistributionSet} - * @throws NullPointerException - * of {@link DistributionSetTag#getName()} is null + * + * @throws EntityNotFoundException + * in case the {@link DistributionSetTag} does not exists and + * cannot be updated */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - DistributionSetTag updateDistributionSetTag(@NotNull DistributionSetTag distributionSetTag); + DistributionSetTag updateDistributionSetTag(@NotNull TagUpdate update); /** * updates the {@link TargetTag}. * - * @param targetTag + * @param update * the {@link TargetTag} with updated values * @return the updated {@link TargetTag} + * + * @throws EntityNotFoundException + * in case the {@link TargetTag} does not exists and cannot be + * updated */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) - TargetTag updateTargetTag(@NotNull TargetTag targetTag); + TargetTag updateTargetTag(@NotNull TagUpdate update); } 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 index 27bb32b25b..8429e42152 100644 --- 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 @@ -11,6 +11,9 @@ import javax.validation.constraints.NotNull; import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; +import org.eclipse.hawkbit.repository.builder.TargetFilterQueryCreate; +import org.eclipse.hawkbit.repository.builder.TargetFilterQueryUpdate; +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.DistributionSet; @@ -28,11 +31,12 @@ public interface TargetFilterQueryManagement { /** * creating new {@link TargetFilterQuery}. * - * @param customTargetFilter + * @param create + * to create * @return the created {@link TargetFilterQuery} */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET) - TargetFilterQuery createTargetFilterQuery(@NotNull TargetFilterQuery customTargetFilter); + TargetFilterQuery createTargetFilterQuery(@NotNull TargetFilterQueryCreate create); /** * Delete target filter query. @@ -73,6 +77,7 @@ public interface TargetFilterQueryManagement { /** * Counts all target filter queries + * * @return the number of all target filter queries */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @@ -135,7 +140,8 @@ Page findTargetFilterQueryByAutoAssignDS(@NotNull Pageable pa DistributionSet distributionSet, String rsqlParam); /** - * Retrieves all target filter query with auto assign DS which {@link TargetFilterQuery}. + * Retrieves all target filter query with auto assign DS which + * {@link TargetFilterQuery}. * * * @return the page with the found {@link TargetFilterQuery} @@ -169,10 +175,32 @@ Page findTargetFilterQueryByAutoAssignDS(@NotNull Pageable pa /** * updates the {@link TargetFilterQuery}. * - * @param targetFilterQuery + * @param update + * to be updated + * + * @return the updated {@link TargetFilterQuery} + * + * @throws EntityNotFoundException + * if either {@link TargetFilterQuery} and/or autoAssignDs are + * provided but not found + */ + @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) + TargetFilterQuery updateTargetFilterQuery(TargetFilterQueryUpdate update); + + /** + * updates the {@link TargetFilterQuery#getAutoAssignDistributionSet()}. + * + * @param queryId * to be updated + * @param dsId + * to be updated or null * @return the updated {@link TargetFilterQuery} + * + * @throws EntityNotFoundException + * if either {@link TargetFilterQuery} and/or autoAssignDs are + * provided but not found */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) - TargetFilterQuery updateTargetFilterQuery(@NotNull TargetFilterQuery targetFilterQuery); + TargetFilterQuery updateTargetFilterQueryAutoAssignDS(Long queryId, Long dsId); + } 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 index fbdf1ee0d7..dcadeb6891 100644 --- 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 @@ -8,14 +8,16 @@ */ 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.builder.TargetCreate; +import org.eclipse.hawkbit.repository.builder.TargetUpdate; 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.DistributionSet; @@ -136,37 +138,14 @@ Long countTargetByFilters(Collection status, Boolean overdue /** * creating a new {@link Target}. * - * @param target + * @param create * 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); + Target createTarget(@NotNull TargetCreate create); /** * creates multiple {@link Target}s. If some of the given {@link Target}s @@ -174,7 +153,7 @@ Long countTargetByFilters(Collection status, Boolean overdue * thrown. {@link Target}s contain all objects of the parameter targets, * including duplicates. * - * @param targets + * @param creates * to be created. * @return the created {@link Target}s * @@ -182,7 +161,7 @@ Long countTargetByFilters(Collection status, Boolean overdue * of one of the given targets already exist. */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET) - List createTargets(@NotNull Collection targets); + List createTargets(@NotNull Collection creates); /** * Deletes all targets with the given IDs. @@ -439,8 +418,8 @@ Page findTargetByAssignedDistributionSet(@NotNull Long distributionSetID */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) Slice findTargetByFilters(@NotNull Pageable pageable, Collection status, - Boolean overdueState, String searchText, Long installedOrAssignedDistributionSetId, Boolean selectTargetWithNoTag, - String... tagNames); + Boolean overdueState, String searchText, Long installedOrAssignedDistributionSetId, + Boolean selectTargetWithNoTag, String... tagNames); /** * retrieves {@link Target}s by the installed {@link DistributionSet}without @@ -651,23 +630,16 @@ Slice findTargetsAllOrderByLinkedDistributionSet(@NotNull Pageable pagea /** * updates the {@link Target}. * - * @param target + * @param update * to be updated + * * @return the updated {@link Target} + * + * @throws EntityNotFoundException + * if given target does not exist */ @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); + Target updateTarget(TargetUpdate update); } diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/ActionStatusBuilder.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/ActionStatusBuilder.java new file mode 100644 index 0000000000..9776b544c2 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/ActionStatusBuilder.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.builder; + +import org.eclipse.hawkbit.repository.model.ActionStatus; + +/** + * Builder for {@link ActionStatus}. + * + */ +@FunctionalInterface +public interface ActionStatusBuilder { + + /** + * @param actionId + * the status is for + * @return create builder + */ + ActionStatusCreate create(long actionId); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/ActionStatusCreate.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/ActionStatusCreate.java new file mode 100644 index 0000000000..a8d50eb26a --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/ActionStatusCreate.java @@ -0,0 +1,56 @@ +/** + * 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.builder; + +import java.util.Collection; + +import org.eclipse.hawkbit.repository.model.Action.Status; +import org.eclipse.hawkbit.repository.model.ActionStatus; +import org.eclipse.hawkbit.repository.model.BaseEntity; + +/** + * Builder to create a new {@link ActionStatus} entry. Defines all fields that + * can be set at creation time. Other fields are set by the repository + * automatically, e.g. {@link BaseEntity#getCreatedAt()}. + * + */ +public interface ActionStatusCreate { + /** + * @param status + * {@link ActionStatus#getStatus()} + * @return updated {@link ActionStatusCreate} object + */ + ActionStatusCreate status(Status status); + + /** + * @param occurredAt + * for {@link ActionStatus#getOccurredAt()} + * @return updated {@link ActionStatusCreate} object + */ + ActionStatusCreate occurredAt(Long occurredAt); + + /** + * @param messages + * for {@link ActionStatus#getMessages()} + * @return updated {@link ActionStatusCreate} object + */ + ActionStatusCreate messages(Collection messages); + + /** + * @param message + * for {@link ActionStatus#getMessages()} + * @return updated {@link ActionStatusCreate} object + */ + ActionStatusCreate message(String message); + + /** + * @return peek on current state of {@link ActionStatus} in the builder + */ + ActionStatus build(); +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/DistributionSetBuilder.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/DistributionSetBuilder.java new file mode 100644 index 0000000000..41a48b510c --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/DistributionSetBuilder.java @@ -0,0 +1,31 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.model.DistributionSet; + +/** + * Builder for {@link DistributionSet}. + * + */ +public interface DistributionSetBuilder { + + /** + * @param id + * of the updatable entity + * @return builder instance + */ + DistributionSetUpdate update(long id); + + /** + * @return builder instance + */ + DistributionSetCreate create(); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/DistributionSetCreate.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/DistributionSetCreate.java new file mode 100644 index 0000000000..4993527fc4 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/DistributionSetCreate.java @@ -0,0 +1,82 @@ +/** + * 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.builder; + +import java.util.Collection; +import java.util.Optional; + +import org.eclipse.hawkbit.repository.model.BaseEntity; +import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.repository.model.DistributionSetType; +import org.hibernate.validator.constraints.NotEmpty; + +/** + * Builder to create a new {@link DistributionSet} entry. Defines all fields + * that can be set at creation time. Other fields are set by the repository + * automatically, e.g. {@link BaseEntity#getCreatedAt()}. + * + */ +public interface DistributionSetCreate { + + /** + * @param name + * for {@link DistributionSet#getName()} + * @return updated builder instance + */ + DistributionSetCreate name(@NotEmpty String name); + + /** + * @param version + * for {@link DistributionSet#getVersion()} + * @return updated builder instance + */ + DistributionSetCreate version(@NotEmpty String version); + + /** + * @param description + * for {@link DistributionSet#getDescription()} + * @return updated builder instance + */ + DistributionSetCreate description(String description); + + /** + * @param typeKey + * for {@link DistributionSet#getType()} + * @return updated builder instance + */ + DistributionSetCreate type(@NotEmpty String typeKey); + + /** + * @param type + * for {@link DistributionSet#getType()} + * @return updated builder instance + */ + default DistributionSetCreate type(final DistributionSetType type) { + return type(Optional.ofNullable(type).map(DistributionSetType::getKey).orElse(null)); + } + + /** + * @param modules + * for {@link DistributionSet#getModules()} + * @return updated builder instance + */ + DistributionSetCreate modules(Collection modules); + + /** + * @param requiredMigrationStep + * for {@link DistributionSet#isRequiredMigrationStep()} + * @return updated builder instance + */ + DistributionSetCreate requiredMigrationStep(Boolean requiredMigrationStep); + + /** + * @return peek on current state of {@link DistributionSet} in the builder + */ + DistributionSet build(); +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/DistributionSetTypeBuilder.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/DistributionSetTypeBuilder.java new file mode 100644 index 0000000000..d2c41f2ecb --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/DistributionSetTypeBuilder.java @@ -0,0 +1,31 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.model.DistributionSetType; + +/** + * Builder for {@link DistributionSetType}. + * + */ +public interface DistributionSetTypeBuilder { + + /** + * @param id + * of the updatable entity + * @return builder instance + */ + DistributionSetTypeUpdate update(long id); + + /** + * @return builder instance + */ + DistributionSetTypeCreate create(); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/DistributionSetTypeCreate.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/DistributionSetTypeCreate.java new file mode 100644 index 0000000000..d91e4549bf --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/DistributionSetTypeCreate.java @@ -0,0 +1,112 @@ +/** + * 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.builder; + +import java.util.Collection; +import java.util.Optional; + +import org.eclipse.hawkbit.repository.model.BaseEntity; +import org.eclipse.hawkbit.repository.model.DistributionSetType; +import org.eclipse.hawkbit.repository.model.SoftwareModuleType; +import org.hibernate.validator.constraints.NotEmpty; + +import com.google.common.collect.Lists; + +/** + * Builder to create a new {@link DistributionSetType} entry. Defines all fields + * that can be set at creation time. Other fields are set by the repository + * automatically, e.g. {@link BaseEntity#getCreatedAt()}. + * + */ +public interface DistributionSetTypeCreate { + + /** + * @param key + * for {@link DistributionSetType#getKey()} + * @return updated builder instance + */ + DistributionSetTypeCreate key(@NotEmpty String key); + + /** + * @param name + * for {@link DistributionSetType#getName()} + * @return updated builder instance + */ + DistributionSetTypeCreate name(@NotEmpty String name); + + /** + * @param description + * for {@link DistributionSetType#getDescription()} + * @return updated builder instance + */ + DistributionSetTypeCreate description(String description); + + /** + * @param colour + * for {@link DistributionSetType#getColour()} + * @return updated builder instance + */ + DistributionSetTypeCreate colour(String colour); + + /** + * @param mandatory + * for {@link DistributionSetType#getMandatoryModuleTypes()} + * @return updated builder instance + */ + DistributionSetTypeCreate mandatory(Collection mandatory); + + /** + * @param mandatory + * for {@link DistributionSetType#getMandatoryModuleTypes()} + * @return updated builder instance + */ + default DistributionSetTypeCreate mandatory(final Long mandatory) { + return mandatory(Lists.newArrayList(mandatory)); + } + + /** + * @param mandatory + * for {@link DistributionSetType#getOptionalModuleTypes()} + * @return updated builder instance + */ + default DistributionSetTypeCreate mandatory(final SoftwareModuleType mandatory) { + return mandatory(Optional.ofNullable(mandatory).map(SoftwareModuleType::getId).orElse(null)); + } + + /** + * @param optional + * for {@link DistributionSetType#getOptionalModuleTypes()} + * @return updated builder instance + */ + DistributionSetTypeCreate optional(Collection optional); + + /** + * @param optional + * for {@link DistributionSetType#getOptionalModuleTypes()} + * @return updated builder instance + */ + default DistributionSetTypeCreate optional(final Long optional) { + return optional(Lists.newArrayList(optional)); + } + + /** + * @param optional + * for {@link DistributionSetType#getOptionalModuleTypes()} + * @return updated builder instance + */ + default DistributionSetTypeCreate optional(final SoftwareModuleType optional) { + return optional(Optional.ofNullable(optional).map(SoftwareModuleType::getId).orElse(null)); + } + + /** + * @return peek on current state of {@link DistributionSetType} in the + * builder + */ + DistributionSetType build(); +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/DistributionSetTypeUpdate.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/DistributionSetTypeUpdate.java new file mode 100644 index 0000000000..ae19c1f53b --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/DistributionSetTypeUpdate.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.builder; + +import java.util.Collection; + +import org.eclipse.hawkbit.repository.model.DistributionSetType; + +/** + * Builder to update an existing {@link DistributionSetType} entry. Defines all + * fields that can be updated. + * + */ +public interface DistributionSetTypeUpdate { + + /** + * @param description + * for {@link DistributionSetType#getDescription()} + * @return updated builder instance + */ + DistributionSetTypeUpdate description(String description); + + /** + * @param colour + * for {@link DistributionSetType#getColour()} + * @return updated builder instance + */ + DistributionSetTypeUpdate colour(String colour); + + /** + * @param mandatory + * for {@link DistributionSetType#getMandatoryModuleTypes()} + * @return updated builder instance + */ + DistributionSetTypeUpdate mandatory(Collection mandatory); + + /** + * @param optional + * for {@link DistributionSetType#getOptionalModuleTypes()} + * @return updated builder instance + */ + DistributionSetTypeUpdate optional(Collection optional); +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/DistributionSetUpdate.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/DistributionSetUpdate.java new file mode 100644 index 0000000000..45a2769464 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/DistributionSetUpdate.java @@ -0,0 +1,66 @@ +/** + * 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.builder; + +import java.util.Optional; + +import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.repository.model.DistributionSetType; +import org.hibernate.validator.constraints.NotEmpty; + +/** + * Builder to update an existing {@link DistributionSet} entry. Defines all + * fields that can be updated. + * + */ +public interface DistributionSetUpdate { + /** + * @param name + * for {@link DistributionSet#getName()} + * @return updated builder instance + */ + DistributionSetUpdate name(@NotEmpty String name); + + /** + * @param version + * for {@link DistributionSet#getVersion()} + * @return updated builder instance + */ + DistributionSetUpdate version(@NotEmpty String version); + + /** + * @param description + * for {@link DistributionSet#getDescription()} + * @return updated builder instance + */ + DistributionSetUpdate description(String description); + + /** + * @param typeKey + * for {@link DistributionSet#getType()} + * @return updated builder instance + */ + DistributionSetUpdate type(@NotEmpty String typeKey); + + /** + * @param type + * for {@link DistributionSet#getType()} + * @return updated builder instance + */ + default DistributionSetUpdate type(final DistributionSetType type) { + return type(Optional.ofNullable(type).map(DistributionSetType::getKey).orElse(null)); + } + + /** + * @param requiredMigrationStep + * for {@link DistributionSet#isRequiredMigrationStep()} + * @return updated builder instance + */ + DistributionSetUpdate requiredMigrationStep(Boolean requiredMigrationStep); +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/RolloutBuilder.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/RolloutBuilder.java new file mode 100644 index 0000000000..7f25eca3b2 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/RolloutBuilder.java @@ -0,0 +1,31 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.model.Rollout; + +/** + * Builder for {@link Rollout}. + * + */ +public interface RolloutBuilder { + + /** + * @param id + * of the updatable entity + * @return builder instance + */ + RolloutUpdate update(long id); + + /** + * @return builder instance + */ + RolloutCreate create(); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/RolloutCreate.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/RolloutCreate.java new file mode 100644 index 0000000000..5608c524d3 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/RolloutCreate.java @@ -0,0 +1,84 @@ +/** + * 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.builder; + +import java.util.Optional; + +import javax.validation.constraints.NotNull; + +import org.eclipse.hawkbit.repository.model.Action.ActionType; +import org.eclipse.hawkbit.repository.model.BaseEntity; +import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.repository.model.Rollout; +import org.hibernate.validator.constraints.NotEmpty; + +/** + * Builder to create a new {@link Rollout} entry. Defines all fields that can be + * set at creation time. Other fields are set by the repository automatically, + * e.g. {@link BaseEntity#getCreatedAt()}. + * + */ +public interface RolloutCreate { + /** + * @param name + * for {@link Rollout#getName()} + * @return updated builder instance + */ + RolloutCreate name(@NotEmpty String name); + + /** + * @param description + * for {@link Rollout#getDescription()} + * @return updated builder instance + */ + RolloutCreate description(String description); + + /** + * @param set + * for {@link Rollout#getDistributionSet()} + * @return updated builder instance + */ + default RolloutCreate set(final DistributionSet set) { + return set(Optional.ofNullable(set).map(DistributionSet::getId).orElse(null)); + } + + /** + * @param setId + * for {@link Rollout#getDistributionSet()} + * @return updated builder instance + */ + RolloutCreate set(long setId); + + /** + * @param targetFilterQuery + * for {@link Rollout#getTargetFilterQuery()} + * @return updated builder instance + */ + RolloutCreate targetFilterQuery(@NotEmpty String targetFilterQuery); + + /** + * @param actionType + * for {@link Rollout#getActionType()} + * @return updated builder instance + */ + RolloutCreate actionType(@NotNull ActionType actionType); + + /** + * @param forcedTime + * for {@link Rollout#getForcedTime()} + * @return updated builder instance + */ + RolloutCreate forcedTime(Long forcedTime); + + /** + * @return peek on current state of {@link Rollout} in the builder + */ + Rollout build(); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/RolloutGroupBuilder.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/RolloutGroupBuilder.java new file mode 100644 index 0000000000..65681f72eb --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/RolloutGroupBuilder.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.builder; + +import org.eclipse.hawkbit.repository.model.Rollout; + +/** + * Builder for {@link Rollout}. + * + */ +@FunctionalInterface +public interface RolloutGroupBuilder { + + /** + * @return builder instance + */ + RolloutGroupCreate create(); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/RolloutGroupCreate.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/RolloutGroupCreate.java new file mode 100644 index 0000000000..be593d7e89 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/RolloutGroupCreate.java @@ -0,0 +1,66 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.model.BaseEntity; +import org.eclipse.hawkbit.repository.model.Rollout; +import org.eclipse.hawkbit.repository.model.RolloutGroup; +import org.eclipse.hawkbit.repository.model.RolloutGroupConditionBuilder; +import org.eclipse.hawkbit.repository.model.RolloutGroupConditions; +import org.hibernate.validator.constraints.NotEmpty; + +/** + * Builder to create a new {@link RolloutGroup} entry. Defines all fields that + * can be set at creation time. Other fields are set by the repository + * automatically, e.g. {@link BaseEntity#getCreatedAt()}. + * + */ +public interface RolloutGroupCreate { + /** + * @param name + * for {@link Rollout#getName()} + * @return updated builder instance + */ + RolloutGroupCreate name(@NotEmpty String name); + + /** + * @param description + * for {@link Rollout#getDescription()} + * @return updated builder instance + */ + RolloutGroupCreate description(String description); + + /** + * @param targetFilterQuery + * for {@link Rollout#getTargetFilterQuery()} + * @return updated builder instance + */ + RolloutGroupCreate targetFilterQuery(@NotEmpty String targetFilterQuery); + + /** + * @param targetPercentage + * the percentage of matching Targets that should be assigned to + * this Group + * @return updated builder instance + */ + RolloutGroupCreate targetPercentage(Float targetPercentage); + + /** + * @param conditions + * as created by {@link RolloutGroupConditionBuilder}. + * @return updated builder instance + */ + RolloutGroupCreate conditions(RolloutGroupConditions conditions); + + /** + * @return peek on current state of {@link RolloutGroup} in the builder + */ + RolloutGroup build(); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/RolloutUpdate.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/RolloutUpdate.java new file mode 100644 index 0000000000..98dfb514d2 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/RolloutUpdate.java @@ -0,0 +1,33 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.model.Rollout; +import org.hibernate.validator.constraints.NotEmpty; + +/** + * Builder to update an existing {@link Rollout} entry. Defines all fields that + * can be updated. + * + */ +public interface RolloutUpdate { + /** + * @param name + * for {@link Rollout#getName()} + * @return updated builder instance + */ + RolloutUpdate name(@NotEmpty String name); + + /** + * @param description + * for {@link Rollout#getDescription()} + * @return updated builder instance + */ + RolloutUpdate description(String description); +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/SoftwareModuleBuilder.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/SoftwareModuleBuilder.java new file mode 100644 index 0000000000..0f6272d7a8 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/SoftwareModuleBuilder.java @@ -0,0 +1,30 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.model.SoftwareModule; + +/** + * Builder for {@link SoftwareModule}. + * + */ +public interface SoftwareModuleBuilder { + + /** + * @param id + * of the updatable entity + * @return builder instance + */ + SoftwareModuleUpdate update(long id); + + /** + * @return builder instance + */ + SoftwareModuleCreate create(); +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/SoftwareModuleCreate.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/SoftwareModuleCreate.java new file mode 100644 index 0000000000..0f702ca07e --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/SoftwareModuleCreate.java @@ -0,0 +1,73 @@ +/** + * 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.builder; + +import java.util.Optional; + +import org.eclipse.hawkbit.repository.model.BaseEntity; +import org.eclipse.hawkbit.repository.model.SoftwareModule; +import org.eclipse.hawkbit.repository.model.SoftwareModuleType; +import org.hibernate.validator.constraints.NotEmpty; + +/** + * Builder to create a new {@link SoftwareModule} entry. Defines all fields that + * can be set at creation time. Other fields are set by the repository + * automatically, e.g. {@link BaseEntity#getCreatedAt()}. + * + */ +public interface SoftwareModuleCreate { + /** + * @param name + * for {@link SoftwareModule#getName()} + * @return updated builder instance + */ + SoftwareModuleCreate name(@NotEmpty String name); + + /** + * @param version + * for {@link SoftwareModule#getVersion()} + * @return updated builder instance + */ + SoftwareModuleCreate version(@NotEmpty String version); + + /** + * @param description + * for {@link SoftwareModule#getDescription()} + * @return updated builder instance + */ + SoftwareModuleCreate description(String description); + + /** + * @param vendor + * for {@link SoftwareModule#getVendor()} + * @return updated builder instance + */ + SoftwareModuleCreate vendor(String vendor); + + /** + * @param typeKey + * for {@link SoftwareModule#getType()} + * @return updated builder instance + */ + SoftwareModuleCreate type(@NotEmpty String typeKey); + + /** + * @param type + * for {@link SoftwareModule#getType()} + * @return updated builder instance + */ + default SoftwareModuleCreate type(final SoftwareModuleType type) { + return type(Optional.ofNullable(type).map(SoftwareModuleType::getKey).orElse(null)); + } + + /** + * @return peek on current state of {@link SoftwareModule} in the builder + */ + SoftwareModule build(); +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/SoftwareModuleTypeBuilder.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/SoftwareModuleTypeBuilder.java new file mode 100644 index 0000000000..1e2dd389d8 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/SoftwareModuleTypeBuilder.java @@ -0,0 +1,30 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.model.SoftwareModuleType; + +/** + * Builder for {@link SoftwareModuleType}. + * + */ +public interface SoftwareModuleTypeBuilder { + + /** + * @param id + * of the updatable entity + * @return builder instance + */ + SoftwareModuleTypeUpdate update(long id); + + /** + * @return builder instance + */ + SoftwareModuleTypeCreate create(); +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/SoftwareModuleTypeCreate.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/SoftwareModuleTypeCreate.java new file mode 100644 index 0000000000..a0ead3ddc0 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/SoftwareModuleTypeCreate.java @@ -0,0 +1,62 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.model.BaseEntity; +import org.eclipse.hawkbit.repository.model.SoftwareModuleType; +import org.hibernate.validator.constraints.NotEmpty; + +/** + * Builder to create a new {@link SoftwareModuleType} entry. Defines all fields + * that can be set at creation time. Other fields are set by the repository + * automatically, e.g. {@link BaseEntity#getCreatedAt()}. + * + */ +public interface SoftwareModuleTypeCreate { + /** + * @param key + * for {@link SoftwareModuleType#getKey()} + * @return updated builder instance + */ + SoftwareModuleTypeCreate key(@NotEmpty String key); + + /** + * @param name + * for {@link SoftwareModuleType#getName()} + * @return updated builder instance + */ + SoftwareModuleTypeCreate name(@NotEmpty String name); + + /** + * @param description + * for {@link SoftwareModuleType#getDescription()} + * @return updated builder instance + */ + SoftwareModuleTypeCreate description(String description); + + /** + * @param colour + * for {@link SoftwareModuleType#getColour()} + * @return updated builder instance + */ + SoftwareModuleTypeCreate colour(String colour); + + /** + * @param maxAssignments + * for {@link SoftwareModuleType#getMaxAssignments()} + * @return updated builder instance + */ + SoftwareModuleTypeCreate maxAssignments(int maxAssignments); + + /** + * @return peek on current state of {@link SoftwareModuleType} in the + * builder + */ + SoftwareModuleType build(); +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/SoftwareModuleTypeUpdate.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/SoftwareModuleTypeUpdate.java new file mode 100644 index 0000000000..b3549cd3e0 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/SoftwareModuleTypeUpdate.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.repository.builder; + +import org.eclipse.hawkbit.repository.model.SoftwareModuleType; + +/** + * Builder to update an existing {@link SoftwareModuleType} entry. Defines all + * fields that can be updated. + * + */ +public interface SoftwareModuleTypeUpdate { + /** + * @param description + * for {@link SoftwareModuleType#getDescription()} + * @return updated builder instance + */ + SoftwareModuleTypeUpdate description(String description); + + /** + * @param colour + * for {@link SoftwareModuleType#getColour()} + * @return updated builder instance + */ + SoftwareModuleTypeUpdate colour(String colour); +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/SoftwareModuleUpdate.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/SoftwareModuleUpdate.java new file mode 100644 index 0000000000..6ab1e67ed0 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/SoftwareModuleUpdate.java @@ -0,0 +1,33 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.model.SoftwareModule; + +/** + * Builder to update an existing {@link SoftwareModule} entry. Defines all + * fields that can be updated. + * + */ +public interface SoftwareModuleUpdate { + + /** + * @param description + * for {@link SoftwareModule#getDescription()} + * @return updated builder instance + */ + SoftwareModuleUpdate description(String description); + + /** + * @param vendor + * for {@link SoftwareModule#getVendor()} + * @return updated builder instance + */ + SoftwareModuleUpdate vendor(String vendor); +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TagBuilder.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TagBuilder.java new file mode 100644 index 0000000000..9b04696626 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TagBuilder.java @@ -0,0 +1,31 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.model.Tag; + +/** + * Builder for {@link Tag}. + * + */ +public interface TagBuilder { + + /** + * @param id + * of the updatable entity + * @return builder instance + */ + TagUpdate update(long id); + + /** + * @return builder instance + */ + TagCreate create(); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TagCreate.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TagCreate.java new file mode 100644 index 0000000000..8dd9a61c01 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TagCreate.java @@ -0,0 +1,47 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.model.BaseEntity; +import org.eclipse.hawkbit.repository.model.Tag; +import org.hibernate.validator.constraints.NotEmpty; + +/** + * Builder to create a new {@link Tag} entry. Defines all fields that can be set + * at creation time. Other fields are set by the repository automatically, e.g. + * {@link BaseEntity#getCreatedAt()}. + * + */ +public interface TagCreate { + /** + * @param name + * for {@link Tag#getName()} + * @return updated builder instance + */ + TagCreate name(@NotEmpty String name); + + /** + * @param description + * for {@link Tag#getDescription()} + * @return updated builder instance + */ + TagCreate description(String description); + + /** + * @param colour + * for {@link Tag#getColour()} + * @return updated builder instance + */ + TagCreate colour(String colour); + + /** + * @return peek on current state of {@link Tag} in the builder + */ + Tag build(); +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TagUpdate.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TagUpdate.java new file mode 100644 index 0000000000..10335f6028 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TagUpdate.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.builder; + +import org.eclipse.hawkbit.repository.model.Tag; +import org.hibernate.validator.constraints.NotEmpty; + +/** + * Builder to update an existing {@link Tag} entry. Defines all fields that can + * be updated. + * + */ +public interface TagUpdate { + /** + * @param name + * for {@link Tag#getName()} + * @return updated builder instance + */ + TagUpdate name(@NotEmpty String name); + + /** + * @param description + * for {@link Tag#getDescription()} + * @return updated builder instance + */ + TagUpdate description(String description); + + /** + * @param colour + * for {@link Tag#getColour()} + * @return updated builder instance + */ + TagUpdate colour(String colour); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TargetBuilder.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TargetBuilder.java new file mode 100644 index 0000000000..a8ff36fc79 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TargetBuilder.java @@ -0,0 +1,31 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.model.Target; +import org.hibernate.validator.constraints.NotEmpty; + +/** + * Builder for {@link Target}. + * + */ +public interface TargetBuilder { + + /** + * @param controllerId + * of the updatable entity + * @return builder instance + */ + TargetUpdate update(@NotEmpty String controllerId); + + /** + * @return builder instance + */ + TargetCreate create(); +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TargetCreate.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TargetCreate.java new file mode 100644 index 0000000000..47fc4eba67 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TargetCreate.java @@ -0,0 +1,83 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.model.BaseEntity; +import org.eclipse.hawkbit.repository.model.Target; +import org.eclipse.hawkbit.repository.model.TargetInfo; +import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; +import org.hibernate.validator.constraints.NotEmpty; + +/** + * Builder to create a new {@link Target} entry. Defines all fields that can be + * set at creation time. Other fields are set by the repository automatically, + * e.g. {@link BaseEntity#getCreatedAt()}. + * + */ +public interface TargetCreate { + + /** + * @param controllerId + * for {@link Target#getControllerId()} + * @return updated builder instance + */ + TargetCreate controllerId(@NotEmpty String controllerId); + + /** + * @param name + * for {@link Target#getName()} + * @return updated builder instance + */ + TargetCreate name(@NotEmpty String name); + + /** + * @param description + * for {@link Target#getDescription()} + * @return updated builder instance + */ + TargetCreate description(String description); + + /** + * @param securityToken + * for {@link Target#getSecurityToken()} + * @return updated builder instance + */ + TargetCreate securityToken(String securityToken); + + /** + * @param address + * for {@link TargetInfo#getAddress()} + * + * @throws IllegalArgumentException + * If the given string violates RFC 2396 + * + * @return updated builder instance + */ + TargetCreate address(String address); + + /** + * @param lastTargetQuery + * for {@link TargetInfo#getLastTargetQuery()} + * @return updated builder instance + */ + TargetCreate lastTargetQuery(Long lastTargetQuery); + + /** + * @param status + * for {@link TargetInfo#getUpdateStatus()} + * @return updated builder instance + */ + TargetCreate status(TargetUpdateStatus status); + + /** + * @return peek on current state of {@link Target} in the builder + */ + Target build(); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TargetFilterQueryBuilder.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TargetFilterQueryBuilder.java new file mode 100644 index 0000000000..2e9698743a --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TargetFilterQueryBuilder.java @@ -0,0 +1,29 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.model.TargetFilterQuery; + +/** + * Builder for {@link TargetFilterQuery}. + * + */ +public interface TargetFilterQueryBuilder { + /** + * @param id + * of the updatable entity + * @return builder instance + */ + TargetFilterQueryUpdate update(long id); + + /** + * @return builder instance + */ + TargetFilterQueryCreate create(); +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TargetFilterQueryCreate.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TargetFilterQueryCreate.java new file mode 100644 index 0000000000..44ebbfe3fe --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TargetFilterQueryCreate.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.builder; + +import java.util.Optional; + +import org.eclipse.hawkbit.repository.model.BaseEntity; +import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.repository.model.TargetFilterQuery; +import org.hibernate.validator.constraints.NotEmpty; + +/** + * Builder to create a new {@link TargetFilterQuery} entry. Defines all fields + * that can be set at creation time. Other fields are set by the repository + * automatically, e.g. {@link BaseEntity#getCreatedAt()}. + * + */ +public interface TargetFilterQueryCreate { + /** + * @param name + * of {@link TargetFilterQuery#getName()} + * @return updated builder instance + */ + TargetFilterQueryCreate name(@NotEmpty String name); + + /** + * @param query + * of {@link TargetFilterQuery#getQuery()} + * @return updated builder instance + */ + TargetFilterQueryCreate query(@NotEmpty String query); + + /** + * @param set + * for {@link TargetFilterQuery#getAutoAssignDistributionSet()} + * @return updated builder instance + */ + default TargetFilterQueryCreate set(final DistributionSet set) { + return set(Optional.ofNullable(set).map(DistributionSet::getId).orElse(null)); + } + + /** + * @param setId + * for {@link TargetFilterQuery#getAutoAssignDistributionSet()} + * @return updated builder instance + */ + TargetFilterQueryCreate set(long setId); + + /** + * @return peek on current state of {@link TargetFilterQuery} in the builder + */ + TargetFilterQuery build(); +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TargetFilterQueryUpdate.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TargetFilterQueryUpdate.java new file mode 100644 index 0000000000..2ce2f37d1a --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TargetFilterQueryUpdate.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.builder; + +import org.eclipse.hawkbit.repository.model.TargetFilterQuery; +import org.hibernate.validator.constraints.NotEmpty; + +/** + * Builder to update an existing {@link TargetFilterQuery} entry. Defines all + * fields that can be updated. + * + */ +public interface TargetFilterQueryUpdate { + /** + * @param name + * of {@link TargetFilterQuery#getName()} + * @return updated builder instance + */ + TargetFilterQueryUpdate name(@NotEmpty String name); + + /** + * @param query + * of {@link TargetFilterQuery#getQuery()} + * @return updated builder instance + */ + TargetFilterQueryUpdate query(@NotEmpty String query); + +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TargetUpdate.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TargetUpdate.java new file mode 100644 index 0000000000..10742e995b --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/builder/TargetUpdate.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.builder; + +import org.eclipse.hawkbit.repository.model.Target; +import org.eclipse.hawkbit.repository.model.TargetInfo; +import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; +import org.hibernate.validator.constraints.NotEmpty; + +/** + * Builder to update an existing {@link Target} entry. Defines all fields that + * can be updated. + * + */ +public interface TargetUpdate { + + /** + * @param name + * for {@link Target#getName()} + * @return updated builder instance + */ + TargetUpdate name(@NotEmpty String name); + + /** + * @param description + * for {@link Target#getDescription()} + * @return updated builder instance + */ + TargetUpdate description(String description); + + /** + * @param securityToken + * for {@link Target#getSecurityToken()} + * @return updated builder instance + */ + TargetUpdate securityToken(@NotEmpty String securityToken); + + /** + * @param address + * for {@link TargetInfo#getAddress()} + * + * @throws IllegalArgumentException + * If the given string violates RFC 2396 + * + * @return updated builder instance + */ + TargetUpdate address(String address); + + /** + * @param lastTargetQuery + * for {@link TargetInfo#getLastTargetQuery()} + * @return updated builder instance + */ + TargetUpdate lastTargetQuery(Long lastTargetQuery); + + /** + * @param status + * for {@link TargetInfo#getUpdateStatus()} + * @return updated builder instance + */ + TargetUpdate status(TargetUpdateStatus status); +} diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/event/remote/TargetAssignDistributionSetEvent.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/event/remote/TargetAssignDistributionSetEvent.java index db88c280ee..a1fcd8158c 100644 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/event/remote/TargetAssignDistributionSetEvent.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/event/remote/TargetAssignDistributionSetEvent.java @@ -12,7 +12,9 @@ import java.util.Collections; import org.eclipse.hawkbit.repository.model.Action; +import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.SoftwareModule; +import org.eclipse.hawkbit.repository.model.Target; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -54,7 +56,20 @@ public TargetAssignDistributionSetEvent(final Action action, final String applic } - private TargetAssignDistributionSetEvent(final String tenant, final Long actionId, final Long distributionSetId, + /** + * Constructor. + * + * @param tenant + * the event belongs to + * @param actionId + * to the action + * @param distributionSetId + * of the assigned {@link DistributionSet} + * @param controllerId + * of the assignment {@link Target} + * @param applicationId + */ + public TargetAssignDistributionSetEvent(final String tenant, final Long actionId, final Long distributionSetId, final String controllerId, final String applicationId) { super(actionId, tenant, applicationId); this.actionId = actionId; diff --git a/hawkbit-repository/hawkbit-repository-api/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 index c7ed8637e0..c6ca452587 100644 --- a/hawkbit-repository/hawkbit-repository-api/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 @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; /** * Thrown if artifact deletion failed. diff --git a/hawkbit-repository/hawkbit-repository-api/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 index 6f762b56c3..dbaf5cc75a 100644 --- a/hawkbit-repository/hawkbit-repository-api/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 @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; /** * diff --git a/hawkbit-repository/hawkbit-repository-api/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 index 1afd994cf8..dd1ca45533 100644 --- a/hawkbit-repository/hawkbit-repository-api/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 @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; /** * Thrown if cancelation of actions is performened where the action is not diff --git a/hawkbit-repository/hawkbit-repository-api/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 index ec2691e526..e1fd9651b6 100644 --- a/hawkbit-repository/hawkbit-repository-api/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 @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; /** * {@link ConcurrentModificationException} is thrown when a given entity in's diff --git a/hawkbit-repository/hawkbit-repository-api/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 index 936d3e5d28..841cd9fd27 100644 --- a/hawkbit-repository/hawkbit-repository-api/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 @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; /** * Thrown if DS creation failed. diff --git a/hawkbit-repository/hawkbit-repository-api/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 index 8cf3c61623..361e918b5e 100644 --- a/hawkbit-repository/hawkbit-repository-api/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 @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetType; diff --git a/hawkbit-repository/hawkbit-repository-api/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 deleted file mode 100644 index 23c3724100..0000000000 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/EntityLockedException.java +++ /dev/null @@ -1,64 +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.exception; - -import org.eclipse.hawkbit.exception.SpServerError; -import org.eclipse.hawkbit.exception.AbstractServerRtException; - -/** - * The {@link EntityLockedException} is thrown when an entity has been locked by - * the server to prevent modification. - * - * - * - */ -public class EntityLockedException extends AbstractServerRtException { - - private static final long serialVersionUID = 1L; - private static final SpServerError THIS_ERROR = SpServerError.SP_ENTITY_LOCKED; - - /** - * Default constructor. - */ - public EntityLockedException() { - super(THIS_ERROR); - } - - /** - * Parameterized constructor. - * - * @param cause - * of the exception - */ - public EntityLockedException(final Throwable cause) { - super(THIS_ERROR, cause); - } - - /** - * Parameterized constructor. - * - * @param message - * of the exception - * @param cause - * of the exception - */ - public EntityLockedException(final String message, final Throwable cause) { - super(message, THIS_ERROR, cause); - } - - /** - * Parameterized constructor. - * - * @param message - * of the exception - */ - public EntityLockedException(final String message) { - super(message, THIS_ERROR); - } -} diff --git a/hawkbit-repository/hawkbit-repository-api/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 index ce1446f67d..47cb1e274f 100644 --- a/hawkbit-repository/hawkbit-repository-api/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 @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; /** * the {@link EntityNotFoundException} is thrown when a entity is tried find but diff --git a/hawkbit-repository/hawkbit-repository-api/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 index f2686abb11..1b548d8be4 100644 --- a/hawkbit-repository/hawkbit-repository-api/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 @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; /** * the {@link EntityReadOnlyException} is thrown when a entity is in read only diff --git a/hawkbit-repository/hawkbit-repository-api/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 index 83957739a4..244211999d 100644 --- a/hawkbit-repository/hawkbit-repository-api/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 @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; /** * Thrown when force quitting an actions is not allowed. e.g. the action is not diff --git a/hawkbit-repository/hawkbit-repository-api/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 index 3f3c49e03c..99200efabf 100644 --- a/hawkbit-repository/hawkbit-repository-api/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 @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; /** * diff --git a/hawkbit-repository/hawkbit-repository-api/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 index 10bc5bba45..3ce9624bcd 100644 --- a/hawkbit-repository/hawkbit-repository-api/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 @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; /** * Thrown if a distribution set is assigned to a a target that is incomplete diff --git a/hawkbit-repository/hawkbit-repository-api/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 index d3802300a1..ef9ff624b8 100644 --- a/hawkbit-repository/hawkbit-repository-api/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 @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; /** * Exception which is thrown in case the current security context object does diff --git a/hawkbit-repository/hawkbit-repository-api/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 index f6083a6129..aa6974b57e 100644 --- a/hawkbit-repository/hawkbit-repository-api/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 @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; /** * Thrown if MD5 checksum check fails. diff --git a/hawkbit-repository/hawkbit-repository-api/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 index 4cc26c5716..7153081e1b 100644 --- a/hawkbit-repository/hawkbit-repository-api/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 @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; /** * Thrown if SHA1 checksum check fails. diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/InvalidTargetAddressException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/InvalidTargetAddressException.java index 160d5c07bd..ada5cb9b64 100644 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/InvalidTargetAddressException.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/InvalidTargetAddressException.java @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; /** * Exception which is thrown when trying to set an invalid target address. diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/MultiPartFileUploadException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/MultiPartFileUploadException.java index 7b554982e1..94bb054256 100644 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/MultiPartFileUploadException.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/MultiPartFileUploadException.java @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; /** * Thrown if a multi part exception occurred. diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/RSQLParameterSyntaxException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/RSQLParameterSyntaxException.java index d46f6d8272..7566775586 100644 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/RSQLParameterSyntaxException.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/RSQLParameterSyntaxException.java @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; /** * Exception used by the REST API in case of RSQL search filter query. diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/RSQLParameterUnsupportedFieldException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/RSQLParameterUnsupportedFieldException.java index 402a3eee77..95ba8502fd 100644 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/RSQLParameterUnsupportedFieldException.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/RSQLParameterUnsupportedFieldException.java @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; /** * Exception used by the REST API in case of invalid field name in the rsql diff --git a/hawkbit-repository/hawkbit-repository-api/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 index 2f1937008b..468824babc 100644 --- a/hawkbit-repository/hawkbit-repository-api/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 @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; /** * the {@link RolloutIllegalStateException} is thrown when a rollout is changing diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/RolloutVerificationException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/RolloutVerificationException.java deleted file mode 100644 index 4dda248dd8..0000000000 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/RolloutVerificationException.java +++ /dev/null @@ -1,63 +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.exception; - -import org.eclipse.hawkbit.exception.AbstractServerRtException; -import org.eclipse.hawkbit.exception.SpServerError; - -/** - * the {@link RolloutVerificationException} is thrown when a rollout or - * its groups get created or modified with a configuration that is - * not valid or can't be verified - * - */ -public class RolloutVerificationException extends AbstractServerRtException { - - private static final long serialVersionUID = 1L; - private static final SpServerError THIS_ERROR = SpServerError.SP_ROLLOUT_VERIFICATION_FAILED; - - /** - * Default constructor. - */ - public RolloutVerificationException() { - super(THIS_ERROR); - } - - /** - * Parameterized constructor. - * - * @param cause - * of the exception - */ - public RolloutVerificationException(final Throwable cause) { - super(THIS_ERROR, cause); - } - - /** - * Parameterized constructor. - * - * @param message - * of the exception - * @param cause - * of the exception - */ - public RolloutVerificationException(final String message, final Throwable cause) { - super(message, THIS_ERROR, cause); - } - - /** - * Parameterized constructor. - * - * @param message - * of the exception - */ - public RolloutVerificationException(final String message) { - super(message, THIS_ERROR); - } -} diff --git a/hawkbit-repository/hawkbit-repository-api/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 index 810054e938..0ccb95d10e 100644 --- a/hawkbit-repository/hawkbit-repository-api/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 @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; /** * the {@link TenantNotExistException} is thrown when e.g. a controller tries to diff --git a/hawkbit-repository/hawkbit-repository-api/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 index 6004bc2e7f..85433b7f9b 100644 --- a/hawkbit-repository/hawkbit-repository-api/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 @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; /** * Thrown if too many status entries have been inserted. diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/TooManyStatusEntriesException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/TooManyStatusEntriesException.java index 3f3399a88e..a0fe82d987 100644 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/TooManyStatusEntriesException.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/TooManyStatusEntriesException.java @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; /** * Thrown if too many status entries have been inserted. diff --git a/hawkbit-repository/hawkbit-repository-api/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 index 2ed76dfbce..489647af4a 100644 --- a/hawkbit-repository/hawkbit-repository-api/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 @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.exception; -import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.AbstractServerRtException; +import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.SoftwareModule; 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 index 98d1014715..66659f2b14 100644 --- 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 @@ -24,12 +24,6 @@ public interface Action extends TenantAwareBaseEntity { */ 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 @@ -44,12 +38,6 @@ default boolean isCancelingOrCanceled() { */ Status getStatus(); - /** - * @param status - * of the {@link Action} - */ - void setStatus(Status status); - /** * @return true if {@link Action} is still running. */ @@ -65,12 +53,6 @@ default boolean isCancelingOrCanceled() { */ List getActionStatus(); - /** - * @param target - * of this {@link Action} - */ - void setTarget(Target target); - /** * @return {@link Target} of this {@link Action}. */ 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 index 10550e37de..467a2cc68e 100644 --- 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 @@ -28,21 +28,6 @@ public interface ActionStatus extends TenantAwareBaseEntity { */ 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 immutable list of message entries that in the * {@link ActionStatus}. @@ -54,12 +39,6 @@ public interface ActionStatus extends TenantAwareBaseEntity { */ 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 @@ -67,12 +46,4 @@ public interface ActionStatus extends TenantAwareBaseEntity { */ 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/DistributionSet.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSet.java index 8704e5e176..3af310a93c 100644 --- 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 @@ -30,21 +30,6 @@ public interface DistributionSet extends NamedVersionedEntity { */ Set getTags(); - /** - * @param tag - * to add - * @return true if tag could be added sucessfully (i.e. was not - * already in the list). - */ - boolean addTag(final DistributionSetTag tag); - - /** - * @param tag - * to remove - * @return true if tag was in the list and removed - */ - boolean removeTag(final DistributionSetTag tag); - /** * @return true if the set is deleted and only kept for history * purposes. @@ -64,25 +49,6 @@ public interface DistributionSet extends NamedVersionedEntity { */ 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 */ @@ -104,44 +70,22 @@ public interface DistributionSet extends NamedVersionedEntity { */ 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. + * @return SoftwareModule of given type or null if not found. */ - SoftwareModule findFirstModuleByType(SoftwareModuleType type); + default SoftwareModule findFirstModuleByType(final SoftwareModuleType type) { + return getModules().stream().filter(module -> module.getType().equals(type)).findFirst().orElse(null); + } /** * @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 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 index 57420bbad4..c9aac9a2c0 100644 --- 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 @@ -111,46 +111,11 @@ default boolean containsOptionalModuleType(final Long softwareModuleTypeId) { */ 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 @@ -164,10 +129,4 @@ default boolean containsOptionalModuleType(final Long softwareModuleTypeId) { */ 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/ExternalArtifactProvider.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifactProvider.java deleted file mode 100644 index 1393270960..0000000000 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifactProvider.java +++ /dev/null @@ -1,41 +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; - -/** - * 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/MetaData.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/MetaData.java index 68b7349f9b..e3322782ff 100644 --- 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 @@ -21,19 +21,9 @@ public interface MetaData extends Serializable { */ 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 index 4d3f3e4199..ea68b44575 100644 --- 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 @@ -23,17 +23,4 @@ public interface NamedEntity extends TenantAwareBaseEntity { * @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 index b661150826..74f9af44be 100644 --- 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 @@ -13,16 +13,8 @@ * */ 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/Rollout.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Rollout.java index e3373f4ea0..7124d027dd 100644 --- 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 @@ -31,12 +31,6 @@ public interface Rollout extends NamedEntity { */ DistributionSet getDistributionSet(); - /** - * @param distributionSet - * that is rolled out - */ - void setDistributionSet(DistributionSet distributionSet); - /** * @return immutable list of deployment groups of the rollout. */ @@ -48,12 +42,6 @@ public interface Rollout extends NamedEntity { */ String getTargetFilterQuery(); - /** - * @param targetFilterQuery - * that identifies the targets that are part of this rollout. - */ - void setTargetFilterQuery(String targetFilterQuery); - /** * @return status of the rollout */ @@ -64,12 +52,6 @@ public interface Rollout extends NamedEntity { */ 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 @@ -77,14 +59,6 @@ public interface Rollout extends NamedEntity { */ 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. */ 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 index 5dcf7d67c7..0c246f832b 100644 --- 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 @@ -21,23 +21,11 @@ public interface RolloutGroup extends NamedEntity { */ 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} @@ -50,14 +38,6 @@ public interface RolloutGroup extends NamedEntity { */ 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 @@ -66,31 +46,12 @@ public interface RolloutGroup extends NamedEntity { */ 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 @@ -99,15 +60,6 @@ public interface RolloutGroup extends NamedEntity { */ 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 @@ -115,14 +67,6 @@ public interface RolloutGroup extends NamedEntity { */ 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 @@ -130,15 +74,6 @@ public interface RolloutGroup extends NamedEntity { */ 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 @@ -152,23 +87,6 @@ public interface RolloutGroup extends NamedEntity { */ String getSuccessActionExp(); - /** - * @param successAction - * which is executed if the {@link RolloutGroupSuccessCondition} - * is met - */ - void setSuccessAction(RolloutGroupSuccessAction successAction); - - /** - * - * @param successActionExp - * 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} - */ - void setSuccessActionExp(String successActionExp); - /** * @return the total amount of targets containing in this group */ @@ -179,38 +97,18 @@ public interface RolloutGroup extends NamedEntity { */ TotalTargetCountStatus getTotalTargetCountStatus(); - /** - * @param totalTargetCountStatus - * the totalTargetCountStatus to set - */ - void setTotalTargetCountStatus(TotalTargetCountStatus totalTargetCountStatus); - /** * @return the target filter query, that is used to assign Targets to this * Group */ String getTargetFilterQuery(); - /** - * @param targetFilterQuery - * the target filter query, that is used to assign Targets to - * this Group. Can be null, if no restrictions should apply. - */ - void setTargetFilterQuery(String targetFilterQuery); - /** * @return the percentage of matching Targets that should be assigned to * this Group */ float getTargetPercentage(); - /** - * @param targetPercentage - * the percentage of matching Targets that should be assigned to - * this Group - */ - void setTargetPercentage(float targetPercentage); - /** * Rollout group state machine. * @@ -290,7 +188,8 @@ public String getBeanName() { } /** - * The actions executed when the {@link RolloutGroup#getErrorCondition()} is hit. + * The actions executed when the {@link RolloutGroup#getErrorCondition()} is + * hit. */ enum RolloutGroupErrorAction { PAUSE("pauseRolloutGroupAction"); @@ -310,8 +209,8 @@ public String getBeanName() { } /** - * The actions executed when the {@link RolloutGroup#getSuccessCondition()} is - * hit. + * The actions executed when the {@link RolloutGroup#getSuccessCondition()} + * is hit. */ enum RolloutGroupSuccessAction { NEXTGROUP("startNextRolloutGroupAction"); 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 index 7ef8c8a19b..821da68eba 100644 --- 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 @@ -88,4 +88,17 @@ public RolloutGroupConditionBuilder errorAction(final RolloutGroupErrorAction ac conditions.setErrorActionExp(expression); return this; } + + /** + * Sets condition defaults. + * + * @return the builder itself + */ + public RolloutGroupConditionBuilder withDefaults() { + successCondition(RolloutGroupSuccessCondition.THRESHOLD, "50"); + successAction(RolloutGroupSuccessAction.NEXTGROUP, ""); + errorCondition(RolloutGroupErrorCondition.THRESHOLD, "50"); + errorAction(RolloutGroupErrorAction.PAUSE, ""); + 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 index 0b627fb6ab..618e93c4e4 100644 --- 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 @@ -18,14 +18,14 @@ * easily built. */ public class RolloutGroupConditions { - private RolloutGroupSuccessCondition successCondition = RolloutGroupSuccessCondition.THRESHOLD; - private String successConditionExp = "50"; - private RolloutGroupSuccessAction successAction = RolloutGroupSuccessAction.NEXTGROUP; - private String successActionExp = ""; - private RolloutGroupErrorCondition errorCondition = RolloutGroupErrorCondition.THRESHOLD; - private String errorConditionExp = "50"; - private RolloutGroupErrorAction errorAction = RolloutGroupErrorAction.PAUSE; - private String errorActionExp = ""; + 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; 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 index 66a1fa3ff9..ef4c31b461 100644 --- 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 @@ -16,12 +16,7 @@ * */ public interface SoftwareModule extends NamedVersionedEntity { - /** - * @param artifact - * is added to the assigned {@link Artifact}s. - */ - void addArtifact(Artifact artifact); - + /** * @param artifactId * to look for @@ -59,12 +54,6 @@ default Optional getArtifactByFilename(final String fileName) { */ String getVendor(); - /** - * @param vendor - * the vendor of this software module to set - */ - void setVendor(String vendor); - /** * @return the type of the software module */ @@ -76,12 +65,6 @@ default Optional getArtifactByFilename(final String fileName) { */ boolean isDeleted(); - /** - * @param type - * the module type for this software module - */ - void setType(SoftwareModuleType type); - /** * @return immutable list of {@link DistributionSet}s the module is assigned * to 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 index ebfea9c285..cfb5be5d14 100644 --- 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 @@ -18,11 +18,4 @@ 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 index 4bd52f3f0d..62d6173f31 100644 --- 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 @@ -21,25 +21,12 @@ public interface SoftwareModuleType extends NamedEntity { */ 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. @@ -51,10 +38,4 @@ public interface SoftwareModuleType extends NamedEntity { */ 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 index bfade80e86..00c053de27 100644 --- 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 @@ -19,9 +19,4 @@ public interface Tag extends NamedEntity { */ 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 index c3db1a55b2..317d60764b 100644 --- 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 @@ -59,24 +59,10 @@ default TargetIdName getTargetIdName() { String getSecurityToken(); /** - * @param token - * new securityToken + * @return {@link TargetWithActionType} with default settings */ - void setSecurityToken(String token); - - /** - * @param tag - * to add - * @return true if tag could be added sucessfully (i.e. was not - * already in the list). - */ - boolean addTag(TargetTag tag); - - /** - * @param tag - * to remove - * @return true if tag was in the list and removed - */ - boolean removeTag(TargetTag tag); + default TargetWithActionType getTargetWithActionType() { + return new TargetWithActionType(getControllerId()); + } } 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 index 5db7593a1b..ffeccc07cd 100644 --- 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 @@ -39,33 +39,14 @@ public interface TargetFilterQuery extends TenantAwareBaseEntity { */ 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); - /** * @return the auto assign {@link DistributionSet} if given. */ DistributionSet getAutoAssignDistributionSet(); - /** - * @param distributionSet - * the {@link DistributionSet} that should be assigned to a - * target when this filter matches. - */ - void setAutoAssignDistributionSet(DistributionSet distributionSet); - } diff --git a/hawkbit-repository/hawkbit-repository-api/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 index 444874581e..d5dcc36b33 100644 --- a/hawkbit-repository/hawkbit-repository-api/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 @@ -81,10 +81,7 @@ public boolean equals(final Object obj) { return false; } final TargetIdName other = (TargetIdName) obj; - if (targetId != other.targetId) { - return false; - } - return true; + return targetId == other.targetId; } @Override 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 index 76a975f75f..c45c7b067f 100644 --- 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 @@ -20,15 +20,6 @@ public interface TargetInfo extends Serializable { */ URI getAddress(); - /** - * @param address - * the target address to set - * - * @throws IllegalArgumentException - * If the given string violates RFC 2396 - */ - void setAddress(String address); - /** * @return {@link Target} this info element belongs to. */ diff --git a/hawkbit-repository/hawkbit-repository-api/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 index 7721dabda2..168133e373 100644 --- a/hawkbit-repository/hawkbit-repository-api/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 @@ -11,7 +11,7 @@ /** * The overall {@link TargetUpdateStatus} of a {@link Target} that describes its * status. A {@link Target} can have only one status. independent of the number - * of {@link UpdateAction}s that have to be applied. + * of {@link Action}s that have to be applied. * */ public enum TargetUpdateStatus { diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetWithActionType.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetWithActionType.java index a9cfa81d18..3944938ee7 100644 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetWithActionType.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/TargetWithActionType.java @@ -18,24 +18,22 @@ */ public class TargetWithActionType { - private final String targetId; + private final String controllerId; private final ActionType actionType; private final long forceTime; - /** - * @param targetId - * @param actionType - * @param forceTime - */ - public TargetWithActionType(final String targetId, final ActionType actionType, final long forceTime) { - this.targetId = targetId; + public TargetWithActionType(final String controllerId) { + this.controllerId = controllerId; + this.actionType = ActionType.FORCED; + this.forceTime = 0; + } + + public TargetWithActionType(final String controllerId, final ActionType actionType, final long forceTime) { + this.controllerId = controllerId; this.actionType = actionType; this.forceTime = forceTime; } - /** - * @return the actionType - */ public ActionType getActionType() { if (actionType != null) { return actionType; @@ -44,9 +42,6 @@ public ActionType getActionType() { return ActionType.FORCED; } - /** - * @return the forceTime - */ public long getForceTime() { if (actionType == ActionType.TIMEFORCED) { return forceTime; @@ -54,10 +49,7 @@ public long getForceTime() { return RepositoryModelConstants.NO_FORCE_TIME; } - /** - * @return the targetId - */ - public String getTargetId() { - return targetId; + public String getControllerId() { + return controllerId; } } 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 index 8c19db2360..b0766dd5a3 100644 --- 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 @@ -18,5 +18,4 @@ 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 index fdbc5c8d3a..3b9c1ce666 100644 --- 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 @@ -20,21 +20,9 @@ public interface TenantConfiguration extends TenantAwareBaseEntity { */ 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/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 index 0b40d99390..c19364ec0e 100644 --- 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 @@ -19,13 +19,6 @@ public interface TenantMetaData extends BaseEntity { */ DistributionSetType getDefaultDsType(); - /** - * @param defaultDsType - * that is used of none is selected for a new - * {@link DistributionSet}. - */ - void setDefaultDsType(DistributionSetType defaultDsType); - /** * @return tenant name */ diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/TimestampCalculator.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/TimestampCalculator.java index e6676ef87b..ea51c0c5ed 100644 --- a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/TimestampCalculator.java +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/TimestampCalculator.java @@ -11,7 +11,6 @@ import java.time.Duration; import java.time.Instant; -import org.eclipse.hawkbit.repository.TenantConfigurationManagement; import org.eclipse.hawkbit.repository.model.helper.TenantConfigurationManagementHolder; import org.eclipse.hawkbit.tenancy.configuration.DurationHelper; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractActionStatusCreate.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractActionStatusCreate.java new file mode 100644 index 0000000000..5e17d63502 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractActionStatusCreate.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.builder; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Optional; + +import org.eclipse.hawkbit.repository.model.Action.Status; + +/** + * Create and update builder DTO. + * + * @param + * update or create builder interface + */ +public abstract class AbstractActionStatusCreate { + protected Status status; + protected Long occurredAt; + protected Collection messages; + protected Long actionId; + + public Long getActionId() { + return actionId; + } + + public T status(final Status status) { + this.status = status; + + return (T) this; + } + + public T occurredAt(final Long occurredAt) { + this.occurredAt = occurredAt; + + return (T) this; + } + + public T messages(final Collection messages) { + if (this.messages == null) { + this.messages = messages; + } else { + this.messages.addAll(messages); + } + + return (T) this; + } + + public T message(final String message) { + if (this.messages == null) { + this.messages = new ArrayList<>(); + } + this.messages.add(message); + + return (T) this; + } + + public Optional getOccurredAt() { + return Optional.ofNullable(occurredAt); + } + +} diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractBaseEntityBuilder.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractBaseEntityBuilder.java new file mode 100644 index 0000000000..53bf9ed2e7 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractBaseEntityBuilder.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.builder; + +import org.springframework.hateoas.Identifiable; + +public abstract class AbstractBaseEntityBuilder implements Identifiable { + + protected Long id; + + @Override + public Long getId() { + return id; + } + +} diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractDistributionSetTypeUpdateCreate.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractDistributionSetTypeUpdateCreate.java new file mode 100644 index 0000000000..1f7848b673 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractDistributionSetTypeUpdateCreate.java @@ -0,0 +1,72 @@ +/** + * 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.builder; + +import java.util.Collection; +import java.util.Optional; + +import org.springframework.util.CollectionUtils; + +/** + * Create and update builder DTO. + * + * @param + * update or create builder interface + */ +public abstract class AbstractDistributionSetTypeUpdateCreate extends AbstractNamedEntityBuilder { + protected String colour; + protected String key; + protected Collection mandatory; + protected Collection optional; + + public T mandatory(final Collection mandatory) { + this.mandatory = mandatory; + return (T) this; + } + + public T optional(final Collection optional) { + this.optional = optional; + return (T) this; + } + + public Optional> getMandatory() { + if (CollectionUtils.isEmpty(mandatory)) { + return Optional.empty(); + } + + return Optional.ofNullable(mandatory); + } + + public Optional> getOptional() { + if (CollectionUtils.isEmpty(optional)) { + return Optional.empty(); + } + + return Optional.ofNullable(optional); + } + + public T colour(final String colour) { + this.colour = colour; + return (T) this; + } + + public Optional getColour() { + return Optional.ofNullable(colour); + } + + public T key(final String key) { + this.key = key; + return (T) this; + } + + public Optional getKey() { + return Optional.ofNullable(key); + } + +} diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractDistributionSetUpdateCreate.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractDistributionSetUpdateCreate.java new file mode 100644 index 0000000000..3323d10a02 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractDistributionSetUpdateCreate.java @@ -0,0 +1,62 @@ +/** + * 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.builder; + +import java.util.Collection; +import java.util.Optional; + +/** + * Create and update builder DTO. + * + * @param + * update or create builder interface + */ +public abstract class AbstractDistributionSetUpdateCreate extends AbstractNamedEntityBuilder { + protected String version; + protected Boolean requiredMigrationStep; + protected String type; + protected Collection modules; + + public T modules(final Collection modules) { + this.modules = modules; + return (T) this; + } + + public Collection getModules() { + return modules; + } + + public T type(final String type) { + this.type = type; + return (T) this; + } + + public String getType() { + return type; + } + + public T requiredMigrationStep(final Boolean requiredMigrationStep) { + this.requiredMigrationStep = requiredMigrationStep; + return (T) this; + } + + public Boolean isRequiredMigrationStep() { + return requiredMigrationStep; + } + + public T version(final String version) { + this.version = version; + return (T) this; + } + + public Optional getVersion() { + return Optional.ofNullable(version); + } + +} diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractNamedEntityBuilder.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractNamedEntityBuilder.java new file mode 100644 index 0000000000..955da15ab9 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractNamedEntityBuilder.java @@ -0,0 +1,36 @@ +/** + * 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.builder; + +import java.util.Optional; + +public abstract class AbstractNamedEntityBuilder extends AbstractBaseEntityBuilder { + + protected String name; + protected String description; + + public T name(final String name) { + this.name = name; + return (T) this; + } + + public T description(final String description) { + this.description = description; + return (T) this; + } + + public Optional getName() { + return Optional.ofNullable(name); + } + + public Optional getDescription() { + return Optional.ofNullable(description); + } + +} diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractRolloutGroupCreate.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractRolloutGroupCreate.java new file mode 100644 index 0000000000..050aa25083 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractRolloutGroupCreate.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.builder; + +import org.eclipse.hawkbit.repository.model.RolloutGroupConditions; + +/** + * Create builder DTO. + * + * @param + * update or create builder interface + */ +public abstract class AbstractRolloutGroupCreate extends AbstractNamedEntityBuilder { + protected String targetFilterQuery; + protected Float targetPercentage; + protected RolloutGroupConditions conditions; + + public T targetFilterQuery(final String targetFilterQuery) { + this.targetFilterQuery = targetFilterQuery; + return (T) this; + } + + public T targetPercentage(final Float targetPercentage) { + this.targetPercentage = targetPercentage; + return (T) this; + } + + public T conditions(final RolloutGroupConditions conditions) { + this.conditions = conditions; + return (T) this; + } + +} diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractRolloutUpdateCreate.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractRolloutUpdateCreate.java new file mode 100644 index 0000000000..a83744ce75 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractRolloutUpdateCreate.java @@ -0,0 +1,45 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.model.Action.ActionType; + +/** + * Create and update builder DTO. + * + * @param + * update or create builder interface + */ +public abstract class AbstractRolloutUpdateCreate extends AbstractNamedEntityBuilder { + protected Long set; + protected String targetFilterQuery; + protected ActionType actionType; + protected Long forcedTime; + + public T set(final long set) { + this.set = set; + return (T) this; + } + + public T targetFilterQuery(final String targetFilterQuery) { + this.targetFilterQuery = targetFilterQuery; + return (T) this; + } + + public T actionType(final ActionType actionType) { + this.actionType = actionType; + return (T) this; + } + + public T forcedTime(final Long forcedTime) { + this.forcedTime = forcedTime; + return (T) this; + } + +} diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractSoftwareModuleTypeUpdateCreate.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractSoftwareModuleTypeUpdateCreate.java new file mode 100644 index 0000000000..1ac5cf440b --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractSoftwareModuleTypeUpdateCreate.java @@ -0,0 +1,51 @@ +/** + * 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.builder; + +import java.util.Optional; + +/** + * Create and update builder DTO. + * + * @param + * update or create builder interface + */ +public abstract class AbstractSoftwareModuleTypeUpdateCreate extends AbstractNamedEntityBuilder { + protected String colour; + protected String key; + protected int maxAssignments = 1; + + public T maxAssignments(final int maxAssignments) { + this.maxAssignments = maxAssignments; + return (T) this; + } + + public int getMaxAssignments() { + return maxAssignments; + } + + public T colour(final String colour) { + this.colour = colour; + return (T) this; + } + + public Optional getColour() { + return Optional.ofNullable(colour); + } + + public T key(final String key) { + this.key = key; + return (T) this; + } + + public Optional getKey() { + return Optional.ofNullable(key); + } + +} diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractSoftwareModuleUpdateCreate.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractSoftwareModuleUpdateCreate.java new file mode 100644 index 0000000000..4024c83b56 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractSoftwareModuleUpdateCreate.java @@ -0,0 +1,51 @@ +/** + * 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.builder; + +import java.util.Optional; + +/** + * Create and update builder DTO. + * + * @param + * update or create builder interface + */ +public abstract class AbstractSoftwareModuleUpdateCreate extends AbstractNamedEntityBuilder { + protected String version; + protected String vendor; + protected String type; + + public T type(final String type) { + this.type = type; + return (T) this; + } + + public Optional getType() { + return Optional.ofNullable(type); + } + + public T vendor(final String vendor) { + this.vendor = vendor; + return (T) this; + } + + public Optional getVendor() { + return Optional.ofNullable(vendor); + } + + public T version(final String version) { + this.version = version; + return (T) this; + } + + public Optional getVersion() { + return Optional.ofNullable(version); + } + +} diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractTagUpdateCreate.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractTagUpdateCreate.java new file mode 100644 index 0000000000..6dedc9fe54 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractTagUpdateCreate.java @@ -0,0 +1,31 @@ +/** + * 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.builder; + +import java.util.Optional; + +/** + * Create and update builder DTO. + * + * @param + * update or create builder interface + */ +public class AbstractTagUpdateCreate extends AbstractNamedEntityBuilder { + protected String colour; + + public T colour(final String colour) { + this.colour = colour; + return (T) this; + } + + public Optional getColour() { + return Optional.ofNullable(colour); + } + +} diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractTargetFilterQueryUpdateCreate.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractTargetFilterQueryUpdateCreate.java new file mode 100644 index 0000000000..0a04dbda29 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractTargetFilterQueryUpdateCreate.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.builder; + +import java.util.Optional; + +/** + * Create and update builder DTO. + * + * @param + * update or create builder interface + */ +public abstract class AbstractTargetFilterQueryUpdateCreate extends AbstractBaseEntityBuilder { + protected String name; + protected String query; + protected Long set; + + public T set(final long set) { + this.set = set; + return (T) this; + } + + public Optional getSet() { + return Optional.ofNullable(set); + } + + public T name(final String name) { + this.name = name; + return (T) this; + } + + public Optional getName() { + return Optional.ofNullable(name); + } + + public T query(final String query) { + this.query = query; + return (T) this; + } + + public Optional getQuery() { + return Optional.ofNullable(query); + } +} diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractTargetUpdateCreate.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractTargetUpdateCreate.java new file mode 100644 index 0000000000..87a6cb2fd4 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/AbstractTargetUpdateCreate.java @@ -0,0 +1,88 @@ +/** + * 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.builder; + +import java.net.URI; +import java.util.Optional; + +import org.eclipse.hawkbit.repository.exception.InvalidTargetAddressException; +import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; + +/** + * Create and update builder DTO. + * + * @param + * update or create builder interface + */ +public class AbstractTargetUpdateCreate extends AbstractNamedEntityBuilder { + protected String controllerId; + protected String address; + protected String securityToken; + protected Long lastTargetQuery; + protected TargetUpdateStatus status; + + protected AbstractTargetUpdateCreate(final String controllerId) { + this.controllerId = controllerId; + } + + public T status(final TargetUpdateStatus status) { + this.status = status; + return (T) this; + } + + public T address(final String address) { + // check if this is a real URI + if (address != null) { + try { + URI.create(address); + } catch (final IllegalArgumentException e) { + throw new InvalidTargetAddressException( + "The given address " + address + " violates the RFC-2396 specification", e); + } + } + this.address = address; + return (T) this; + } + + public T securityToken(final String securityToken) { + this.securityToken = securityToken; + return (T) this; + } + + public T lastTargetQuery(final Long lastTargetQuery) { + this.lastTargetQuery = lastTargetQuery; + return (T) this; + } + + public TargetCreate controllerId(final String controllerId) { + this.controllerId = controllerId; + return (TargetCreate) this; + } + + public String getControllerId() { + return controllerId; + } + + public Optional getAddress() { + return Optional.ofNullable(address); + } + + public Optional getSecurityToken() { + return Optional.ofNullable(securityToken); + } + + public Optional getLastTargetQuery() { + return Optional.ofNullable(lastTargetQuery); + } + + public Optional getStatus() { + return Optional.ofNullable(status); + } + +} diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/GenericDistributionSetTypeUpdate.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/GenericDistributionSetTypeUpdate.java new file mode 100644 index 0000000000..1f255f84cf --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/GenericDistributionSetTypeUpdate.java @@ -0,0 +1,21 @@ +/** + * 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.builder; + +/** + * Update implementation. + */ +public class GenericDistributionSetTypeUpdate extends AbstractDistributionSetTypeUpdateCreate + implements DistributionSetTypeUpdate { + + public GenericDistributionSetTypeUpdate(final Long id) { + super.id = id; + } + +} diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/GenericDistributionSetUpdate.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/GenericDistributionSetUpdate.java new file mode 100644 index 0000000000..4c66a21a71 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/GenericDistributionSetUpdate.java @@ -0,0 +1,21 @@ +/** + * 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.builder; + +/** + * Update implementation. + */ +public class GenericDistributionSetUpdate extends AbstractDistributionSetUpdateCreate + implements DistributionSetUpdate { + + public GenericDistributionSetUpdate(final Long id) { + super.id = id; + } + +} diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/GenericRolloutUpdate.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/GenericRolloutUpdate.java new file mode 100644 index 0000000000..a7ae902a63 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/GenericRolloutUpdate.java @@ -0,0 +1,20 @@ +/** + * 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.builder; + +/** + * Update implementation. + */ +public class GenericRolloutUpdate extends AbstractRolloutUpdateCreate implements RolloutUpdate { + + public GenericRolloutUpdate(final Long id) { + super.id = id; + } + +} diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/GenericSoftwareModuleTypeUpdate.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/GenericSoftwareModuleTypeUpdate.java new file mode 100644 index 0000000000..13ece37976 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/GenericSoftwareModuleTypeUpdate.java @@ -0,0 +1,21 @@ +/** + * 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.builder; + +/** + * Update implementation. + */ +public class GenericSoftwareModuleTypeUpdate extends AbstractSoftwareModuleTypeUpdateCreate + implements SoftwareModuleTypeUpdate { + + public GenericSoftwareModuleTypeUpdate(final Long id) { + super.id = id; + } + +} diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/GenericSoftwareModuleUpdate.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/GenericSoftwareModuleUpdate.java new file mode 100644 index 0000000000..fdcf6b1ef5 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/GenericSoftwareModuleUpdate.java @@ -0,0 +1,21 @@ +/** + * 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.builder; + +/** + * Update implementation. + */ +public class GenericSoftwareModuleUpdate extends AbstractSoftwareModuleUpdateCreate + implements SoftwareModuleUpdate { + + public GenericSoftwareModuleUpdate(final Long id) { + super.id = id; + } + +} diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/GenericTagUpdate.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/GenericTagUpdate.java new file mode 100644 index 0000000000..a512b7aa62 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/GenericTagUpdate.java @@ -0,0 +1,18 @@ +/** + * 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.builder; + +/** + * Update implementation. + */ +public class GenericTagUpdate extends AbstractTagUpdateCreate implements TagUpdate { + public GenericTagUpdate(final Long id) { + super.id = id; + } +} diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/GenericTargetFilterQueryUpdate.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/GenericTargetFilterQueryUpdate.java new file mode 100644 index 0000000000..4c65f6b092 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/builder/GenericTargetFilterQueryUpdate.java @@ -0,0 +1,21 @@ +/** + * 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.builder; + +/** + * Update implementation. + */ +public class GenericTargetFilterQueryUpdate extends AbstractTargetFilterQueryUpdateCreate + implements TargetFilterQueryUpdate { + + public GenericTargetFilterQueryUpdate(final Long id) { + super.id = id; + } + +} diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/rsql/VirtualPropertyResolver.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/rsql/VirtualPropertyResolver.java index 764db59373..63853895ab 100644 --- a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/rsql/VirtualPropertyResolver.java +++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/repository/rsql/VirtualPropertyResolver.java @@ -13,7 +13,6 @@ import org.apache.commons.lang3.text.StrLookup; import org.apache.commons.lang3.text.StrSubstitutor; import org.eclipse.hawkbit.repository.TimestampCalculator; -import org.eclipse.hawkbit.repository.rsql.VirtualPropertyReplacer; /** * Adds macro capabilities to RSQL expressions that are used to filter for diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java index f2956a27cb..67fd2f3e46 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java @@ -28,6 +28,11 @@ import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; import org.eclipse.hawkbit.repository.TenantStatsManagement; +import org.eclipse.hawkbit.repository.builder.DistributionSetBuilder; +import org.eclipse.hawkbit.repository.builder.DistributionSetTypeBuilder; +import org.eclipse.hawkbit.repository.builder.RolloutBuilder; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleBuilder; +import org.eclipse.hawkbit.repository.builder.TargetFilterQueryBuilder; import org.eclipse.hawkbit.repository.event.remote.EventEntityManager; import org.eclipse.hawkbit.repository.event.remote.EventEntityManagerHolder; import org.eclipse.hawkbit.repository.jpa.JpaArtifactManagement; @@ -48,6 +53,11 @@ import org.eclipse.hawkbit.repository.jpa.aspects.ExceptionMappingAspectHandler; import org.eclipse.hawkbit.repository.jpa.autoassign.AutoAssignChecker; import org.eclipse.hawkbit.repository.jpa.autoassign.AutoAssignScheduler; +import org.eclipse.hawkbit.repository.jpa.builder.JpaDistributionSetBuilder; +import org.eclipse.hawkbit.repository.jpa.builder.JpaDistributionSetTypeBuilder; +import org.eclipse.hawkbit.repository.jpa.builder.JpaRolloutBuilder; +import org.eclipse.hawkbit.repository.jpa.builder.JpaSoftwareModuleBuilder; +import org.eclipse.hawkbit.repository.jpa.builder.JpaTargetFilterQueryBuilder; import org.eclipse.hawkbit.repository.jpa.configuration.MultiTenantJpaTransactionManager; import org.eclipse.hawkbit.repository.jpa.event.JpaEventEntityManager; import org.eclipse.hawkbit.repository.jpa.model.helper.AfterTransactionCommitExecutorHolder; @@ -56,6 +66,11 @@ import org.eclipse.hawkbit.repository.jpa.model.helper.SystemSecurityContextHolder; import org.eclipse.hawkbit.repository.jpa.model.helper.TenantAwareHolder; import org.eclipse.hawkbit.repository.jpa.rsql.RsqlParserValidationOracle; +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.SoftwareModule; +import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.eclipse.hawkbit.repository.model.helper.SystemManagementHolder; import org.eclipse.hawkbit.repository.model.helper.TenantConfigurationManagementHolder; import org.eclipse.hawkbit.repository.rsql.RsqlValidationOracle; @@ -102,6 +117,63 @@ public RsqlValidationOracle rsqlValidationOracle() { return new RsqlParserValidationOracle(); } + /** + * @param distributionSetManagement + * to loading the {@link DistributionSetType} + * @param softwareManagement + * for loading {@link DistributionSet#getModules()} + * @return DistributionSetBuilder bean + */ + @Bean + public DistributionSetBuilder distributionSetBuilder(final DistributionSetManagement distributionSetManagement, + final SoftwareManagement softwareManagement) { + return new JpaDistributionSetBuilder(distributionSetManagement, softwareManagement); + } + + /** + * @param softwareManagement + * for loading + * {@link DistributionSetType#getMandatoryModuleTypes()} and + * {@link DistributionSetType#getOptionalModuleTypes()} + * @return DistributionSetTypeBuilder bean + */ + @Bean + public DistributionSetTypeBuilder distributionSetTypeBuilder(final SoftwareManagement softwareManagement) { + return new JpaDistributionSetTypeBuilder(softwareManagement); + } + + /** + * @param softwareManagement + * for loading {@link SoftwareModule#getType()} + * @return SoftwareModuleBuilder bean + */ + @Bean + public SoftwareModuleBuilder softwareModuleBuilder(final SoftwareManagement softwareManagement) { + return new JpaSoftwareModuleBuilder(softwareManagement); + } + + /** + * @param distributionSetManagement + * for loading {@link Rollout#getDistributionSet()} + * @return RolloutBuilder bean + */ + @Bean + public RolloutBuilder rolloutBuilder(final DistributionSetManagement distributionSetManagement) { + return new JpaRolloutBuilder(distributionSetManagement); + } + + /** + * @param distributionSetManagement + * for loading + * {@link TargetFilterQuery#getAutoAssignDistributionSet()} + * @return TargetFilterQueryBuilder bean + */ + @Bean + public TargetFilterQueryBuilder targetFilterQueryBuilder( + final DistributionSetManagement distributionSetManagement) { + return new JpaTargetFilterQueryBuilder(distributionSetManagement); + } + /** * @return the {@link SystemSecurityContext} singleton bean which make it * accessible in beans which cannot access the service directly, diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionRepository.java index 0cdd117f2f..b2d54263ea 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionRepository.java @@ -26,7 +26,6 @@ import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TotalTargetCountActionStatus; -import org.springframework.cache.annotation.CacheEvict; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Slice; @@ -95,7 +94,9 @@ public interface ActionRepository extends BaseEntityRepository, /** * Retrieves the oldest {@link Action} that is active and referring to the * given {@link Target}. - * + * + * @param sort + * order * @param target * the target to find assigned actions * @param active @@ -107,7 +108,7 @@ public interface ActionRepository extends BaseEntityRepository, Optional findFirstByTargetAndActive(final Sort sort, final JpaTarget target, boolean active); /** - * Retrieves latest {@link UpdateAction} for given target and + * Retrieves latest {@link Action} for given target and * {@link SoftwareModule}. * * @param targetId @@ -122,7 +123,7 @@ List findActionByTargetAndSoftwareModule(@Param("target") final String t @Param("module") JpaSoftwareModule module); /** - * Retrieves all {@link UpdateAction}s which are referring the given + * Retrieves all {@link Action}s which are referring the given * {@link DistributionSet} and {@link Target}. * * @param pageable @@ -131,10 +132,10 @@ List findActionByTargetAndSoftwareModule(@Param("target") final String t * is the assigned target * @param ds * the {@link DistributionSet} on which will be filtered - * @return the found {@link UpdateAction}s + * @return the found {@link Action}s */ @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, + Page findByTargetAndDistributionSet(final Pageable pageable, @Param("target") final JpaTarget target, @Param("ds") JpaDistributionSet ds); /** @@ -146,24 +147,7 @@ Page findByTargetAndDistributionSet(final Pageable pageable, @Param("tar * @return a list of actions according to the searched target */ @Query("Select a from JpaAction a where a.target = :target order by a.id") - List findByTarget(@Param("target") JpaTarget target); - - /** - * Retrieves all {@link Action}s of a specific target and given active flag - * ordered by action ID. - * - * @param pageable - * the pagination parameter - * @param target - * to search for - * @param active - * {@code true} for all actions which are currently active, - * {@code false} for inactive - * @return a paged list of actions ordered by action ID - */ - @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); + List findByTarget(@Param("target") Target target); /** * Retrieves all {@link Action}s of a specific target and given active flag @@ -181,20 +165,6 @@ Page findByActiveAndTarget(Pageable pageable, @Param("target") JpaTarget @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. - * - * @param keySet - * the list of actions to set inactive - * @param targetsIds - * the IDs of the targets according to the action to set in - * active - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @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, * only if the actions are in a specific status. This should be a atomar @@ -215,26 +185,6 @@ Page findByActiveAndTarget(Pageable pageable, @Param("target") JpaTarget void switchStatus(@Param("statusToSet") Action.Status statusToSet, @Param("targetsIds") List targetIds, @Param("active") boolean active, @Param("currentStatus") Action.Status currentStatus); - /** - * Switches the status of actions from one specific status into another, - * only if the actions are in a specific status. This should be a atomar - * operation. - * - * @param statusToSet - * the new status the actions should get - * @param rollout - * the rollout of the actions which are affected - * @param active - * the active flag of the actions which should be affected - * @param currentStatus - * the current status of the actions which are affected - */ - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @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); - /** * * Retrieves all {@link Action}s which are active and referring to the given @@ -259,14 +209,6 @@ List findByActiveAndTargetIdInAndActionStatusNotEqualToAndDistributio */ Long countByTarget(JpaTarget target); - @Override - @CacheEvict(value = "feedbackReceivedOverTime", allEntries = true) - List save(Iterable entities); - - @Override - @CacheEvict(value = "feedbackReceivedOverTime", allEntries = true) - S save(S entity); - /** * Counts all {@link Action}s referring to the given DistributionSet. * @@ -276,15 +218,6 @@ List findByActiveAndTargetIdInAndActionStatusNotEqualToAndDistributio */ Long countByDistributionSet(JpaDistributionSet distributionSet); - /** - * Counts all {@link Action}s referring to the given rollout. - * - * @param rollout - * the rollout to count the {@link Action}s from - * @return the count of actions referring to the given rollout - */ - Long countByRollout(JpaRollout rollout); - /** * Counts all actions referring to a given rollout and rolloutgroup which * are currently not in the given status. An in-clause statement does not @@ -367,22 +300,6 @@ Page findByRolloutAndRolloutGroupParentAndStatus(Pageable pageable, JpaR Page findByRolloutAndRolloutGroupParentIsNullAndStatus(Pageable pageable, JpaRollout rollout, Status actionStatus); - /** - * Retrieving all actions referring to a given rollout group with a specific - * a specific status. - * - * @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 ids referring a specific rollout group and a specific - * status - */ - List findByRolloutAndRolloutGroupAndStatus(JpaRollout rollout, - JpaRolloutGroup rolloutGroupParent, Status actionStatus); - /** * Retrieves all actions for a specific rollout and in a specific status. * diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionStatusRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionStatusRepository.java index 7a2c574dfa..d9c282c19e 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionStatusRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionStatusRepository.java @@ -11,7 +11,6 @@ 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; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -39,18 +38,6 @@ public interface ActionStatusRepository */ Long countByAction(JpaAction action); - /** - * Counts {@link ActionStatus} entries of given {@link Action} with given - * {@link Status} in repository. - * - * @param action - * to count status entries - * @param status - * to filter for - * @return number of actions in repository - */ - Long countByActionAndStatus(JpaAction action, Status status); - /** * Retrieves all {@link ActionStatus} entries from repository of given * {@link Action}. 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 index f5d00862b1..d3e3ec049c 100644 --- 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 @@ -14,7 +14,6 @@ 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; @@ -71,7 +70,7 @@ static JpaTarget updateTargetInfo(@NotNull final JpaTarget target, @NotNull fina * the action which is set to canceled * @param actionRepository * for the operation - * @param targetManagement + * @param targetRepository * for the operation * @param entityManager * for the operation @@ -79,7 +78,7 @@ static JpaTarget updateTargetInfo(@NotNull final JpaTarget target, @NotNull fina * for the operation */ static void successCancellation(final JpaAction action, final ActionRepository actionRepository, - final TargetManagement targetManagement, final TargetInfoRepository targetInfoRepository, + final TargetRepository targetRepository, final TargetInfoRepository targetInfoRepository, final EntityManager entityManager) { // set action inactive @@ -96,7 +95,8 @@ static void successCancellation(final JpaAction action, final ActionRepository a } else { target.setAssignedDistributionSet(nextActiveActions.get(0).getDistributionSet()); } - targetManagement.updateTarget(target); + target.setNew(false); + targetRepository.save(target); } } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetRepository.java index 83791a66d3..1908af1f93 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetRepository.java @@ -57,9 +57,6 @@ public interface DistributionSetRepository @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. * @@ -81,7 +78,7 @@ public interface DistributionSetRepository * to search for * @return {@link List} of found {@link DistributionSet}s */ - List findByModules(JpaSoftwareModule module); + Long countByModules(JpaSoftwareModule module); /** * Finds {@link DistributionSet}s based on given ID that are assigned yet to @@ -105,19 +102,6 @@ public interface DistributionSetRepository @Query("select ra.distributionSet.id from JpaRollout ra where ra.distributionSet.id in :ids") List findAssignedToRolloutDistributionSetsById(@Param("ids") Long... ids); - /** - * Saves all given {@link DistributionSet}s. - * - * @param entities - * @return the saved entities - * @throws IllegalArgumentException - * in case the given entity is (@literal null}. - * - * @see org.springframework.data.repository.CrudRepository#save(java.lang.Iterable) - */ - @Override - List save(Iterable entities); - /** * Finds the distribution set for a specific action. * diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetTagRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetTagRepository.java index d13316b912..597c8b192b 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetTagRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetTagRepository.java @@ -53,7 +53,4 @@ public interface DistributionSetTagRepository */ @Override List findAll(); - - @Override - List save(Iterable entities); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/EclipseLinkTargetInfoRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/EclipseLinkTargetInfoRepository.java index e4f707ad12..8733f64f3f 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/EclipseLinkTargetInfoRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/EclipseLinkTargetInfoRepository.java @@ -16,7 +16,6 @@ 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; import org.springframework.data.jpa.repository.Modifying; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; @@ -48,7 +47,6 @@ public void setTargetUpdateStatus(final TargetUpdateStatus status, final List S save(final S entity) { if (entity.isNew()) { 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 index c8bfc53c4a..19a396663e 100644 --- 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 @@ -196,15 +196,7 @@ public Artifact createArtifact(final InputStream inputStream, final Long moduleI final boolean overrideExisting) { return createArtifact(inputStream, moduleId, filename, null, null, overrideExisting, null); } - - @Override - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - public Artifact createArtifact(final InputStream inputStream, final Long moduleId, final String filename, - final boolean overrideExisting, final String contentType) { - return createArtifact(inputStream, moduleId, filename, null, null, overrideExisting, contentType); - } - + @Override public Long countArtifactsAll() { return localArtifactRepository.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 index fa9e449318..104544c7b0 100644 --- 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 @@ -19,14 +19,19 @@ import javax.persistence.criteria.Root; import org.eclipse.hawkbit.repository.ControllerManagement; +import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.RepositoryConstants; import org.eclipse.hawkbit.repository.RepositoryProperties; import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; +import org.eclipse.hawkbit.repository.builder.ActionStatusCreate; import org.eclipse.hawkbit.repository.event.remote.DownloadProgressEvent; +import org.eclipse.hawkbit.repository.event.remote.entity.TargetUpdatedEvent; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.exception.ToManyAttributeEntriesException; import org.eclipse.hawkbit.repository.exception.TooManyStatusEntriesException; +import org.eclipse.hawkbit.repository.jpa.builder.JpaActionStatusCreate; +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.JpaActionStatus_; @@ -108,12 +113,18 @@ public class JpaControllerManagement implements ControllerManagement { @Autowired private SystemSecurityContext systemSecurityContext; + @Autowired + private EntityFactory entityFactory; + @Autowired private ApplicationEventPublisher eventPublisher; @Autowired private ApplicationContext applicationContext; + @Autowired + private AfterTransactionCommitExecutor afterCommit; + @Override public String getPollingTime() { final TenantConfigurationKey configurationKey = TenantConfigurationKey.POLLING_TIME_INTERVAL; @@ -170,11 +181,6 @@ public boolean hasTargetArtifactAssigned(final Long targetId, final Artifact loc return actionRepository.count(ActionSpecifications.hasTargetAssignedArtifact(target, localArtifact)) > 0; } - @Override - public List findActiveActionByTarget(final Target target) { - return actionRepository.findByTargetAndActiveOrderByIdAsc((JpaTarget) target, true); - } - @Override public Optional findOldestActiveActionByTarget(final Target target) { // used in favorite to findFirstByTargetAndActiveOrderByIdAsc due to @@ -184,7 +190,7 @@ public Optional findOldestActiveActionByTarget(final Target target) { @Override public Action findActionWithDetails(final Long actionId) { - return actionRepository.findById(actionId); + return getActionAndThrowExceptionIfNotFound(actionId); } @Override @@ -194,14 +200,13 @@ public Target findOrRegisterTargetIfItDoesNotexist(final String controllerId, fi final Specification spec = (targetRoot, query, cb) -> cb .equal(targetRoot.get(JpaTarget_.controllerId), controllerId); - JpaTarget target = targetRepository.findOne(spec); + final 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 targetManagement.createTarget(entityFactory.target().create().controllerId(controllerId) + .description("Plug and Play target: " + controllerId).name(controllerId) + .status(TargetUpdateStatus.REGISTERED).lastTargetQuery(System.currentTimeMillis()) + .address(Optional.ofNullable(address).map(URI::toString).orElse(null))); } return updateLastTargetQuery(target.getTargetInfo(), address).getTarget(); @@ -225,6 +230,8 @@ public TargetInfo updateTargetStatus(final TargetInfo targetInfo, final TargetUp if (mtargetInfo.getUpdateStatus() == TargetUpdateStatus.UNKNOWN) { mtargetInfo.setUpdateStatus(TargetUpdateStatus.REGISTERED); + afterCommit.afterCommit(() -> eventPublisher + .publishEvent(new TargetUpdatedEvent(mtargetInfo.getTarget(), applicationContext.getId()))); } return targetInfoRepository.save(mtargetInfo); @@ -233,8 +240,11 @@ public TargetInfo updateTargetStatus(final TargetInfo targetInfo, final TargetUp @Override @Modifying @Transactional(isolation = Isolation.READ_COMMITTED) - public Action addCancelActionStatus(final ActionStatus actionStatus) { - final JpaAction action = (JpaAction) actionStatus.getAction(); + public Action addCancelActionStatus(final ActionStatusCreate c) { + final JpaActionStatusCreate create = (JpaActionStatusCreate) c; + + final JpaAction action = getActionAndThrowExceptionIfNotFound(create.getActionId()); + final JpaActionStatus actionStatus = create.build(); checkForToManyStatusEntries(action); action.setStatus(actionStatus.getStatus()); @@ -254,27 +264,28 @@ public Action addCancelActionStatus(final ActionStatus actionStatus) { default: // do nothing } - actionRepository.save(action); - actionStatusRepository.save((JpaActionStatus) actionStatus); + actionStatus.setAction(actionRepository.save(action)); + actionStatusRepository.save(actionStatus); return action; } - private void handleFinishedCancelation(final ActionStatus actionStatus, final JpaAction action) { + private void handleFinishedCancelation(final JpaActionStatus 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, + DeploymentHelper.successCancellation(action, actionRepository, targetRepository, targetInfoRepository, entityManager); } @Override @Modifying @Transactional(isolation = Isolation.READ_COMMITTED) - public Action addUpdateActionStatus(final ActionStatus actionStatus) { - final Action action = actionStatus.getAction(); - final Long actionId = action.getId(); + public Action addUpdateActionStatus(final ActionStatusCreate c) { + final JpaActionStatusCreate create = (JpaActionStatusCreate) c; + final JpaAction action = getActionAndThrowExceptionIfNotFound(create.getActionId()); + final JpaActionStatus actionStatus = create.build(); // if action is already closed we accept further status updates if // permitted so by configuration. This is especially useful if the @@ -283,10 +294,10 @@ public Action addUpdateActionStatus(final ActionStatus actionStatus) { // close messages. if (actionIsNotActiveButIntermediateFeedbackStillAllowed(actionStatus, action.isActive())) { LOG.debug("Update of actionStatus {} for action {} not possible since action not active anymore.", - actionStatus.getStatus(), actionId); + actionStatus.getStatus(), action.getId()); return action; } - return handleAddUpdateActionStatus((JpaActionStatus) actionStatus, actionId); + return handleAddUpdateActionStatus(actionStatus, action); } private boolean actionIsNotActiveButIntermediateFeedbackStillAllowed(final ActionStatus actionStatus, @@ -302,10 +313,9 @@ private boolean actionIsNotActiveButIntermediateFeedbackStillAllowed(final Actio * @param action * @return */ - private Action handleAddUpdateActionStatus(final JpaActionStatus actionStatus, final Long actionId) { - LOG.debug("addUpdateActionStatus for action {}", actionId); + private Action handleAddUpdateActionStatus(final JpaActionStatus actionStatus, final JpaAction action) { + LOG.debug("addUpdateActionStatus for action {}", action.getId()); - final JpaAction action = actionRepository.findById(actionId); JpaTarget target = (JpaTarget) action.getTarget(); // check for a potential DOS attack checkForToManyStatusEntries(action); @@ -326,10 +336,13 @@ private Action handleAddUpdateActionStatus(final JpaActionStatus actionStatus, f break; } + actionStatus.setAction(action); actionStatusRepository.save(actionStatus); LOG.debug("addUpdateActionStatus {} for target {} is finished.", action, target.getId()); + action.setStatus(actionStatus.getStatus()); + return actionRepository.save(action); } @@ -337,7 +350,9 @@ private void handleErrorOnAction(final JpaAction mergedAction, final JpaTarget m mergedAction.setActive(false); mergedAction.setStatus(Status.ERROR); mergedTarget.setAssignedDistributionSet(null); - targetManagement.updateTarget(mergedTarget); + + mergedTarget.setNew(false); + targetRepository.save(mergedTarget); } private void checkForToManyStatusEntries(final JpaAction action) { @@ -372,6 +387,10 @@ private void handleFinishedAndStoreInTargetStatus(final JpaTarget target, final } targetInfoRepository.save(targetInfo); + + afterCommit.afterCommit( + () -> eventPublisher.publishEvent(new TargetUpdatedEvent(target, applicationContext.getId()))); + entityManager.detach(ds); } @@ -398,7 +417,13 @@ public Target updateControllerAttributes(final String controllerId, final Map eventPublisher.publishEvent(new TargetUpdatedEvent(result, applicationContext.getId()))); + + return result; } @Override @@ -464,8 +489,20 @@ private Action handleRegisterRetrieved(final JpaAction action, final String mess @Override @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) - public ActionStatus addInformationalActionStatus(final ActionStatus statusMessage) { - return actionStatusRepository.save((JpaActionStatus) statusMessage); + public ActionStatus addInformationalActionStatus(final ActionStatusCreate c) { + final JpaActionStatusCreate create = (JpaActionStatusCreate) c; + final JpaAction action = getActionAndThrowExceptionIfNotFound(create.getActionId()); + final JpaActionStatus statusMessage = create.build(); + statusMessage.setAction(action); + + checkForToManyStatusEntries(action); + + return actionStatusRepository.save(statusMessage); + } + + private JpaAction getActionAndThrowExceptionIfNotFound(final Long actionId) { + return Optional.ofNullable(actionRepository.findById(actionId)) + .orElseThrow(() -> new EntityNotFoundException("Action with ID " + actionId + " not found!")); } @Override 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 index 111158a4ac..3eb1dbdd4b 100644 --- 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 @@ -9,7 +9,6 @@ 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; @@ -34,6 +33,7 @@ import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.event.remote.TargetAssignDistributionSetEvent; import org.eclipse.hawkbit.repository.event.remote.entity.CancelTargetAssignmentEvent; +import org.eclipse.hawkbit.repository.event.remote.entity.TargetUpdatedEvent; import org.eclipse.hawkbit.repository.exception.CancelActionNotAllowedException; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.exception.ForceQuitActionNotAllowedException; @@ -72,7 +72,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.annotation.CacheEvict; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEventPublisher; import org.springframework.data.domain.AuditorAware; @@ -147,45 +146,21 @@ public class JpaDeploymentManagement implements DeploymentManagement { @Autowired private PlatformTransactionManager txManager; - @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) + final long forcedTimestamp, final Collection targetIDs) { + return assignDistributionSet(dsID, targetIDs.stream() .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) { return assignDistributionSet(dsID, targets, null); @@ -194,7 +169,6 @@ public DistributionSetAssignmentResult assignDistributionSet(final Long dsID, @Override @Modifying @Transactional(isolation = Isolation.READ_COMMITTED) - @CacheEvict(value = { "distributionUsageAssigned" }, allEntries = true) public DistributionSetAssignmentResult assignDistributionSet(final Long dsID, final Collection targets, final String actionMessage) { final JpaDistributionSet set = distributoinSetRepository.findOne(dsID); @@ -209,7 +183,6 @@ public DistributionSetAssignmentResult assignDistributionSet(final Long dsID, @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); @@ -250,13 +223,13 @@ private DistributionSetAssignmentResult assignDistributionSetToTargets(@NotNull "Distribution set of type " + set.getType().getKey() + " is incomplete: " + set.getId()); } - final List controllerIDs = targetsWithActionType.stream().map(TargetWithActionType::getTargetId) + final List controllerIDs = targetsWithActionType.stream().map(TargetWithActionType::getControllerId) .collect(Collectors.toList()); LOG.debug("assignDistribution({}) to {} targets", set, controllerIDs.size()); final Map targetsWithActionMap = targetsWithActionType.stream() - .collect(Collectors.toMap(TargetWithActionType::getTargetId, Function.identity())); + .collect(Collectors.toMap(TargetWithActionType::getControllerId, 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 @@ -302,10 +275,9 @@ private DistributionSetAssignmentResult assignDistributionSetToTargets(@NotNull 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())); + final Map targetIdsToActions = targets.stream().map( + t -> actionRepository.save(createTargetAction(targetsWithActionMap, t, set, rollout, rolloutGroup))) + .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 @@ -317,7 +289,7 @@ private DistributionSetAssignmentResult assignDistributionSetToTargets(@NotNull 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(), + targets.stream().map(Target::getControllerId).collect(Collectors.toList()), targets.size(), controllerIDs.size() - targets.size(), targetIdsToActions.values().stream().map(Action::getId).collect(Collectors.toList()), targetManagement); @@ -356,6 +328,8 @@ private static JpaAction createTargetAction(final Map eventPublisher + .publishEvent(new TargetUpdatedEvent(action.getTarget(), applicationContext.getId()))); afterCommit.afterCommit(() -> eventPublisher .publishEvent(new TargetAssignDistributionSetEvent(action, applicationContext.getId()))); } @@ -374,22 +348,20 @@ private Set overrideObsoleteUpdateActions(final List targetsIds) { final List activeActions = actionRepository .findByActiveAndTargetIdInAndActionStatusNotEqualToAndDistributionSetRequiredMigrationStep(targetsIds, Action.Status.CANCELING); - final Set cancelledTargetIds = activeActions.stream().map(action -> { + + return activeActions.stream().map(action -> { action.setStatus(Status.CANCELING); // document that the status has been retrieved actionStatusRepository.save(new JpaActionStatus(action, Status.CANCELING, System.currentTimeMillis(), "manual cancelation requested")); + actionRepository.save(action); cancelAssignDistributionSetEvent(action.getTarget(), action.getId()); return action.getTarget().getId(); }).collect(Collectors.toSet()); - actionRepository.save(activeActions); - - return cancelledTargetIds; - } private DistributionSetAssignmentResult assignDistributionSetByTargetId(@NotNull final JpaDistributionSet set, @@ -463,7 +435,7 @@ public Action forceQuitAction(final Action action) { actionStatusRepository.save(new JpaActionStatus(mergedAction, Status.CANCELED, System.currentTimeMillis(), "A force quit has been performed.")); - DeploymentHelper.successCancellation(mergedAction, actionRepository, targetManagement, targetInfoRepository, + DeploymentHelper.successCancellation(mergedAction, actionRepository, targetRepository, targetInfoRepository, entityManager); return actionRepository.save(mergedAction); @@ -528,9 +500,9 @@ private long startScheduledActionsByRolloutGroupParentInNewTransaction(final Rol private Page findActionsByRolloutAndRolloutGroupParent(final Rollout rollout, final RolloutGroup rolloutGroupParent, final int limit) { - JpaRollout jpaRollout = (JpaRollout) rollout; - JpaRolloutGroup jpaRolloutGroup = (JpaRolloutGroup) rolloutGroupParent; - PageRequest pageRequest = new PageRequest(0, limit); + final JpaRollout jpaRollout = (JpaRollout) rollout; + final JpaRolloutGroup jpaRolloutGroup = (JpaRolloutGroup) rolloutGroupParent; + final PageRequest pageRequest = new PageRequest(0, limit); if (rolloutGroupParent == null) { return actionRepository.findByRolloutAndRolloutGroupParentIsNullAndStatus(pageRequest, jpaRollout, Action.Status.SCHEDULED); @@ -624,7 +596,7 @@ public Slice findActionsByTarget(final Pageable pageable, final Target t @Override public List findActionsByTarget(final Target target) { - return actionRepository.findByTarget((JpaTarget) target); + return Collections.unmodifiableList(actionRepository.findByTarget(target)); } @Override @@ -673,11 +645,6 @@ public Slice findActionsByTarget(final Target foundTarget, final Pageabl 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); @@ -688,11 +655,6 @@ 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); 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 index 1cefd8f351..4a21be5a36 100644 --- 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 @@ -8,30 +8,34 @@ */ 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.List; -import java.util.Set; import java.util.stream.Collectors; import javax.persistence.EntityManager; +import org.apache.commons.collections4.CollectionUtils; 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.builder.DistributionSetCreate; +import org.eclipse.hawkbit.repository.builder.DistributionSetTypeCreate; +import org.eclipse.hawkbit.repository.builder.DistributionSetTypeUpdate; +import org.eclipse.hawkbit.repository.builder.DistributionSetUpdate; +import org.eclipse.hawkbit.repository.builder.GenericDistributionSetTypeUpdate; +import org.eclipse.hawkbit.repository.builder.GenericDistributionSetUpdate; import org.eclipse.hawkbit.repository.event.remote.DistributionSetDeletedEvent; 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.builder.JpaDistributionSetCreate; +import org.eclipse.hawkbit.repository.jpa.builder.JpaDistributionSetTypeCreate; import org.eclipse.hawkbit.repository.jpa.executor.AfterTransactionCommitExecutor; import org.eclipse.hawkbit.repository.jpa.model.DsMetadataCompositeKey; import org.eclipse.hawkbit.repository.jpa.model.JpaAction; @@ -40,8 +44,9 @@ 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.model.JpaSoftwareModule; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType; import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility; -import org.eclipse.hawkbit.repository.rsql.VirtualPropertyReplacer; import org.eclipse.hawkbit.repository.jpa.specifications.DistributionSetSpecification; import org.eclipse.hawkbit.repository.jpa.specifications.DistributionSetTypeSpecification; import org.eclipse.hawkbit.repository.jpa.specifications.SpecificationsBuilder; @@ -53,7 +58,8 @@ 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.MetaData; +import org.eclipse.hawkbit.repository.rsql.VirtualPropertyReplacer; import org.eclipse.hawkbit.tenancy.TenantAware; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; @@ -117,6 +123,12 @@ public class JpaDistributionSetManagement implements DistributionSetManagement { @Autowired private VirtualPropertyReplacer virtualPropertyReplacer; + @Autowired + private SoftwareModuleRepository softwareModuleRepository; + + @Autowired + private SoftwareModuleTypeRepository softwareModuleTypeRepository; + @Override public DistributionSet findDistributionSetByIdWithDetails(final Long distid) { return distributionSetRepository.findOne(DistributionSetSpecification.byId(distid)); @@ -149,10 +161,14 @@ public DistributionSetTagAssignmentResult toggleTagAssignment(final Collection findDistributionSetListWithDetails(final Collec @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); + public DistributionSet updateDistributionSet(final DistributionSetUpdate u) { + final GenericDistributionSetUpdate update = (GenericDistributionSetUpdate) u; + + final JpaDistributionSet set = findDistributionSetAndThrowExceptionIfNotFound(update.getId()); + + update.getName().ifPresent(set::setName); + update.getDescription().ifPresent(set::setDescription); + update.getVersion().ifPresent(set::setVersion); + + if (update.isRequiredMigrationStep() != null + && !update.isRequiredMigrationStep().equals(set.isRequiredMigrationStep())) { + checkDistributionSetIsAssignedToTargets(set); + set.setRequiredMigrationStep(update.isRequiredMigrationStep()); + } + + if (update.getType() != null) { + final DistributionSetType type = findDistributionSetTypeWithExceptionIfNotFound(update.getType()); + if (!type.getId().equals(set.getType().getId())) { + checkDistributionSetIsAssignedToTargets(set); + + set.setType(type); + } + } + + return distributionSetRepository.save(set); + } + + private DistributionSetType findDistributionSetTypeWithExceptionIfNotFound(final String distributionSetTypekey) { + + final DistributionSetType module = findDistributionSetTypeByKey(distributionSetTypekey); + if (module == null) { + throw new EntityNotFoundException( + "DistributionSetType with key {" + distributionSetTypekey + "} does not exist"); + } + return module; + } + + private JpaDistributionSetType findDistributionSetTypeAndThrowExceptionIfNotFound(final Long setId) { + final JpaDistributionSetType set = (JpaDistributionSetType) findDistributionSetTypeById(setId); + + if (set == null) { + throw new EntityNotFoundException("Distribution set type cannot be updated as it does not exixt" + setId); + } + return set; + } + + private JpaDistributionSet findDistributionSetAndThrowExceptionIfNotFound(final Long setId) { + final JpaDistributionSet set = (JpaDistributionSet) findDistributionSetByIdWithDetails(setId); + + if (set == null) { + throw new EntityNotFoundException("Distribution set cannot be updated as it does not exixt" + setId); + } + return set; + } + + private JpaSoftwareModule findSoftwareModuleAndThrowExceptionIfNotFound(final Long moduleId) { + final JpaSoftwareModule module = softwareModuleRepository.findOne(moduleId); + + if (module == null) { + throw new EntityNotFoundException("Distribution set cannot be updated as it does not exixt" + moduleId); + } + return module; } @Override @@ -208,87 +281,155 @@ public void deleteDistributionSet(final Long... distributionSetIDs) { @Override @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) - public DistributionSet createDistributionSet(final DistributionSet dSet) { - prepareDsSave(dSet); - if (dSet.getType() == null) { - dSet.setType(systemManagement.getTenantMetadata().getDefaultDsType()); + public DistributionSet createDistributionSet(final DistributionSetCreate c) { + final JpaDistributionSetCreate create = (JpaDistributionSetCreate) c; + if (create.getType() == null) { + create.type(systemManagement.getTenantMetadata().getDefaultDsType().getKey()); } - 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"); - } + final JpaDistributionSet dSet = create.build(); if (distributionSetRepository.countByNameAndVersion(dSet.getName(), dSet.getVersion()) > 0) { throw new EntityAlreadyExistsException("DistributionSet with that name and version already exists."); } + return distributionSetRepository.save(dSet); } @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()); - } + public List createDistributionSets(final Collection creates) { + return creates.stream().map(this::createDistributionSet).collect(Collectors.toList()); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public DistributionSet assignSoftwareModules(final Long setId, final Collection moduleIds) { + final JpaDistributionSet set = findDistributionSetAndThrowExceptionIfNotFound(setId); + final Collection modules = softwareModuleRepository.findByIdIn(moduleIds); + + if (modules.size() < moduleIds.size()) { + throw new EntityNotFoundException("Not all given software modules where found."); } - @SuppressWarnings({ "unchecked", "rawtypes" }) - final Collection toSave = (Collection) distributionSets; + checkDistributionSetIsAssignedToTargets(set); + + modules.forEach(set::addModule); + + return distributionSetRepository.save(set); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public DistributionSet unassignSoftwareModule(final Long setId, final Long moduleId) { + final JpaDistributionSet set = findDistributionSetAndThrowExceptionIfNotFound(setId); + final JpaSoftwareModule module = findSoftwareModuleAndThrowExceptionIfNotFound(moduleId); + + checkDistributionSetIsAssignedToTargets(set); + + set.removeModule(module); - return Collections.unmodifiableList(distributionSetRepository.save(toSave)); + return distributionSetRepository.save(set); } @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); + public DistributionSetType updateDistributionSetType(final DistributionSetTypeUpdate u) { + final GenericDistributionSetTypeUpdate update = (GenericDistributionSetTypeUpdate) u; + + final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(update.getId()); + + update.getDescription().ifPresent(type::setDescription); + update.getColour().ifPresent(type::setColour); + + if (hasModules(update)) { + checkDistributionSetTypeSoftwareModuleTypesIsAllowedToModify(type); + + update.getMandatory().ifPresent( + mand -> softwareModuleTypeRepository.findByIdIn(mand).forEach(type::addMandatoryModuleType)); + update.getOptional().ifPresent( + opt -> softwareModuleTypeRepository.findByIdIn(opt).forEach(type::addOptionalModuleType)); } - return distributionSetRepository.save((JpaDistributionSet) ds); + + return distributionSetTypeRepository.save(type); + } + + private static boolean hasModules(final GenericDistributionSetTypeUpdate update) { + return update.getOptional().isPresent() || update.getMandatory().isPresent(); } @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); + public DistributionSetType assignMandatorySoftwareModuleTypes(final Long dsTypeId, + final Collection softwareModulesTypeIds) { + final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(dsTypeId); + + final Collection modules = softwareModuleTypeRepository + .findByIdIn(softwareModulesTypeIds); + + if (modules.size() < softwareModulesTypeIds.size()) { + throw new EntityNotFoundException("Not all given software module types where found."); + } + + checkDistributionSetTypeSoftwareModuleTypesIsAllowedToModify(type); + + modules.forEach(type::addMandatoryModuleType); + + return distributionSetTypeRepository.save(type); } @Override @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) - public DistributionSetType updateDistributionSetType(final DistributionSetType dsType) { - checkNotNull(dsType.getId()); + public DistributionSetType assignOptionalSoftwareModuleTypes(final Long dsTypeId, + final Collection softwareModulesTypeIds) { + final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(dsTypeId); - final JpaDistributionSetType persisted = distributionSetTypeRepository.findOne(dsType.getId()); + final Collection modules = softwareModuleTypeRepository + .findByIdIn(softwareModulesTypeIds); - // 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())); + if (modules.size() < softwareModulesTypeIds.size()) { + throw new EntityNotFoundException("Not all given software module types where found."); + } + + checkDistributionSetTypeSoftwareModuleTypesIsAllowedToModify(type); + + modules.forEach(type::addOptionalModuleType); + + return distributionSetTypeRepository.save(type); + } + + private void checkDistributionSetTypeSoftwareModuleTypesIsAllowedToModify(final JpaDistributionSetType type) { + if (distributionSetRepository.countByType(type) > 0) { + throw new EntityReadOnlyException(String.format( + "distribution set type %s is already assigned to distribution sets and cannot be changed", + type.getName())); } - return distributionSetTypeRepository.save((JpaDistributionSetType) dsType); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public DistributionSetType unassignSoftwareModuleType(final Long dsTypeId, final Long softwareModuleTypeId) { + final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(dsTypeId); + + checkDistributionSetTypeSoftwareModuleTypesIsAllowedToModify(type); + + type.removeModuleType(softwareModuleTypeId); + + return distributionSetTypeRepository.save(type); } @Override public Page findDistributionSetTypesAll(final String rsqlParam, final Pageable pageable) { - final Specification spec = RSQLUtility.parse(rsqlParam, - DistributionSetTypeFields.class, virtualPropertyReplacer); + final Specification spec = RSQLUtility.parse(rsqlParam, DistributionSetTypeFields.class, + virtualPropertyReplacer); return convertDsTPage(distributionSetTypeRepository.findAll(spec, pageable)); } @@ -452,12 +593,10 @@ public DistributionSetType findDistributionSetTypeByKey(final String 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!"); - } + public DistributionSetType createDistributionSetType(final DistributionSetTypeCreate c) { + final JpaDistributionSetTypeCreate create = (JpaDistributionSetTypeCreate) c; - return distributionSetTypeRepository.save((JpaDistributionSetType) type); + return distributionSetTypeRepository.save(create.build()); } @Override @@ -478,70 +617,60 @@ public void deleteDistributionSetType(final DistributionSetType ty) { @Override @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying - public DistributionSetMetadata createDistributionSetMetadata(final DistributionSetMetadata md) { - final JpaDistributionSetMetadata metadata = (JpaDistributionSetMetadata) md; + public List createDistributionSetMetadata(final Long dsId, final Collection md) { - if (distributionSetMetadataRepository.exists(metadata.getId())) { - throwMetadataKeyAlreadyExists(metadata.getId().getKey()); - } + md.forEach(meta -> checkAndThrowAlreadyIfDistributionSetMetadataExists( + new DsMetadataCompositeKey(dsId, meta.getKey()))); - touch(metadata.getDistributionSet()); - return distributionSetMetadataRepository.save(metadata); - } + final JpaDistributionSet set = touch(dsId); - @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 -> touch(m.getDistributionSet())); - - return new ArrayList<>( - (Collection) distributionSetMetadataRepository.save(metadata)); + return Collections.unmodifiableList(md.stream() + .map(meta -> distributionSetMetadataRepository + .save(new JpaDistributionSetMetadata(meta.getKey(), set, meta.getValue()))) + .collect(Collectors.toList())); } @Override @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying - public DistributionSetMetadata updateDistributionSetMetadata(final DistributionSetMetadata md) { - final JpaDistributionSetMetadata metadata = (JpaDistributionSetMetadata) md; + public DistributionSetMetadata updateDistributionSetMetadata(final Long dsId, final MetaData md) { // check if exists otherwise throw entity not found exception - findOne(metadata.getDistributionSet(), metadata.getKey()); + final JpaDistributionSetMetadata toUpdate = (JpaDistributionSetMetadata) findDistributionSetMetadata(dsId, + md.getKey()); + toUpdate.setValue(md.getValue()); // touch it to update the lock revision because we are modifying the // DS indirectly - touch(metadata.getDistributionSet()); - return distributionSetMetadataRepository.save(metadata); + touch(dsId); + return distributionSetMetadataRepository.save(toUpdate); } @Override @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying - public void deleteDistributionSetMetadata(final DistributionSet distributionSet, final String key) { + public void deleteDistributionSetMetadata(final Long distributionSet, final String key) { touch(distributionSet); distributionSetMetadataRepository.delete(new DsMetadataCompositeKey(distributionSet, key)); } /** - * Method to get the latest distribution set based on ds ID after the + * Method to get the latest distribution set based on DS ID after the * metadata changes for that distribution set. * - * @param distributionSet + * @param distId * Distribution set */ - private void touch(final DistributionSet distributionSet) { - final DistributionSet latestDistributionSet = findDistributionSetById(distributionSet.getId()); + private JpaDistributionSet touch(final Long distId) { + final DistributionSet latestDistributionSet = findDistributionSetAndThrowExceptionIfNotFound(distId); + // 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) latestDistributionSet).setLastModifiedAt(0L); + final JpaDistributionSet result = entityManager.merge((JpaDistributionSet) latestDistributionSet); + result.setLastModifiedAt(0L); + + return result; } @Override @@ -584,7 +713,7 @@ private static Page convertMdPage(final Page> buildDistributionSetSpecifications( final DistributionSetFilter distributionSetFilter) { - final List> specList = new ArrayList<>(7); + final List> specList = Lists.newArrayListWithExpectedSize(7); Specification spec; @@ -645,28 +774,20 @@ private static List> buildDistributionSetSpeci 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( + private void checkDistributionSetIsAssignedToTargets(final JpaDistributionSet distributionSet) { + if (actionRepository.countByDistributionSet(distributionSet) > 0) { + throw new EntityReadOnlyException( 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; + return distributionSetFilter.getSelectDSWithNoTag() != null && distributionSetFilter.getSelectDSWithNoTag(); } private static Boolean isTagsSelected(final DistributionSetFilter distributionSetFilter) { - if (distributionSetFilter.getTagNames() != null && !distributionSetFilter.getTagNames().isEmpty()) { - return true; - } - return false; + return !CollectionUtils.isEmpty(distributionSetFilter.getTagNames()); } /** @@ -696,10 +817,6 @@ private void checkAndThrowAlreadyIfDistributionSetMetadataExists(final DsMetadat } } - private static void throwMetadataKeyAlreadyExists(final String metadataKey) { - throw new EntityAlreadyExistsException("Metadata entry with key '" + metadataKey + "' already exists"); - } - @Override @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) @@ -708,7 +825,8 @@ public List assignTag(final Collection dsIds, final Distr allDs.forEach(ds -> ds.addTag(tag)); - return Collections.unmodifiableList(distributionSetRepository.save(allDs)); + return Collections + .unmodifiableList(allDs.stream().map(distributionSetRepository::save).collect(Collectors.toList())); } @Override @@ -734,13 +852,15 @@ public DistributionSet unAssignTag(final Long dsId, final DistributionSetTag dis private List unAssignTag(final Collection distributionSets, final DistributionSetTag tag) { distributionSets.forEach(ds -> ds.removeTag(tag)); - return distributionSetRepository.save(distributionSets); + return Collections.unmodifiableList( + distributionSets.stream().map(distributionSetRepository::save).collect(Collectors.toList())); } @Override @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) - public List createDistributionSetTypes(final Collection types) { + public List createDistributionSetTypes(final Collection types) { + return types.stream().map(this::createDistributionSetType).collect(Collectors.toList()); } @@ -756,11 +876,13 @@ public void deleteDistributionSet(final DistributionSet set) { @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()); + return toggleTagAssignment(sets.stream().map(DistributionSet::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 index d2d66d4840..43d67f5762 100644 --- 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 @@ -8,41 +8,25 @@ */ package org.eclipse.hawkbit.repository.jpa; -import java.util.Collection; - -import org.apache.commons.lang3.StringUtils; 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.JpaArtifact; -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.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.Artifact; -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.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.eclipse.hawkbit.repository.builder.ActionStatusBuilder; +import org.eclipse.hawkbit.repository.builder.DistributionSetBuilder; +import org.eclipse.hawkbit.repository.builder.DistributionSetTypeBuilder; +import org.eclipse.hawkbit.repository.builder.RolloutBuilder; +import org.eclipse.hawkbit.repository.builder.RolloutGroupBuilder; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleBuilder; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeBuilder; +import org.eclipse.hawkbit.repository.builder.TagBuilder; +import org.eclipse.hawkbit.repository.builder.TargetBuilder; +import org.eclipse.hawkbit.repository.builder.TargetFilterQueryBuilder; +import org.eclipse.hawkbit.repository.jpa.builder.JpaActionStatusBuilder; +import org.eclipse.hawkbit.repository.jpa.builder.JpaRolloutGroupBuilder; +import org.eclipse.hawkbit.repository.jpa.builder.JpaSoftwareModuleTypeBuilder; +import org.eclipse.hawkbit.repository.jpa.builder.JpaTagBuilder; +import org.eclipse.hawkbit.repository.jpa.builder.JpaTargetBuilder; +import org.eclipse.hawkbit.repository.jpa.model.JpaMetaData; +import org.eclipse.hawkbit.repository.model.MetaData; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; /** @@ -52,177 +36,74 @@ @Validated 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); - } + @Autowired + private DistributionSetBuilder distributionSetBuilder; - @Override - public Target generateTarget(final String controllerId) { - return new JpaTarget(controllerId); - } + @Autowired + private DistributionSetTypeBuilder distributionSetTypeBuilder; - @Override - public Target generateTarget(final String controllerId, final String securityToken) { - if (StringUtils.isEmpty(securityToken)) { - return new JpaTarget(controllerId); - } - return new JpaTarget(controllerId, securityToken); - } + @Autowired + private SoftwareModuleBuilder softwareModuleBuilder; - @Override - public TargetTag generateTargetTag() { - return new JpaTargetTag(); - } + @Autowired + private RolloutBuilder rolloutBuilder; - @Override - public DistributionSetTag generateDistributionSetTag() { - return new JpaDistributionSetTag(); - } + @Autowired + private TargetFilterQueryBuilder targetFilterQueryBuilder; @Override - public TargetTag generateTargetTag(final String name, final String description, final String colour) { - return new JpaTargetTag(name, description, colour); + public MetaData generateMetadata(final String key, final String value) { + return new JpaMetaData(key, value); } @Override - public DistributionSetTag generateDistributionSetTag(final String name, final String description, - final String colour) { - return new JpaDistributionSetTag(name, description, colour); + public DistributionSetTypeBuilder distributionSetType() { + return distributionSetTypeBuilder; } @Override - public TargetTag generateTargetTag(final String name) { - return new JpaTargetTag(name); + public DistributionSetBuilder distributionSet() { + return distributionSetBuilder; } @Override - public DistributionSetTag generateDistributionSetTag(final String name) { - return new JpaDistributionSetTag(name); + public TargetBuilder target() { + return new JpaTargetBuilder(); } @Override - public TargetFilterQuery generateTargetFilterQuery() { - return new JpaTargetFilterQuery(); + public TagBuilder tag() { + return new JpaTagBuilder(); } @Override - public TargetFilterQuery generateTargetFilterQuery(final String name, final String query) { - return new JpaTargetFilterQuery(name, query); + public TargetFilterQueryBuilder targetFilterQuery() { + return targetFilterQueryBuilder; } @Override - public TargetFilterQuery generateTargetFilterQuery(final String name, final String query, - final DistributionSet autoAssignDS) { - return new JpaTargetFilterQuery(name, query, (JpaDistributionSet) autoAssignDS); + public SoftwareModuleBuilder softwareModule() { + return softwareModuleBuilder; } @Override - public SoftwareModuleType generateSoftwareModuleType() { - return new JpaSoftwareModuleType(); + public SoftwareModuleTypeBuilder softwareModuleType() { + return new JpaSoftwareModuleTypeBuilder(); } @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; + public ActionStatusBuilder actionStatus() { + return new JpaActionStatusBuilder(); } @Override - public ActionStatus generateActionStatus(final Action action, final Status status, final Long occurredAt) { - return new JpaActionStatus(action, status, occurredAt); + public RolloutBuilder rollout() { + return rolloutBuilder; } @Override - public Artifact generateArtifact() { - return new JpaArtifact(); + public RolloutGroupBuilder rolloutGroup() { + return new JpaRolloutGroupBuilder(); } } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutGroupManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutGroupManagement.java index f5873b02cf..a9a8e0ec7c 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutGroupManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutGroupManagement.java @@ -118,7 +118,7 @@ public Page findAllRolloutGroupsWithDetailedStatus(final Long roll final Map> allStatesForRollout = getStatusCountItemForRolloutGroup( rolloutGroupIds); - for (final RolloutGroup rolloutGroup : rolloutGroups) { + for (final JpaRolloutGroup rolloutGroup : rolloutGroups) { final TotalTargetCountStatus totalTargetCountStatus = new TotalTargetCountStatus( allStatesForRollout.get(rolloutGroup.getId()), Long.valueOf(rolloutGroup.getTotalTargets())); rolloutGroup.setTotalTargetCountStatus(totalTargetCountStatus); @@ -129,7 +129,7 @@ public Page findAllRolloutGroupsWithDetailedStatus(final Long roll @Override public RolloutGroup findRolloutGroupWithDetailedStatus(final Long rolloutGroupId) { - final RolloutGroup rolloutGroup = findRolloutGroupById(rolloutGroupId); + final JpaRolloutGroup rolloutGroup = (JpaRolloutGroup) findRolloutGroupById(rolloutGroupId); final List rolloutStatusCountItems = actionRepository .getStatusCountByRolloutGroupId(rolloutGroupId); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutManagement.java index 042f7c9d56..f423a7d117 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutManagement.java @@ -11,9 +11,12 @@ import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.stream.Collectors; import javax.persistence.EntityManager; +import javax.persistence.EntityNotFoundException; +import javax.validation.ConstraintDeclarationException; import org.apache.commons.lang3.StringUtils; import org.eclipse.hawkbit.repository.DeploymentManagement; @@ -21,10 +24,14 @@ import org.eclipse.hawkbit.repository.RolloutGroupManagement; import org.eclipse.hawkbit.repository.RolloutManagement; import org.eclipse.hawkbit.repository.TargetManagement; +import org.eclipse.hawkbit.repository.builder.GenericRolloutUpdate; +import org.eclipse.hawkbit.repository.builder.RolloutCreate; +import org.eclipse.hawkbit.repository.builder.RolloutGroupCreate; +import org.eclipse.hawkbit.repository.builder.RolloutUpdate; import org.eclipse.hawkbit.repository.event.remote.entity.RolloutGroupCreatedEvent; +import org.eclipse.hawkbit.repository.exception.ConstraintViolationException; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; import org.eclipse.hawkbit.repository.exception.RolloutIllegalStateException; -import org.eclipse.hawkbit.repository.exception.RolloutVerificationException; import org.eclipse.hawkbit.repository.jpa.executor.AfterTransactionCommitExecutor; import org.eclipse.hawkbit.repository.jpa.model.JpaRollout; import org.eclipse.hawkbit.repository.jpa.model.JpaRolloutGroup; @@ -69,7 +76,6 @@ import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; -import org.springframework.util.Assert; import org.springframework.validation.annotation.Validated; /** @@ -81,7 +87,8 @@ public class JpaRolloutManagement implements RolloutManagement { private static final Logger LOGGER = LoggerFactory.getLogger(RolloutManagement.class); /** - * Maximum amount of targets that are assigned to a Rollout Group in one transaction. + * Maximum amount of targets that are assigned to a Rollout Group in one + * transaction. */ private static final long TRANSACTION_TARGETS = 1000; @@ -159,33 +166,32 @@ public Rollout findRolloutById(final Long rolloutId) { @Override @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying - public Rollout createRollout(final Rollout rollout, final int amountGroup, + public Rollout createRollout(final RolloutCreate rollout, final int amountGroup, final RolloutGroupConditions conditions) { RolloutHelper.verifyRolloutGroupParameter(amountGroup); - final JpaRollout savedRollout = createRollout((JpaRollout) rollout); + final JpaRollout savedRollout = createRollout((JpaRollout) rollout.build()); return createRolloutGroups(amountGroup, conditions, savedRollout); } @Override @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying - public Rollout createRollout(final Rollout rollout, - final List groups, - final RolloutGroupConditions conditions) { + public Rollout createRollout(final RolloutCreate rollout, final List groups, + final RolloutGroupConditions conditions) { RolloutHelper.verifyRolloutGroupParameter(groups.size()); - final JpaRollout savedRollout = createRollout((JpaRollout) rollout); + final JpaRollout savedRollout = createRollout((JpaRollout) rollout.build()); return createRolloutGroups(groups, conditions, savedRollout); } private JpaRollout createRollout(final JpaRollout rollout) { - JpaRollout existingRollout = rolloutRepository.findByName(rollout.getName()); - if(existingRollout != null) { + final JpaRollout existingRollout = rolloutRepository.findByName(rollout.getName()); + if (existingRollout != null) { throw new EntityAlreadyExistsException(existingRollout.getName()); } final Long totalTargets = targetManagement.countTargetByTargetFilterQuery(rollout.getTargetFilterQuery()); - if(totalTargets == 0) { - throw new RolloutVerificationException("Rollout does not match any existing targets"); + if (totalTargets == 0) { + throw new ConstraintViolationException("Rollout does not match any existing targets"); } rollout.setTotalTargets(totalTargets); return rolloutRepository.save(rollout); @@ -231,14 +237,14 @@ private Rollout createRolloutGroups(final int amountOfGroups, final RolloutGroup return rolloutRepository.save(savedRollout); } - private Rollout createRolloutGroups(final List groupList, final RolloutGroupConditions conditions, - final Rollout rollout) { + private Rollout createRolloutGroups(final List groupList, + final RolloutGroupConditions conditions, final Rollout rollout) { RolloutHelper.verifyRolloutInStatus(rollout, RolloutStatus.CREATING); final JpaRollout savedRollout = (JpaRollout) rollout; // Preparing the groups - final List groups = groupList.stream().map( - group -> RolloutHelper.prepareRolloutGroupWithDefaultConditions(group, conditions)) + final List groups = groupList.stream() + .map(group -> RolloutHelper.prepareRolloutGroupWithDefaultConditions(group, conditions)) .collect(Collectors.toList()); groups.forEach(RolloutHelper::verifyRolloutGroupHasConditions); @@ -289,14 +295,16 @@ private void publishRolloutGroupCreatedEventAfterCommit(final RolloutGroup group @Override @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying - public void fillRolloutGroupsWithTargets(final Rollout rollout) { + public void fillRolloutGroupsWithTargets(final Long rolloutId) { + final JpaRollout rollout = Optional.ofNullable(rolloutRepository.findOne(rolloutId)) + .orElseThrow(() -> new EntityNotFoundException("Rollout with id " + rolloutId + " not found.")); + RolloutHelper.verifyRolloutInStatus(rollout, RolloutStatus.CREATING); - final JpaRollout jpaRollout = (JpaRollout) rollout; - List rolloutGroups = RolloutHelper.getOrderedGroups(rollout); + final List rolloutGroups = RolloutHelper.getOrderedGroups(rollout); int readyGroups = 0; int totalTargets = 0; - for (RolloutGroup group : rolloutGroups) { + for (final RolloutGroup group : rolloutGroups) { if (group.getStatus() != RolloutGroupStatus.CREATING) { readyGroups++; totalTargets += group.getTotalTargets(); @@ -304,25 +312,26 @@ public void fillRolloutGroupsWithTargets(final Rollout rollout) { } final RolloutGroup filledGroup = fillRolloutGroupWithTargets(rollout, group); - if(filledGroup.getStatus() == RolloutGroupStatus.READY) { + if (filledGroup.getStatus() == RolloutGroupStatus.READY) { readyGroups++; totalTargets += filledGroup.getTotalTargets(); } } - // When all groups are ready the rollout status can be changed to be ready, too. - if(readyGroups == rolloutGroups.size()) { - jpaRollout.setStatus(RolloutStatus.READY); - jpaRollout.setLastCheck(0); - jpaRollout.setTotalTargets(totalTargets); - rolloutRepository.save(jpaRollout); + // When all groups are ready the rollout status can be changed to be + // ready, too. + if (readyGroups == rolloutGroups.size()) { + rollout.setStatus(RolloutStatus.READY); + rollout.setLastCheck(0); + rollout.setTotalTargets(totalTargets); + rolloutRepository.save(rollout); } } private RolloutGroup fillRolloutGroupWithTargets(final Rollout rollout, final RolloutGroup group1) { RolloutHelper.verifyRolloutInStatus(rollout, RolloutStatus.CREATING); - JpaRolloutGroup group = (JpaRolloutGroup) group1; + final JpaRolloutGroup group = (JpaRolloutGroup) group1; final String baseFilter = RolloutHelper.getTargetFilterQuery(rollout); final String groupTargetFilter; @@ -361,13 +370,13 @@ private RolloutGroup fillRolloutGroupWithTargets(final Rollout rollout, final Ro group.setTotalTargets(rolloutTargetGroupRepository.countByRolloutGroup(group).intValue()); return rolloutGroupRepository.save(group); - } catch (TransactionException e) { + } catch (final TransactionException e) { LOGGER.warn("Transaction assigning Targets to RolloutGroup failed", e); return group; } } - private Long runInNewCountingTransaction(final String transactionName, TransactionCallback action) { + private Long runInNewCountingTransaction(final String transactionName, final TransactionCallback action) { final DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName(transactionName); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); @@ -381,8 +390,8 @@ private long assignTargetsToGroupInNewTransaction(final Rollout rollout, final R final PageRequest pageRequest = new PageRequest(0, Math.toIntExact(limit)); final List readyGroups = RolloutHelper.getGroupsByStatusIncludingGroup(rollout, RolloutGroupStatus.READY, group); - Page targets = targetManagement.findAllTargetsByTargetFilterQueryAndNotInRolloutGroups(pageRequest, - readyGroups, targetFilter); + final Page targets = targetManagement + .findAllTargetsByTargetFilterQueryAndNotInRolloutGroups(pageRequest, readyGroups, targetFilter); createAssignmentOfTargetsToGroup(targets, group); @@ -398,7 +407,7 @@ private void verifyRolloutGroupTargetCounts(final List groups, fin final String baseFilter = RolloutHelper.getTargetFilterQuery(rollout); final long totalTargets = targetManagement.countTargetByTargetFilterQuery(baseFilter); if (totalTargets == 0) { - throw new RolloutVerificationException("Rollout target filter does not match any targets"); + throw new ConstraintDeclarationException("Rollout target filter does not match any targets"); } long targetCount = totalTargets; @@ -412,7 +421,8 @@ private void verifyRolloutGroupTargetCounts(final List groups, fin final long overlappingTargets = countOverlappingTargetsWithPreviousGroups(baseFilter, groups, group, i); final long realTargetsInGroup; - // Assume that targets which were not used in the previous groups are used in this group + // Assume that targets which were not used in the previous groups + // are used in this group if (overlappingTargets > 0 && unusedTargetsCount > 0) { realTargetsInGroup = targetsInGroupFilter - overlappingTargets + unusedTargetsCount; unusedTargetsCount = 0; @@ -435,15 +445,14 @@ private long countTargetsOfGroup(final String baseFilter, final long baseFilterC if (StringUtils.isEmpty(group.getTargetFilterQuery())) { return baseFilterCount; } else { - return targetManagement - .countTargetByTargetFilterQuery(baseFilter + ";" + group.getTargetFilterQuery()); + return targetManagement.countTargetByTargetFilterQuery(baseFilter + ";" + group.getTargetFilterQuery()); } } private long countOverlappingTargetsWithPreviousGroups(final String baseFilter, final List groups, final RolloutGroup group, final int groupIndex) { // there can't be overlapping targets in the first group - if(groupIndex == 0) { + if (groupIndex == 0) { return 0; } final List previousGroups = groups.subList(0, groupIndex); @@ -536,7 +545,7 @@ private long createActionsForRolloutGroup(final Rollout rollout, final RolloutGr totalActionsCreated += actionsCreated; } while (actionsCreated > 0); - } catch (TransactionException e) { + } catch (final TransactionException e) { LOGGER.warn("Transaction assigning Targets to RolloutGroup failed", e); return 0; } @@ -553,7 +562,7 @@ private long createActionsForTargetsInNewTransaction(final long rolloutId, final final ActionType actionType = rollout.getActionType(); final long forceTime = rollout.getForcedTime(); - Page targets = targetManagement.findAllTargetsInRolloutGroupWithoutAction(pageRequest, group); + final Page targets = targetManagement.findAllTargetsInRolloutGroupWithoutAction(pageRequest, group); if (targets.getTotalElements() > 0) { deploymentManagement.createScheduledAction(targets.getContent(), distributionSet, actionType, forceTime, rollout, group); @@ -759,19 +768,19 @@ private void executeRolloutGroupSuccessAction(final Rollout rollout, final Rollo @Override @Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_UNCOMMITTED) @Modifying - public void checkCreatingRollouts(long delayBetweenChecks) { + public void checkCreatingRollouts(final long delayBetweenChecks) { final long lastCheck = System.currentTimeMillis(); final int updated = rolloutRepository.updateLastCheck(lastCheck, delayBetweenChecks, RolloutStatus.CREATING); if (updated == 0) { // nothing to check, maybe another instance already checked in // between - LOGGER.debug("No rollouts creating check necessary for current scheduled check {}, next check at {}", lastCheck, - lastCheck + delayBetweenChecks); + LOGGER.debug("No rollouts creating check necessary for current scheduled check {}, next check at {}", + lastCheck, lastCheck + delayBetweenChecks); return; } - final List rolloutsToCheck = rolloutRepository.findByLastCheckAndStatus(lastCheck, - RolloutStatus.CREATING); + final List rolloutsToCheck = rolloutRepository.findByLastCheckAndStatus(lastCheck, RolloutStatus.CREATING) + .stream().map(Rollout::getId).collect(Collectors.toList()); LOGGER.info("Found {} creating rollouts to check", rolloutsToCheck.size()); rolloutsToCheck.forEach(this::fillRolloutGroupsWithTargets); @@ -781,14 +790,14 @@ public void checkCreatingRollouts(long delayBetweenChecks) { @Override @Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_UNCOMMITTED) @Modifying - public void checkStartingRollouts(long delayBetweenChecks) { + public void checkStartingRollouts(final long delayBetweenChecks) { final long lastCheck = System.currentTimeMillis(); final int updated = rolloutRepository.updateLastCheck(lastCheck, delayBetweenChecks, RolloutStatus.STARTING); if (updated == 0) { // nothing to check, maybe another instance already checked in // between - LOGGER.debug("No rollouts starting check necessary for current scheduled check {}, next check at {}", lastCheck, - lastCheck + delayBetweenChecks); + LOGGER.debug("No rollouts starting check necessary for current scheduled check {}, next check at {}", + lastCheck, lastCheck + delayBetweenChecks); return; } @@ -797,7 +806,7 @@ public void checkStartingRollouts(long delayBetweenChecks) { LOGGER.info("Found {} starting rollouts to check", rolloutsToCheck.size()); rolloutsToCheck.forEach(rollout -> { - if(ensureAllGroupsAreScheduled(rollout)) { + if (ensureAllGroupsAreScheduled(rollout)) { startFirstRolloutGroup(rollout); } }); @@ -837,31 +846,20 @@ public Rollout findRolloutByName(final String rolloutName) { return rolloutRepository.findByName(rolloutName); } - /** - * Update rollout details. - * - * @param rollout - * rollout to be updated - * - * @return Rollout updated rollout - */ @Override @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying - public Rollout updateRollout(final Rollout rollout) { - Assert.notNull(rollout.getId()); - return rolloutRepository.save((JpaRollout) rollout); + public Rollout updateRollout(final RolloutUpdate u) { + final GenericRolloutUpdate update = (GenericRolloutUpdate) u; + final JpaRollout rollout = Optional.ofNullable(rolloutRepository.findOne(update.getId())) + .orElseThrow(() -> new EntityNotFoundException("Rollout with id " + update.getId() + " not found.")); + + update.getName().ifPresent(rollout::setName); + update.getDescription().ifPresent(rollout::setDescription); + + return rolloutRepository.save(rollout); } - /** - * 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 - * - */ @Override public Page findAllRolloutsWithDetailedStatus(final Pageable pageable) { final Page rollouts = rolloutRepository.findAll(pageable); 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 index cc41c8ce35..9220be8472 100644 --- 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 @@ -8,15 +8,13 @@ */ 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.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -34,8 +32,16 @@ import org.eclipse.hawkbit.repository.SoftwareModuleFields; import org.eclipse.hawkbit.repository.SoftwareModuleMetadataFields; import org.eclipse.hawkbit.repository.SoftwareModuleTypeFields; +import org.eclipse.hawkbit.repository.builder.GenericSoftwareModuleTypeUpdate; +import org.eclipse.hawkbit.repository.builder.GenericSoftwareModuleUpdate; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleCreate; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeCreate; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeUpdate; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleUpdate; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; +import org.eclipse.hawkbit.repository.jpa.builder.JpaSoftwareModuleCreate; +import org.eclipse.hawkbit.repository.jpa.builder.JpaSoftwareModuleTypeCreate; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet_; import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; @@ -50,6 +56,7 @@ import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.AssignedSoftwareModule; import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.repository.model.MetaData; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; @@ -113,80 +120,65 @@ public class JpaSoftwareManagement implements SoftwareManagement { @Override @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) - public SoftwareModule updateSoftwareModule(final SoftwareModule sm) { - checkNotNull(sm.getId()); + public SoftwareModule updateSoftwareModule(final SoftwareModuleUpdate u) { + final GenericSoftwareModuleUpdate update = (GenericSoftwareModuleUpdate) u; - final JpaSoftwareModule module = softwareModuleRepository.findOne(sm.getId()); + final JpaSoftwareModule module = Optional.ofNullable(softwareModuleRepository.findOne(update.getId())) + .orElseThrow(() -> new EntityNotFoundException( + "Software module cannot be updated as it does not exixt" + update.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; - } + update.getDescription().ifPresent(module::setDescription); + update.getVendor().ifPresent(module::setVendor); - return updated ? softwareModuleRepository.save(module) : module; + return softwareModuleRepository.save(module); } @Override @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) - public SoftwareModuleType updateSoftwareModuleType(final SoftwareModuleType sm) { - checkNotNull(sm.getId()); + public SoftwareModuleType updateSoftwareModuleType(final SoftwareModuleTypeUpdate u) { + final GenericSoftwareModuleTypeUpdate update = (GenericSoftwareModuleTypeUpdate) u; - final JpaSoftwareModuleType type = softwareModuleTypeRepository.findOne(sm.getId()); + final JpaSoftwareModuleType type = findSoftwareModuleTypeAndThrowExceptionIfNotFound(update.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; + update.getDescription().ifPresent(type::setDescription); + update.getColour().ifPresent(type::setColour); + + return softwareModuleTypeRepository.save(type); + } + + private JpaSoftwareModuleType findSoftwareModuleTypeAndThrowExceptionIfNotFound(final Long smTypeid) { + final JpaSoftwareModuleType set = softwareModuleTypeRepository.findOne(smTypeid); + + if (set == null) { + throw new EntityNotFoundException("Software module type cannot be updated as it does not exixt" + smTypeid); } - return updated ? softwareModuleTypeRepository.save(type) : type; + return set; } @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); + public SoftwareModule createSoftwareModule(final SoftwareModuleCreate c) { + final JpaSoftwareModuleCreate create = (JpaSoftwareModuleCreate) c; + + return softwareModuleRepository.save(create.build()); } @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 Collections.unmodifiableList(softwareModuleRepository.save(jpaCast)); + public List createSoftwareModule(final Collection swModules) { + return swModules.stream().map(this::createSoftwareModule).collect(Collectors.toList()); } @Override public Slice findSoftwareModulesByType(final Pageable pageable, final Long typeId) { - final List> specList = new LinkedList<>(); + final List> specList = Lists.newArrayListWithExpectedSize(2); - Specification spec = SoftwareModuleSpecification.equalType(typeId); - specList.add(spec); - - spec = SoftwareModuleSpecification.isDeletedFalse(); - specList.add(spec); + specList.add(SoftwareModuleSpecification.equalType(typeId)); + specList.add(SoftwareModuleSpecification.isDeletedFalse()); return convertSmPage(findSwModuleByCriteriaAPI(pageable, specList), pageable); } @@ -218,7 +210,7 @@ public SoftwareModule findSoftwareModuleByNameAndVersion(final String name, fina } private boolean isUnassigned(final JpaSoftwareModule bsmMerged) { - return distributionSetRepository.findByModules(bsmMerged).isEmpty(); + return distributionSetRepository.countByModules(bsmMerged) <= 0; } private Slice findSwModuleByCriteriaAPI(final Pageable pageable, @@ -423,7 +415,7 @@ public Slice findSoftwareModuleOrderBySetAssignmentAndMo private static List> buildSpecificationList(final String searchText, final Long typeId) { - final List> specList = new ArrayList<>(3); + final List> specList = Lists.newArrayListWithExpectedSize(3); if (!Strings.isNullOrEmpty(searchText)) { specList.add(SoftwareModuleSpecification.likeNameOrVersion(searchText)); } @@ -491,12 +483,10 @@ public SoftwareModuleType findSoftwareModuleTypeByName(final String 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!"); - } + public SoftwareModuleType createSoftwareModuleType(final SoftwareModuleTypeCreate c) { + final JpaSoftwareModuleTypeCreate create = (JpaSoftwareModuleTypeCreate) c; - return softwareModuleTypeRepository.save((JpaSoftwareModuleType) type); + return softwareModuleTypeRepository.save(create.build()); } @Override @@ -523,53 +513,74 @@ public Page findSoftwareModuleByAssignedTo(final Pageable pageab @Override @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying - public SoftwareModuleMetadata createSoftwareModuleMetadata(final SoftwareModuleMetadata md) { - final JpaSoftwareModuleMetadata metadata = (JpaSoftwareModuleMetadata) md; + public SoftwareModuleMetadata createSoftwareModuleMetadata(final Long moduleId, final MetaData md) { + + checkAndThrowAlreadyIfSoftwareModuleMetadataExists(moduleId, md); - if (softwareModuleMetadataRepository.exists(metadata.getId())) { - throwMetadataKeyAlreadyExists(metadata.getId().getKey()); + return softwareModuleMetadataRepository + .save(new JpaSoftwareModuleMetadata(md.getKey(), touch(moduleId), md.getValue())); + } + + private void checkAndThrowAlreadyIfSoftwareModuleMetadataExists(final Long moduleId, final MetaData md) { + if (softwareModuleMetadataRepository.exists(new SwMetadataCompositeKey(moduleId, md.getKey()))) { + throwMetadataKeyAlreadyExists(md.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; + public List createSoftwareModuleMetadata(final Long moduleId, + final Collection md) { + md.forEach(meta -> checkAndThrowAlreadyIfSoftwareModuleMetadataExists(moduleId, meta)); - for (final JpaSoftwareModuleMetadata softwareModuleMetadata : metadata) { - checkAndThrowAlreadyExistsIfSoftwareModuleMetadataExists(softwareModuleMetadata.getId()); - } - metadata.forEach(m -> entityManager.merge((JpaSoftwareModule) m.getSoftwareModule()).setLastModifiedAt(-1L)); - return Collections.unmodifiableList(softwareModuleMetadataRepository.save(metadata)); + final JpaSoftwareModule module = touch(moduleId); + + return Collections.unmodifiableList(md.stream() + .map(meta -> softwareModuleMetadataRepository + .save(new JpaSoftwareModuleMetadata(meta.getKey(), module, meta.getValue()))) + .collect(Collectors.toList())); } @Override @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying - public SoftwareModuleMetadata updateSoftwareModuleMetadata(final SoftwareModuleMetadata md) { - final JpaSoftwareModuleMetadata metadata = (JpaSoftwareModuleMetadata) md; + public SoftwareModuleMetadata updateSoftwareModuleMetadata(final Long moduleId, final MetaData 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); + final JpaSoftwareModuleMetadata metadata = findSoftwareModuleMetadata( + new SwMetadataCompositeKey(moduleId, md.getKey())); + metadata.setValue(md.getValue()); + + touch(moduleId); return softwareModuleMetadataRepository.save(metadata); } + /** + * Method to get the latest module based on ID after the metadata changes + * for that module. + * + * @param distributionSet + * Distribution set + */ + private JpaSoftwareModule touch(final Long moduleId) { + final JpaSoftwareModule latestModule = softwareModuleRepository.findOne(moduleId); + + // 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. + final JpaSoftwareModule result = entityManager.merge(latestModule); + result.setLastModifiedAt(0L); + + return result; + } + @Override @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying public void deleteSoftwareModuleMetadata(final Long moduleId, final String key) { + touch(moduleId); softwareModuleMetadataRepository.delete(new SwMetadataCompositeKey(moduleId, key)); } @@ -609,8 +620,8 @@ public SoftwareModuleMetadata findSoftwareModuleMetadata(final Long moduleId, fi return findSoftwareModuleMetadata(new SwMetadataCompositeKey(moduleId, key)); } - private SoftwareModuleMetadata findSoftwareModuleMetadata(final SwMetadataCompositeKey id) { - final SoftwareModuleMetadata findOne = softwareModuleMetadataRepository.findOne(id); + private JpaSoftwareModuleMetadata findSoftwareModuleMetadata(final SwMetadataCompositeKey id) { + final JpaSoftwareModuleMetadata findOne = softwareModuleMetadataRepository.findOne(id); if (findOne == null) { throw new EntityNotFoundException("Metadata with key '" + id.getKey() + "' does not exist"); } @@ -638,9 +649,13 @@ public void deleteSoftwareModule(final Long moduleId) { @Override @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) - public List createSoftwareModuleType(final Collection types) { + public List createSoftwareModuleType(final Collection creates) { + return creates.stream().map(this::createSoftwareModuleType).collect(Collectors.toList()); + } - return types.stream().map(this::createSoftwareModuleType).collect(Collectors.toList()); + @Override + public List findSoftwareModuleTypesById(final Collection ids) { + return Collections.unmodifiableList(softwareModuleTypeRepository.findByIdIn(ids)); } } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSystemManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSystemManagement.java index 34afd0c8f5..38d3d81b88 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSystemManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSystemManagement.java @@ -18,7 +18,6 @@ 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.configuration.MultiTenantJpaTransactionManager; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType; import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType; @@ -205,7 +204,7 @@ private TenantMetaData createInitialTenantMetaData(final String tenant) { @Override public List findTenants() { - return tenantMetaDataRepository.findAll().stream().map(md -> md.getTenant()).collect(Collectors.toList()); + return tenantMetaDataRepository.findAll().stream().map(TenantMetaData::getTenant).collect(Collectors.toList()); } @Override @@ -270,12 +269,12 @@ public String currentTenant() { @Override @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying - public TenantMetaData updateTenantMetadata(final TenantMetaData metaData) { - if (!tenantMetaDataRepository.exists(metaData.getId())) { - throw new EntityNotFoundException("Metadata does not exist: " + metaData.getId()); - } + public TenantMetaData updateTenantMetadata(final Long defaultDsType) { + final JpaTenantMetaData data = (JpaTenantMetaData) getTenantMetadata(); + + data.setDefaultDsType(distributionSetTypeRepository.findOne(defaultDsType)); - return tenantMetaDataRepository.save((JpaTenantMetaData) metaData); + return tenantMetaDataRepository.save(data); } private DistributionSetType createStandardSoftwareDataSetup() { @@ -285,19 +284,19 @@ private DistributionSetType createStandardSoftwareDataSetup() { 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)); + // make sure the module types get their IDs + entityManager.flush(); + + distributionSetTypeRepository.save(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)); + return distributionSetTypeRepository.save(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)); } @Override public TenantMetaData getTenantMetadata(final Long tenantId) { return tenantMetaDataRepository.findOne(tenantId); } -} \ 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 index 4ef8ed14ab..15c2ce6012 100644 --- 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 @@ -8,15 +8,17 @@ */ package org.eclipse.hawkbit.repository.jpa; -import static com.google.common.base.Preconditions.checkNotNull; - import java.util.Collection; import java.util.Collections; -import java.util.LinkedList; import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; import org.eclipse.hawkbit.repository.TagFields; import org.eclipse.hawkbit.repository.TagManagement; +import org.eclipse.hawkbit.repository.builder.GenericTagUpdate; +import org.eclipse.hawkbit.repository.builder.TagCreate; +import org.eclipse.hawkbit.repository.builder.TagUpdate; import org.eclipse.hawkbit.repository.event.remote.DistributionSetTagDeletedEvent; import org.eclipse.hawkbit.repository.event.remote.TargetTagDeletedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetTagCreatedEvent; @@ -24,16 +26,16 @@ import org.eclipse.hawkbit.repository.event.remote.entity.TargetTagCreatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.TargetTagUpdateEvent; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; +import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; +import org.eclipse.hawkbit.repository.jpa.builder.JpaTagCreate; 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.rsql.VirtualPropertyReplacer; import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.repository.model.TargetTag; import org.eclipse.hawkbit.repository.model.helper.EventPublisherHolder; +import org.eclipse.hawkbit.repository.rsql.VirtualPropertyReplacer; import org.eclipse.hawkbit.tenancy.TenantAware; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; @@ -78,7 +80,7 @@ public class JpaTagManagement implements TagManagement { @Autowired private TenantAware tenantAware; - + @Autowired private VirtualPropertyReplacer virtualPropertyReplacer; @@ -89,16 +91,16 @@ public TargetTag findTargetTag(final String name) { @Override @Transactional(isolation = Isolation.READ_UNCOMMITTED) - public TargetTag createTargetTag(final TargetTag targetTag) { - if (null != targetTag.getId()) { - throw new EntityAlreadyExistsException(); - } + public TargetTag createTargetTag(final TagCreate c) { + final JpaTagCreate create = (JpaTagCreate) c; + + final JpaTargetTag targetTag = create.buildTargetTag(); if (findTargetTag(targetTag.getName()) != null) { throw new EntityAlreadyExistsException(); } - final TargetTag save = targetTagRepository.save((JpaTargetTag) targetTag); + final TargetTag save = targetTagRepository.save(targetTag); afterCommit.afterCommit( () -> eventPublisher.publishEvent(new TargetTagCreatedEvent(save, applicationContext.getId()))); @@ -109,17 +111,12 @@ public TargetTag createTargetTag(final TargetTag targetTag) { @Override @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) - public List createTargetTags(final Collection tt) { + 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 Collection targetTags = (Collection) tt; - final List save = Collections.unmodifiableList(targetTagRepository.save(targetTags)); + final List save = Collections.unmodifiableList(targetTags.stream() + .map(ttc -> targetTagRepository.save(ttc.buildTargetTag())).collect(Collectors.toList())); afterCommit.afterCommit(() -> save.forEach( tag -> eventPublisher.publishEvent(new TargetTagCreatedEvent(tag, applicationContext.getId())))); return save; @@ -131,14 +128,10 @@ public List createTargetTags(final Collection tt) { 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.removeTag(tag); - changed.add(target); - } - - // save association delete - targetRepository.save(changed); + targetRepository.findByTag(tag).forEach(set -> { + set.removeTag(tag); + targetRepository.save(set); + }); // finally delete the tag itself targetTagRepository.deleteByName(targetTagName); @@ -177,15 +170,42 @@ public long countTargetTags() { @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); + public TargetTag updateTargetTag(final TagUpdate u) { + final GenericTagUpdate update = (GenericTagUpdate) u; + + final JpaTargetTag tag = Optional.ofNullable(targetTagRepository.findOne(update.getId())) + .orElseThrow(() -> new EntityNotFoundException("Target tag with ID " + update.getId() + " not found")); + + update.getName().ifPresent(tag::setName); + update.getDescription().ifPresent(tag::setDescription); + update.getColour().ifPresent(tag::setColour); + + final TargetTag save = targetTagRepository.save(tag); afterCommit.afterCommit(() -> eventPublisher .publishEvent(new TargetTagUpdateEvent(save, EventPublisherHolder.getInstance().getApplicationId()))); return save; } + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public DistributionSetTag updateDistributionSetTag(final TagUpdate u) { + final GenericTagUpdate update = (GenericTagUpdate) u; + + final JpaDistributionSetTag tag = Optional.ofNullable(distributionSetTagRepository.findOne(update.getId())) + .orElseThrow(() -> new EntityNotFoundException( + "Distribution set tag with ID " + update.getId() + " not found")); + + update.getName().ifPresent(tag::setName); + update.getDescription().ifPresent(tag::setDescription); + update.getColour().ifPresent(tag::setColour); + + final DistributionSetTag save = distributionSetTagRepository.save(tag); + afterCommit.afterCommit(() -> eventPublisher.publishEvent( + new DistributionSetTagUpdateEvent(save, EventPublisherHolder.getInstance().getApplicationId()))); + return save; + } + @Override public DistributionSetTag findDistributionSetTag(final String name) { return distributionSetTagRepository.findByNameEquals(name); @@ -194,16 +214,16 @@ public DistributionSetTag findDistributionSetTag(final String name) { @Override @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) - public DistributionSetTag createDistributionSetTag(final DistributionSetTag distributionSetTag) { - if (null != distributionSetTag.getId()) { - throw new EntityAlreadyExistsException(); - } + public DistributionSetTag createDistributionSetTag(final TagCreate c) { + final JpaTagCreate create = (JpaTagCreate) c; + + final JpaDistributionSetTag distributionSetTag = create.buildDistributionSetTag(); if (distributionSetTagRepository.findByNameEquals(distributionSetTag.getName()) != null) { throw new EntityAlreadyExistsException(); } - final DistributionSetTag save = distributionSetTagRepository.save((JpaDistributionSetTag) distributionSetTag); + final DistributionSetTag save = distributionSetTagRepository.save(distributionSetTag); afterCommit.afterCommit(() -> eventPublisher .publishEvent(new DistributionSetTagCreatedEvent(save, applicationContext.getId()))); @@ -213,18 +233,14 @@ public DistributionSetTag createDistributionSetTag(final DistributionSetTag dist @Override @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) - public List createDistributionSetTags(final Collection dst) { + public List createDistributionSetTags(final Collection dst) { @SuppressWarnings({ "rawtypes", "unchecked" }) - final Collection distributionSetTags = (Collection) dst; + final Collection creates = (Collection) dst; - for (final DistributionSetTag dsTag : distributionSetTags) { - if (dsTag.getId() != null) { - throw new EntityAlreadyExistsException(); - } - } - final List save = Collections - .unmodifiableList(distributionSetTagRepository.save(distributionSetTags)); + final List save = Collections.unmodifiableList( + creates.stream().map(create -> distributionSetTagRepository.save(create.buildDistributionSetTag())) + .collect(Collectors.toList())); afterCommit.afterCommit(() -> save.forEach(tag -> eventPublisher .publishEvent(new DistributionSetTagCreatedEvent(tag, applicationContext.getId())))); return save; @@ -236,14 +252,10 @@ public List createDistributionSetTags(final Collection changed = new LinkedList<>(); - for (final JpaDistributionSet set : distributionSetRepository.findByTag(tag)) { + distributionSetRepository.findByTag(tag).forEach(set -> { set.removeTag(tag); - changed.add(set); - } - - // save association delete - distributionSetRepository.save(changed); + distributionSetRepository.save(set); + }); distributionSetTagRepository.deleteByName(tagName); @@ -252,19 +264,6 @@ public void deleteDistributionSetTag(final String tagName) { tag.getId(), applicationContext.getId()))); } - @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(() -> eventPublisher.publishEvent( - new DistributionSetTagUpdateEvent(save, EventPublisherHolder.getInstance().getApplicationId()))); - - return save; - } - @Override public List findAllDistributionSetTags() { return Collections.unmodifiableList(distributionSetTagRepository.findAll()); 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 index 02e59b0c34..9fd061bdad 100644 --- 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 @@ -11,20 +11,28 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Optional; import javax.validation.constraints.NotNull; +import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.TargetFields; import org.eclipse.hawkbit.repository.TargetFilterQueryFields; import org.eclipse.hawkbit.repository.TargetFilterQueryManagement; +import org.eclipse.hawkbit.repository.builder.GenericTargetFilterQueryUpdate; +import org.eclipse.hawkbit.repository.builder.TargetFilterQueryCreate; +import org.eclipse.hawkbit.repository.builder.TargetFilterQueryUpdate; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; +import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; +import org.eclipse.hawkbit.repository.jpa.builder.JpaTargetFilterQueryCreate; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; import org.eclipse.hawkbit.repository.jpa.model.JpaTargetFilterQuery; import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility; -import org.eclipse.hawkbit.repository.rsql.VirtualPropertyReplacer; import org.eclipse.hawkbit.repository.jpa.specifications.SpecificationsBuilder; import org.eclipse.hawkbit.repository.jpa.specifications.TargetFilterQuerySpecification; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.TargetFilterQuery; +import org.eclipse.hawkbit.repository.rsql.VirtualPropertyReplacer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; @@ -34,7 +42,6 @@ import org.springframework.data.jpa.repository.Modifying; 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; @@ -53,15 +60,21 @@ public class JpaTargetFilterQueryManagement implements TargetFilterQueryManageme @Autowired private VirtualPropertyReplacer virtualPropertyReplacer; + @Autowired + private DistributionSetManagement distributionSetManagement; + @Override @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) - public TargetFilterQuery createTargetFilterQuery(final TargetFilterQuery customTargetFilter) { + public TargetFilterQuery createTargetFilterQuery(final TargetFilterQueryCreate c) { + final JpaTargetFilterQueryCreate create = (JpaTargetFilterQueryCreate) c; + + final JpaTargetFilterQuery query = create.build(); - if (targetFilterQueryRepository.findByName(customTargetFilter.getName()) != null) { - throw new EntityAlreadyExistsException(customTargetFilter.getName()); + if (targetFilterQueryRepository.findByName(query.getName()) != null) { + throw new EntityAlreadyExistsException(query.getName()); } - return targetFilterQueryRepository.save((JpaTargetFilterQuery) customTargetFilter); + return targetFilterQueryRepository.save(query); } @Override @@ -96,7 +109,8 @@ public Page findTargetFilterQueryByName(final Pageable pageab } @Override - public Page findTargetFilterQueryByFilter(@NotNull Pageable pageable, String rsqlFilter) { + public Page findTargetFilterQueryByFilter(@NotNull final Pageable pageable, + final String rsqlFilter) { List> specList = Collections.emptyList(); if (!Strings.isNullOrEmpty(rsqlFilter)) { specList = Collections.singletonList( @@ -106,14 +120,14 @@ public Page findTargetFilterQueryByFilter(@NotNull Pageable p } @Override - public Page findTargetFilterQueryByAutoAssignDS(@NotNull Pageable pageable, - DistributionSet distributionSet) { + public Page findTargetFilterQueryByAutoAssignDS(@NotNull final Pageable pageable, + final DistributionSet distributionSet) { return findTargetFilterQueryByAutoAssignDS(pageable, distributionSet, null); } @Override - public Page findTargetFilterQueryByAutoAssignDS(@NotNull Pageable pageable, - DistributionSet distributionSet, String rsqlFilter) { + public Page findTargetFilterQueryByAutoAssignDS(@NotNull final Pageable pageable, + final DistributionSet distributionSet, final String rsqlFilter) { final List> specList = new ArrayList<>(2); if (distributionSet != null) { specList.add(TargetFilterQuerySpecification.byAutoAssignDS(distributionSet)); @@ -125,7 +139,7 @@ public Page findTargetFilterQueryByAutoAssignDS(@NotNull Page } @Override - public Page findTargetFilterQueryWithAutoAssignDS(@NotNull Pageable pageable) { + public Page findTargetFilterQueryWithAutoAssignDS(@NotNull final Pageable pageable) { final List> specList = Collections .singletonList(TargetFilterQuerySpecification.withAutoAssignDS()); return convertPage(findTargetFilterQueryByCriteriaAPI(pageable, specList), pageable); @@ -154,9 +168,42 @@ public TargetFilterQuery findTargetFilterQueryById(final Long targetFilterQueryI @Override @Modifying @Transactional(isolation = Isolation.READ_UNCOMMITTED) - public TargetFilterQuery updateTargetFilterQuery(final TargetFilterQuery targetFilterQuery) { - Assert.notNull(targetFilterQuery.getId()); - return targetFilterQueryRepository.save((JpaTargetFilterQuery) targetFilterQuery); + public TargetFilterQuery updateTargetFilterQuery(final TargetFilterQueryUpdate u) { + final GenericTargetFilterQueryUpdate update = (GenericTargetFilterQueryUpdate) u; + + final JpaTargetFilterQuery targetFilterQuery = findTargetFilterQueryOrThrowExceptionIfNotFound(update.getId()); + + update.getName().ifPresent(targetFilterQuery::setName); + update.getQuery().ifPresent(targetFilterQuery::setQuery); + + return targetFilterQueryRepository.save(targetFilterQuery); + } + + @Override + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) + public TargetFilterQuery updateTargetFilterQueryAutoAssignDS(final Long queryId, final Long dsId) { + final JpaTargetFilterQuery targetFilterQuery = findTargetFilterQueryOrThrowExceptionIfNotFound(queryId); + + targetFilterQuery.setAutoAssignDistributionSet( + Optional.ofNullable(dsId).map(this::findDistributionSetAndThrowExceptionIfNotFound).orElse(null)); + + return targetFilterQueryRepository.save(targetFilterQuery); + } + + private JpaDistributionSet findDistributionSetAndThrowExceptionIfNotFound(final Long setId) { + final JpaDistributionSet set = (JpaDistributionSet) distributionSetManagement + .findDistributionSetByIdWithDetails(setId); + + if (set == null) { + throw new EntityNotFoundException("Distribution set cannot be updated as it does not exixt" + setId); + } + return set; + } + + private JpaTargetFilterQuery findTargetFilterQueryOrThrowExceptionIfNotFound(final Long queryId) { + return Optional.ofNullable(targetFilterQueryRepository.findOne(queryId)).orElseThrow( + () -> new EntityNotFoundException("TargetFilterQuery with given ID " + queryId + " not found!")); } @Override 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 index e8932927e3..1f3d25500c 100644 --- 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 @@ -8,12 +8,12 @@ */ 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.Optional; import java.util.stream.Collectors; import javax.persistence.EntityManager; @@ -32,10 +32,14 @@ import org.eclipse.hawkbit.repository.TargetFields; import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.TimestampCalculator; +import org.eclipse.hawkbit.repository.builder.TargetCreate; +import org.eclipse.hawkbit.repository.builder.TargetUpdate; import org.eclipse.hawkbit.repository.event.remote.TargetDeletedEvent; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; +import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; +import org.eclipse.hawkbit.repository.jpa.builder.JpaTargetCreate; +import org.eclipse.hawkbit.repository.jpa.builder.JpaTargetUpdate; 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; @@ -43,19 +47,18 @@ 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.model.RolloutGroup; -import org.eclipse.hawkbit.repository.rsql.VirtualPropertyReplacer; import org.eclipse.hawkbit.repository.jpa.specifications.SpecificationsBuilder; import org.eclipse.hawkbit.repository.jpa.specifications.TargetSpecifications; +import org.eclipse.hawkbit.repository.model.RolloutGroup; 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.eclipse.hawkbit.repository.rsql.VirtualPropertyReplacer; import org.eclipse.hawkbit.tenancy.TenantAware; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.annotation.CacheEvict; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEventPublisher; import org.springframework.data.domain.Page; @@ -69,7 +72,6 @@ import org.springframework.data.jpa.repository.Modifying; 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.collect.Lists; @@ -106,9 +108,6 @@ public class JpaTargetManagement implements TargetManagement { @Autowired private TenantAware tenantAware; - @Autowired - private AfterTransactionCommitExecutor afterCommit; - @Autowired private VirtualPropertyReplacer virtualPropertyReplacer; @@ -163,8 +162,7 @@ public Slice findTargetsAll(final Pageable pageable) { @Override public Slice findTargetsAll(final TargetFilterQuery targetFilterQuery, final Pageable pageable) { return findTargetsBySpec( - RSQLUtility.parse(targetFilterQuery.getQuery(), TargetFields.class, virtualPropertyReplacer), - pageable); + RSQLUtility.parse(targetFilterQuery.getQuery(), TargetFields.class, virtualPropertyReplacer), pageable); } @Override @@ -188,25 +186,21 @@ public List findTargetsByControllerIDsWithTags(final List contro @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); - } + public Target updateTarget(final TargetUpdate u) { + final JpaTargetUpdate update = (JpaTargetUpdate) u; - @Override - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - public List updateTargets(final Collection targets) { + final JpaTarget target = Optional.ofNullable(targetRepository.findByControllerId(update.getControllerId())) + .orElseThrow(() -> new EntityNotFoundException( + "Target with ID " + update.getControllerId() + " not found.")); - @SuppressWarnings({ "unchecked", "rawtypes" }) - final Collection toUpdate = (Collection) targets; + target.setNew(false); - toUpdate.forEach(target -> target.setNew(false)); + update.getName().ifPresent(target::setName); + update.getDescription().ifPresent(target::setDescription); + update.getAddress().ifPresent(address -> ((JpaTargetInfo) target.getTargetInfo()).setAddress(address)); + update.getSecurityToken().ifPresent(target::setSecurityToken); - return Collections.unmodifiableList(targetRepository.save(toUpdate)); + return targetRepository.save(target); } @Override @@ -235,8 +229,7 @@ public Page findTargetByAssignedDistributionSet(final Long distributionS public Page findTargetByAssignedDistributionSet(final Long distributionSetID, final String rsqlParam, final Pageable pageReq) { - final Specification spec = RSQLUtility.parse(rsqlParam, TargetFields.class, - virtualPropertyReplacer); + final Specification spec = RSQLUtility.parse(rsqlParam, TargetFields.class, virtualPropertyReplacer); return convertPage( targetRepository @@ -264,8 +257,7 @@ public Page findTargetByInstalledDistributionSet(final Long distribution public Page findTargetByInstalledDistributionSet(final Long distributionSetId, final String rsqlParam, final Pageable pageable) { - final Specification spec = RSQLUtility.parse(rsqlParam, TargetFields.class, - virtualPropertyReplacer); + final Specification spec = RSQLUtility.parse(rsqlParam, TargetFields.class, virtualPropertyReplacer); return convertPage( targetRepository @@ -294,8 +286,8 @@ public Slice findTargetByFilters(final Pageable pageable, final Collecti @Override public Long countTargetByFilters(final Collection status, final Boolean overdueState, - final String searchText, final Long installedOrAssignedDistributionSetId, - final Boolean selectTargetWithNoTag, final String... tagNames) { + final String searchText, final Long installedOrAssignedDistributionSetId, + final Boolean selectTargetWithNoTag, final String... tagNames) { final List> specList = buildSpecificationList( new FilterParams(installedOrAssignedDistributionSetId, status, overdueState, searchText, selectTargetWithNoTag, tagNames), @@ -304,19 +296,17 @@ public Long countTargetByFilters(final Collection status, fi } private static List> buildSpecificationList(final FilterParams filterParams, - final boolean fetch) { + final boolean fetch) { final List> specList = new ArrayList<>(); if (filterParams.getFilterByStatus() != null && !filterParams.getFilterByStatus().isEmpty()) { specList.add(TargetSpecifications.hasTargetUpdateStatus(filterParams.getFilterByStatus(), fetch)); } if (filterParams.getOverdueState() != null) { - specList.add( - TargetSpecifications.isOverdue(TimestampCalculator.calculateOverdueTimestamp())); + specList.add(TargetSpecifications.isOverdue(TimestampCalculator.calculateOverdueTimestamp())); } if (filterParams.getFilterByDistributionId() != null) { - specList.add( - TargetSpecifications - .hasInstalledOrAssignedDistributionSet(filterParams.getFilterByDistributionId())); + specList.add(TargetSpecifications + .hasInstalledOrAssignedDistributionSet(filterParams.getFilterByDistributionId())); } if (StringUtils.isNotEmpty(filterParams.getFilterBySearchText())) { specList.add(TargetSpecifications.likeNameOrDescriptionOrIp(filterParams.getFilterBySearchText())); @@ -363,7 +353,8 @@ public TargetTagAssignmentResult toggleTagAssignment(final Collection ta @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 alreadyAssignedTargets = targetRepository.findByTagNameAndControllerIdIn(tagName, + targetIds); final List allTargets = targetRepository .findAll(TargetSpecifications.byControllerIdWithStatusAndTagsInJoin(targetIds)); @@ -371,7 +362,7 @@ public TargetTagAssignmentResult toggleTagAssignment(final Collection ta if (alreadyAssignedTargets.size() == allTargets.size()) { alreadyAssignedTargets.forEach(target -> target.removeTag(tag)); final TargetTagAssignmentResult result = new TargetTagAssignmentResult(0, 0, alreadyAssignedTargets.size(), - Collections.emptyList(), alreadyAssignedTargets, tag); + Collections.emptyList(), Collections.unmodifiableList(alreadyAssignedTargets), tag); return result; } @@ -380,7 +371,9 @@ public TargetTagAssignmentResult toggleTagAssignment(final Collection ta // some or none are assigned -> assign allTargets.forEach(target -> target.addTag(tag)); final TargetTagAssignmentResult result = new TargetTagAssignmentResult(alreadyAssignedTargets.size(), - allTargets.size(), 0, Collections.unmodifiableList(targetRepository.save(allTargets)), + allTargets.size(), 0, + Collections + .unmodifiableList(allTargets.stream().map(targetRepository::save).collect(Collectors.toList())), Collections.emptyList(), tag); // no reason to persist the tag @@ -396,7 +389,8 @@ public List assignTag(final Collection controllerIds, final Targ .findAll(TargetSpecifications.byControllerIdWithStatusAndTagsInJoin(controllerIds)); allTargets.forEach(target -> target.addTag(tag)); - return Collections.unmodifiableList(targetRepository.save(allTargets)); + return Collections + .unmodifiableList(allTargets.stream().map(targetRepository::save).collect(Collectors.toList())); } private List unAssignTag(final Collection targets, final TargetTag tag) { @@ -405,7 +399,8 @@ private List unAssignTag(final Collection targets, final TargetT toUnassign.forEach(target -> target.removeTag(tag)); - return Collections.unmodifiableList(targetRepository.save(toUnassign)); + return Collections + .unmodifiableList(toUnassign.stream().map(targetRepository::save).collect(Collectors.toList())); } @Override @@ -451,8 +446,7 @@ public Slice findTargetsAllOrderByLinkedDistributionSet(final Pageable p // build the specifications and then to predicates necessary by the // given filters final Predicate[] specificationsForMultiSelect = specificationsToPredicate( - buildSpecificationList(filterParams, true), - targetRoot, query, cb); + buildSpecificationList(filterParams, true), targetRoot, query, cb); // if we have some predicates then add it to the where clause of the // multiselect @@ -508,9 +502,8 @@ public List findAllTargetIds() { @Override public List findAllTargetIdsByFilters(final Pageable pageRequest, final Collection filterByStatus, final Boolean overdueState, - final String filterBySearchText, - final Long installedOrAssignedDistributionSetId, final Boolean selectTargetWithNoTag, - final String... filterByTagNames) { + 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); @@ -526,8 +519,7 @@ public List findAllTargetIdsByFilters(final Pageable pageRequest, final Predicate[] specificationsForMultiSelect = specificationsToPredicate( buildSpecificationList(new FilterParams(installedOrAssignedDistributionSetId, filterByStatus, - overdueState, filterBySearchText, - selectTargetWithNoTag, filterByTagNames), false), + overdueState, filterBySearchText, selectTargetWithNoTag, filterByTagNames), false), targetRoot, multiselect, cb); // if we have some predicates then add it to the where clause of the @@ -588,7 +580,7 @@ public Page findAllTargetsByTargetFilterQueryAndNonDS(@NotNull final Pag @Override public Page findAllTargetsByTargetFilterQueryAndNotInRolloutGroups(@NotNull final Pageable pageRequest, - final List groups, @NotNull final String targetFilterQuery) { + final List groups, @NotNull final String targetFilterQuery) { final Specification spec = RSQLUtility.parse(targetFilterQuery, TargetFields.class, virtualPropertyReplacer); @@ -608,7 +600,7 @@ public Page findAllTargetsInRolloutGroupWithoutAction(@NotNull final Pag @Override public Long countAllTargetsByTargetFilterQueryAndNotInRolloutGroups(final List groups, - @NotNull final String targetFilterQuery) { + @NotNull final String targetFilterQuery) { final Specification spec = RSQLUtility.parse(targetFilterQuery, TargetFields.class, virtualPropertyReplacer); final List> specList = new ArrayList<>(2); @@ -622,7 +614,7 @@ public Long countAllTargetsByTargetFilterQueryAndNotInRolloutGroups(final List spec = RSQLUtility.parse(targetFilterQuery.getQuery(), TargetFields.class, - virtualPropertyReplacer); + virtualPropertyReplacer); final List> specList = new ArrayList<>(2); specList.add(spec); specList.add(TargetSpecifications.hasNotDistributionSetInActions(distributionSetId)); @@ -633,52 +625,30 @@ public Long countTargetsByTargetFilterQueryAndNonDS(final Long distributionSetId @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; + public Target createTarget(final TargetCreate c) { + final JpaTargetCreate create = (JpaTargetCreate) c; + + final JpaTarget target = create.build(); if (targetRepository.findByControllerId(target.getControllerId()) != null) { - throw new EntityAlreadyExistsException(target.getControllerId()); + throw new EntityAlreadyExistsException(); } 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(); - } - - return targets.stream() - .map(t -> createTarget(t, TargetUpdateStatus.UNKNOWN, null, t.getTargetInfo().getAddress())) - .collect(Collectors.toList()); + public List createTargets(final Collection targets) { + return targets.stream().map(this::createTarget).collect(Collectors.toList()); } @Override diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutGroupRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutGroupRepository.java index ca9d4d6489..1aeb8343a0 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutGroupRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutGroupRepository.java @@ -53,28 +53,6 @@ public interface RolloutGroupRepository */ List findByRolloutAndStatus(final Rollout rollout, final RolloutGroupStatus status); - /** - * Counts all {@link RolloutGroup} referring a specific rollout. - * - * @param rollout - * the rollout the rolloutgroup belong to - * @return the count of the rollout groups for a specific rollout - */ - Long countByRollout(final JpaRollout rollout); - - /** - * Counts all {@link RolloutGroup} referring a specific rollout in a - * specific {@link RolloutGroupStatus}. - * - * @param rollout - * the rollout the rolloutgroup belong to - * @param rolloutGroupStatus - * the status of the rollout groups - * @return the count of rollout groups belonging to a rollout in a specific - * status - */ - Long countByRolloutAndStatus(JpaRollout rollout, RolloutGroupStatus rolloutGroupStatus); - /** * Counts all {@link RolloutGroup} referring a specific rollout in specific * {@link RolloutGroupStatus}s. An in-clause statement does not work with diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutHelper.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutHelper.java index f7720f86ae..155be4d9aa 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutHelper.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutHelper.java @@ -8,16 +8,19 @@ */ package org.eclipse.hawkbit.repository.jpa; +import java.util.List; +import java.util.stream.Collectors; + import org.apache.commons.lang3.StringUtils; +import org.eclipse.hawkbit.repository.builder.RolloutGroupCreate; +import org.eclipse.hawkbit.repository.exception.ConstraintViolationException; import org.eclipse.hawkbit.repository.exception.RolloutIllegalStateException; -import org.eclipse.hawkbit.repository.exception.RolloutVerificationException; +import org.eclipse.hawkbit.repository.jpa.builder.JpaRolloutGroupCreate; +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.RolloutGroupConditions; -import java.util.List; -import java.util.stream.Collectors; - /** * A collection of static helper methods for the {@link JpaRolloutManagement} */ @@ -33,26 +36,31 @@ private RolloutHelper() { */ static void verifyRolloutGroupConditions(final RolloutGroupConditions conditions) { if (conditions.getSuccessCondition() == null) { - throw new RolloutVerificationException("Rollout group is missing success condition"); + throw new ConstraintViolationException("Rollout group is missing success condition"); } if (conditions.getSuccessAction() == null) { - throw new RolloutVerificationException("Rollout group is missing success action"); + throw new ConstraintViolationException("Rollout group is missing success action"); } } /** - * Verifies that the group has the required success condition and action. + * Verifies that the group has the required success condition and action and + * a falid target percentage. * * @param group * the input group * @return the verified group */ static RolloutGroup verifyRolloutGroupHasConditions(final RolloutGroup group) { + if (group.getTargetPercentage() < 1F || group.getTargetPercentage() > 100F) { + throw new ConstraintViolationException("Target percentage has to be between 1 and 100"); + } + if (group.getSuccessCondition() == null) { - throw new RolloutVerificationException("Rollout group is missing success condition"); + throw new ConstraintViolationException("Rollout group is missing success condition"); } if (group.getSuccessAction() == null) { - throw new RolloutVerificationException("Rollout group is missing success action"); + throw new ConstraintViolationException("Rollout group is missing success action"); } return group; } @@ -65,10 +73,11 @@ static RolloutGroup verifyRolloutGroupHasConditions(final RolloutGroup group) { * group to check * @param conditions * default conditions and actions - * @return group with all conditions and actions */ - static RolloutGroup prepareRolloutGroupWithDefaultConditions(final RolloutGroup group, + static JpaRolloutGroup prepareRolloutGroupWithDefaultConditions(final RolloutGroupCreate create, final RolloutGroupConditions conditions) { + final JpaRolloutGroup group = ((JpaRolloutGroupCreate) create).build(); + if (group.getSuccessCondition() == null) { group.setSuccessCondition(conditions.getSuccessCondition()); } @@ -94,6 +103,7 @@ static RolloutGroup prepareRolloutGroupWithDefaultConditions(final RolloutGroup if (group.getErrorActionExp() == null) { group.setErrorActionExp(conditions.getErrorActionExp()); } + return group; } @@ -105,9 +115,9 @@ static RolloutGroup prepareRolloutGroupWithDefaultConditions(final RolloutGroup */ static void verifyRolloutGroupParameter(final int amountGroup) { if (amountGroup <= 0) { - throw new RolloutVerificationException("the amountGroup must be greater than zero"); + throw new ConstraintViolationException("the amountGroup must be greater than zero"); } else if (amountGroup > 500) { - throw new RolloutVerificationException("the amountGroup must not be greater than 500"); + throw new ConstraintViolationException("the amountGroup must not be greater than 500"); } } @@ -119,9 +129,9 @@ static void verifyRolloutGroupParameter(final int amountGroup) { */ static void verifyRolloutGroupTargetPercentage(final float percentage) { if (percentage <= 0) { - throw new RolloutVerificationException("the percentage must be greater than zero"); + throw new ConstraintViolationException("the percentage must be greater than zero"); } else if (percentage > 100) { - throw new RolloutVerificationException("the percentage must not be greater than 100"); + throw new ConstraintViolationException("the percentage must not be greater than 100"); } } @@ -193,11 +203,13 @@ static List getOrderedGroups(final Rollout rollout) { } /** - * Creates an RSQL expression that matches all targets in the provided groups. - * Links all target filter queries with OR. + * Creates an RSQL expression that matches all targets in the provided + * groups. Links all target filter queries with OR. * - * @param groups the rollout groups - * @return RSQL string without base filter of the Rollout. Can be an empty string. + * @param groups + * the rollout groups + * @return RSQL string without base filter of the Rollout. Can be an empty + * string. */ static String getAllGroupsTargetFilter(final List groups) { if (groups.stream().anyMatch(group -> StringUtils.isEmpty(group.getTargetFilterQuery()))) { @@ -207,12 +219,15 @@ static String getAllGroupsTargetFilter(final List groups) { } /** - * Creates an RSQL Filter that matches all targets that are in the provided group and - * in the provided groups. + * Creates an RSQL Filter that matches all targets that are in the provided + * group and in the provided groups. * - * @param groups the rollout groups - * @param group the group - * @return RSQL string without base filter of the Rollout. Can be an empty string. + * @param groups + * the rollout groups + * @param group + * the group + * @return RSQL string without base filter of the Rollout. Can be an empty + * string. */ static String getOverlappingWithGroupsTargetFilter(final List groups, final RolloutGroup group) { final String previousGroupFilters = getAllGroupsTargetFilter(groups); @@ -235,11 +250,11 @@ static String getOverlappingWithGroupsTargetFilter(final List grou */ static void verifyRemainingTargets(final long targetCount) { if (targetCount > 0) { - throw new RolloutVerificationException( + throw new ConstraintViolationException( "Rollout groups don't match all targets that are targeted by the rollout"); } if (targetCount != 0) { - throw new RolloutVerificationException("Rollout groups target count verification failed"); + throw new ConstraintViolationException("Rollout groups target count verification failed"); } } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutRepository.java index 3051796819..de7a628972 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutRepository.java @@ -13,8 +13,6 @@ 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; -import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; @@ -62,18 +60,6 @@ int updateLastCheck(@Param("lastCheck") final long lastCheck, @Param("delay") fi */ List findByLastCheckAndStatus(long lastCheck, RolloutStatus status); - /** - * Retrieves all {@link Rollout} for a specific {@code name}. - * - * @param pageable - * for paging information - * - * @param name - * the rollout name - * @return {@link Rollout} for specific name - */ - Page findByName(final Pageable pageable, String name); - /** * Retrieves all {@link Rollout} for a specific {@code name} * @@ -82,13 +68,4 @@ int updateLastCheck(@Param("lastCheck") final long lastCheck, @Param("delay") fi * @return {@link Rollout} for specific name */ JpaRollout findByName(String name); - - /** - * Retrieves all {@link Rollout} for a specific status. - * - * @param status - * the status of the rollouts to retrieve - * @return a list of {@link Rollout} having the given status - */ - List findByStatus(final RolloutStatus status); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleMetadataRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleMetadataRepository.java index c962b31ec7..7020935996 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleMetadataRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleMetadataRepository.java @@ -8,8 +8,6 @@ */ 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; @@ -29,17 +27,6 @@ public interface SoftwareModuleMetadataRepository extends PagingAndSortingRepository, JpaSpecificationExecutor { - /** - * Saves all given entities. - * - * @param entities - * @return the saved entities - * @throws IllegalArgumentException - * in case the given entity is (@literal null}. - */ - @Override - List save(Iterable entities); - /** * finds all software module meta data of the given software module id. * diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleRepository.java index 94d23f11e4..54f9877204 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleRepository.java @@ -18,8 +18,6 @@ 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.EntityGraph; -import org.springframework.data.jpa.repository.EntityGraph.EntityGraphType; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; @@ -86,17 +84,6 @@ void deleteSoftwareModule(@Param("lastModifiedAt") Long modifiedAt, @Param("last */ Page findByAssignedTo(Pageable pageable, JpaDistributionSet set); - /** - * - * - * @param setId - * to search for - * @return all {@link SoftwareModule}s that are assigned to given - * {@link DistributionSet} - */ - @EntityGraph(value = "SoftwareModule.artifacts", type = EntityGraphType.LOAD) - List findByAssignedToId(Long setId); - /** * @param pageable * the page request to page the result set @@ -109,23 +96,6 @@ void deleteSoftwareModule(@Param("lastModifiedAt") Long modifiedAt, @Param("last */ Page findByAssignedToAndType(Pageable pageable, JpaDistributionSet set, SoftwareModuleType type); - /** - * retrieves all software modules with a given {@link SoftwareModuleType} - * and {@link SoftwareModule#getId()}. - * - * @param ids - * to search for - * @param type - * to search for - * @return {@link List} of found {@link SoftwareModule}s - */ - // Workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=349477 - @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); - /** * retrieves all software modules with a given * {@link SoftwareModule#getId()}. diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleTypeRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleTypeRepository.java index c4ecfbd749..1019f2d8bb 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleTypeRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleTypeRepository.java @@ -8,11 +8,15 @@ */ package org.eclipse.hawkbit.repository.jpa; +import java.util.List; + import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType; +import org.eclipse.hawkbit.repository.model.SoftwareModule; 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; +import org.springframework.data.jpa.repository.Query; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; @@ -58,4 +62,16 @@ public interface SoftwareModuleTypeRepository * {@link SoftwareModuleType#getName()} */ JpaSoftwareModuleType findByName(String name); + + /** + * retrieves all software module types with a given + * {@link SoftwareModuleType#getId()}. + * + * @param ids + * to search for + * @return {@link List} of found {@link SoftwareModule}s + */ + // Workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=349477 + @Query("SELECT sm FROM JpaSoftwareModuleType sm WHERE sm.id IN ?1") + List findByIdIn(Iterable ids); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryRepository.java index 5ebee76199..7afa161563 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryRepository.java @@ -40,11 +40,6 @@ public interface TargetFilterQueryRepository @Override Page findAll(); - @Override - @Modifying - @Transactional - S save(S entity); - /** * Sets the auto assign distribution sets to null which match the ds ids. * diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetInfoRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetInfoRepository.java index 0f6f40768f..099343211d 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetInfoRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetInfoRepository.java @@ -52,5 +52,7 @@ public interface TargetInfoRepository { * * @return persisted or updated {@link Entity} */ + @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) S save(S entity); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetRepository.java index 4a0798485f..ca4942d572 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetRepository.java @@ -18,9 +18,8 @@ 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.TargetInfo; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; -import org.eclipse.hawkbit.repository.model.TargetWithActionStatus; -import org.springframework.cache.annotation.CacheEvict; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.EntityGraph; @@ -49,15 +48,6 @@ public interface TargetRepository extends BaseEntityRepository, @EntityGraph(value = "Target.detail", type = EntityGraphType.LOAD) JpaTarget findByControllerId(String controllerID); - /** - * Finds targets by given list of {@link Target#getControllerId()}s. - * - * @param controllerIDs - * to serach for - * @return list of found {@link Target}s - */ - List findByControllerIdIn(String... controllerIDs); - /** * Deletes the {@link Target}s with the given target IDs. * @@ -68,7 +58,6 @@ public interface TargetRepository extends BaseEntityRepository, @Transactional(isolation = Isolation.READ_UNCOMMITTED) // Workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=349477 @Query("DELETE FROM JpaTarget t WHERE t.id IN ?1") - @CacheEvict(value = { "targetStatus", "distributionUsageInstalled", "targetsLastPoll" }, allEntries = true) void deleteByIdIn(final Collection targetIDs); /** @@ -92,7 +81,7 @@ public interface TargetRepository extends BaseEntityRepository, * @return {@link List} of found {@link Target}s. */ @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, + List findByTagNameAndControllerIdIn(@Param("tagname") final String tag, @Param("targets") final Collection controllerIds); /** @@ -107,18 +96,6 @@ List findByTagNameAndControllerIdIn(@Param("tagname") final String tag, */ Page findByTargetInfoUpdateStatus(final Pageable pageable, final TargetUpdateStatus status); - /** - * Finds all targets that have defined {@link DistributionSet} installed. - * - * @param pageable - * for page configuration - * @param set - * is the {@link DistributionSet} to filter for. - * - * @return found targets - */ - Page findByTargetInfoInstalledDistributionSet(final Pageable pageable, final JpaDistributionSet set); - /** * retrieves the {@link Target}s which has the {@link DistributionSet} * installed with the given ID. @@ -131,48 +108,6 @@ List findByTagNameAndControllerIdIn(@Param("tagname") final String tag, */ Page findByTargetInfoInstalledDistributionSetId(final Pageable pageable, final Long setID); - /** - * Finds all targets that have defined {@link DistributionSet} assigned. - * - * @param pageable - * for page configuration - * @param set - * is the {@link DistributionSet} to filter for. - * - * @return found targets - */ - Page findByAssignedDistributionSet(final Pageable pageable, final JpaDistributionSet set); - - /** - * Saves all given {@link Target}s. - * - * @param entities - * @return the saved entities - * @throws IllegalArgumentException - * in case the given entity is (@literal null}. - * - * @see org.springframework.data.repository.CrudRepository#save(java.lang.Iterable) - */ - @Override - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @CacheEvict(value = { "targetStatus", "distributionUsageInstalled", "targetsLastPoll" }, allEntries = true) - List save(Iterable entities); - - /** - * Saves a given entity. Use the returned instance for further operations as - * the save operation might have changed the entity instance completely. - * - * @param entity - * the target to save - * @return the saved entity - */ - @Override - @Modifying - @Transactional(isolation = Isolation.READ_UNCOMMITTED) - @CacheEvict(value = { "targetStatus", "distributionUsageInstalled", "targetsLastPoll" }, allEntries = true) - S save(S entity); - /** * Finds all targets that have defined {@link DistributionSet} assigned. * @@ -196,18 +131,9 @@ List findByTagNameAndControllerIdIn(@Param("tagname") final String tag, */ Long countByAssignedDistributionSetId(final Long distId); - /** - * @param ids - * of count in DB - * @return number of found {@link Target}s with given - * {@link Target#getControllerId()}s - */ - @Query("SELECT COUNT(t) FROM JpaTarget t WHERE t.controllerId IN ?1") - Long countByControllerIdIn(final Collection ids); - /** * Counts number of targets with given - * {@link TargetStatus#getInstalledDistributionSet()}. + * {@link TargetInfo#getInstalledDistributionSet()}. * * @param distId * to search for @@ -215,41 +141,6 @@ List findByTagNameAndControllerIdIn(@Param("tagname") final String tag, */ Long countByTargetInfoInstalledDistributionSetId(final Long distId); - /** - * Finds all targets that have defined {@link DistributionSet} assigned or - * installed. - * - * @param pageable - * for page configuration - * @param assigned - * {@link DistributionSet} filter for; please note: must not be - * null - * @param installed - * {@link DistributionSet} filter for; please note: must not be - * null - * - * @return found targets - */ - Page findByAssignedDistributionSetOrTargetInfoInstalledDistributionSet(final Pageable pageable, - final JpaDistributionSet assigned, final JpaDistributionSet installed); - - /** - * Finds all targets that have defined {@link DistributionSet} assigned or - * installed. - * - * @param pageable - * for page configuration - * @param assigned - * {@link DistributionSet} filter for; please note: must not be - * null - * @param installed - * {@link DistributionSet} filter for; please note: must not be - * null - * @return found targets - */ - Page findByAssignedDistributionSetIdOrTargetInfoInstalledDistributionSetId(final Pageable pageable, - final Long assigned, final Long installed); - /** * Finds all {@link Target}s in the repository. * @@ -283,8 +174,6 @@ Page findByAssignedDistributionSetIdOrTargetInfoInstalledDistributionSet void setAssignedDistributionSet(@Param("set") JpaDistributionSet set, @Param("lastModifiedAt") Long modifiedAt, @Param("lastModifiedBy") String modifiedBy, @Param("targets") Collection targets); - List findByRolloutTargetGroupRolloutGroup(final JpaRolloutGroup rolloutGroup); - /** * * Finds all targets of a rollout group. @@ -308,17 +197,4 @@ void setAssignedDistributionSet(@Param("set") JpaDistributionSet set, @Param("la * @return a page of all targets related to a rollout group */ Page findByActionsRolloutGroup(JpaRolloutGroup rolloutGroup, Pageable page); - - /** - * Find all targets with action status for a specific group. - * - * @param pageable - * the page request parameter - * @param rolloutGroupId - * 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 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/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetTagRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetTagRepository.java index 6b9e021b1c..8000cd8c90 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetTagRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetTagRepository.java @@ -28,7 +28,7 @@ public interface TargetTagRepository /** * deletes the {@link TargetTag}s with the given tag names. * - * @param tagNames + * @param tagName * to be deleted * @return 1 if tag was deleted */ @@ -52,7 +52,4 @@ public interface TargetTagRepository */ @Override List findAll(); - - @Override - List save(Iterable entities); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TenantConfigurationRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TenantConfigurationRepository.java index bd99cb918b..4649d00fe2 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TenantConfigurationRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TenantConfigurationRepository.java @@ -8,8 +8,6 @@ */ 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; @@ -31,9 +29,6 @@ public interface TenantConfigurationRepository extends BaseEntityRepository findAll(); - /** * Deletes a tenant configuration by tenant and key. * diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TenantMetaDataRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TenantMetaDataRepository.java index 353f6500b9..b5de8f112e 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TenantMetaDataRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TenantMetaDataRepository.java @@ -32,16 +32,6 @@ public interface TenantMetaDataRepository extends PagingAndSortingRepository findAll(); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaActionStatusBuilder.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaActionStatusBuilder.java new file mode 100644 index 0000000000..acb12c15cf --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaActionStatusBuilder.java @@ -0,0 +1,26 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.builder.ActionStatusBuilder; +import org.eclipse.hawkbit.repository.builder.ActionStatusCreate; +import org.eclipse.hawkbit.repository.model.ActionStatus; + +/** + * Builder implementation for {@link ActionStatus}. + * + */ +public class JpaActionStatusBuilder implements ActionStatusBuilder { + + @Override + public ActionStatusCreate create(final long actionId) { + return new JpaActionStatusCreate(actionId); + } + +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaActionStatusCreate.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaActionStatusCreate.java new file mode 100644 index 0000000000..6132988b26 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaActionStatusCreate.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.jpa.builder; + +import org.eclipse.hawkbit.repository.builder.AbstractActionStatusCreate; +import org.eclipse.hawkbit.repository.builder.ActionStatusCreate; +import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus; + +/** + * Create/build implementation. + * + */ +public class JpaActionStatusCreate extends AbstractActionStatusCreate + implements ActionStatusCreate { + + JpaActionStatusCreate(final Long actionId) { + super.actionId = actionId; + } + + @Override + public JpaActionStatus build() { + final JpaActionStatus result = new JpaActionStatus(status, getOccurredAt().orElse(System.currentTimeMillis())); + if (messages != null) { + messages.forEach(result::addMessage); + } + return result; + } +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaDistributionSetBuilder.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaDistributionSetBuilder.java new file mode 100644 index 0000000000..f63c18378f --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaDistributionSetBuilder.java @@ -0,0 +1,44 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.DistributionSetManagement; +import org.eclipse.hawkbit.repository.SoftwareManagement; +import org.eclipse.hawkbit.repository.builder.DistributionSetBuilder; +import org.eclipse.hawkbit.repository.builder.DistributionSetCreate; +import org.eclipse.hawkbit.repository.builder.DistributionSetUpdate; +import org.eclipse.hawkbit.repository.builder.GenericDistributionSetUpdate; +import org.eclipse.hawkbit.repository.model.DistributionSet; + +/** + * Builder implementation for {@link DistributionSet}. + * + */ +public class JpaDistributionSetBuilder implements DistributionSetBuilder { + + private final DistributionSetManagement distributionSetManagement; + private final SoftwareManagement softwareManagement; + + public JpaDistributionSetBuilder(final DistributionSetManagement distributionSetManagement, + final SoftwareManagement softwareManagement) { + this.distributionSetManagement = distributionSetManagement; + this.softwareManagement = softwareManagement; + } + + @Override + public DistributionSetUpdate update(final long id) { + return new GenericDistributionSetUpdate(id); + } + + @Override + public DistributionSetCreate create() { + return new JpaDistributionSetCreate(distributionSetManagement, softwareManagement); + } + +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaDistributionSetCreate.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaDistributionSetCreate.java new file mode 100644 index 0000000000..6865f82cad --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaDistributionSetCreate.java @@ -0,0 +1,75 @@ +/** + * 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.builder; + +import java.util.Collection; +import java.util.Collections; +import java.util.Optional; + +import org.apache.commons.collections4.CollectionUtils; +import org.eclipse.hawkbit.repository.DistributionSetManagement; +import org.eclipse.hawkbit.repository.SoftwareManagement; +import org.eclipse.hawkbit.repository.builder.AbstractDistributionSetUpdateCreate; +import org.eclipse.hawkbit.repository.builder.DistributionSetCreate; +import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; +import org.eclipse.hawkbit.repository.model.DistributionSetType; +import org.eclipse.hawkbit.repository.model.SoftwareModule; + +/** + * Create/build implementation. + * + */ +public class JpaDistributionSetCreate extends AbstractDistributionSetUpdateCreate + implements DistributionSetCreate { + + private final DistributionSetManagement distributionSetManagement; + private final SoftwareManagement softwareManagement; + + JpaDistributionSetCreate(final DistributionSetManagement distributionSetManagement, + final SoftwareManagement softwareManagement) { + this.distributionSetManagement = distributionSetManagement; + this.softwareManagement = softwareManagement; + } + + @Override + public JpaDistributionSet build() { + return new JpaDistributionSet(name, version, description, + Optional.ofNullable(type).map(this::findDistributionSetTypeWithExceptionIfNotFound).orElse(null), + findSoftwareModuleWithExceptionIfNotFound(modules), + Optional.ofNullable(requiredMigrationStep).orElse(Boolean.FALSE)); + } + + private DistributionSetType findDistributionSetTypeWithExceptionIfNotFound(final String distributionSetTypekey) { + + final DistributionSetType module = distributionSetManagement + .findDistributionSetTypeByKey(distributionSetTypekey); + if (module == null) { + throw new EntityNotFoundException( + "DistributionSetType with key {" + distributionSetTypekey + "} does not exist"); + } + return module; + } + + private Collection findSoftwareModuleWithExceptionIfNotFound( + final Collection softwareModuleId) { + if (CollectionUtils.isEmpty(softwareModuleId)) { + return Collections.emptyList(); + } + + final Collection module = softwareManagement.findSoftwareModulesById(softwareModuleId); + if (module.size() < softwareModuleId.size()) { + throw new EntityNotFoundException( + "Some SoftwareModules out of the range {" + softwareModuleId + "} due not exist"); + } + + return module; + } + +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaDistributionSetTypeBuilder.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaDistributionSetTypeBuilder.java new file mode 100644 index 0000000000..5218b76a6d --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaDistributionSetTypeBuilder.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.builder; + +import org.eclipse.hawkbit.repository.SoftwareManagement; +import org.eclipse.hawkbit.repository.builder.DistributionSetTypeBuilder; +import org.eclipse.hawkbit.repository.builder.DistributionSetTypeCreate; +import org.eclipse.hawkbit.repository.builder.DistributionSetTypeUpdate; +import org.eclipse.hawkbit.repository.builder.GenericDistributionSetTypeUpdate; +import org.eclipse.hawkbit.repository.model.DistributionSetType; + +/** + * Builder implementation for {@link DistributionSetType}. + * + */ +public class JpaDistributionSetTypeBuilder implements DistributionSetTypeBuilder { + + private final SoftwareManagement softwareManagement; + + public JpaDistributionSetTypeBuilder(final SoftwareManagement softwareManagement) { + this.softwareManagement = softwareManagement; + } + + @Override + public DistributionSetTypeUpdate update(final long id) { + return new GenericDistributionSetTypeUpdate(id); + } + + @Override + public DistributionSetTypeCreate create() { + return new JpaDistributionSetTypeCreate(softwareManagement); + } + +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaDistributionSetTypeCreate.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaDistributionSetTypeCreate.java new file mode 100644 index 0000000000..a717326466 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaDistributionSetTypeCreate.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.jpa.builder; + +import java.util.Collection; +import java.util.Collections; + +import org.apache.commons.collections4.CollectionUtils; +import org.eclipse.hawkbit.repository.SoftwareManagement; +import org.eclipse.hawkbit.repository.builder.AbstractDistributionSetTypeUpdateCreate; +import org.eclipse.hawkbit.repository.builder.DistributionSetTypeCreate; +import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType; +import org.eclipse.hawkbit.repository.model.SoftwareModuleType; + +/** + * Create/build implementation. + * + */ +public class JpaDistributionSetTypeCreate extends AbstractDistributionSetTypeUpdateCreate + implements DistributionSetTypeCreate { + + private final SoftwareManagement softwareManagement; + + JpaDistributionSetTypeCreate(final SoftwareManagement softwareManagement) { + this.softwareManagement = softwareManagement; + } + + @Override + public JpaDistributionSetType build() { + final JpaDistributionSetType result = new JpaDistributionSetType(key, name, description, colour); + + findSoftwareModuleTypeWithExceptionIfNotFound(mandatory).forEach(result::addMandatoryModuleType); + findSoftwareModuleTypeWithExceptionIfNotFound(optional).forEach(result::addOptionalModuleType); + + return result; + } + + private Collection findSoftwareModuleTypeWithExceptionIfNotFound( + final Collection softwareModuleTypeId) { + if (CollectionUtils.isEmpty(softwareModuleTypeId)) { + return Collections.emptyList(); + } + + final Collection module = softwareManagement + .findSoftwareModuleTypesById(softwareModuleTypeId); + if (module.size() < softwareModuleTypeId.size()) { + throw new EntityNotFoundException( + "SoftwareModules types out of the range {" + softwareModuleTypeId + "} due not exist"); + } + + return module; + } + +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaRolloutBuilder.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaRolloutBuilder.java new file mode 100644 index 0000000000..dbf908e4e0 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaRolloutBuilder.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.jpa.builder; + +import org.eclipse.hawkbit.repository.DistributionSetManagement; +import org.eclipse.hawkbit.repository.builder.GenericRolloutUpdate; +import org.eclipse.hawkbit.repository.builder.RolloutBuilder; +import org.eclipse.hawkbit.repository.builder.RolloutCreate; +import org.eclipse.hawkbit.repository.builder.RolloutUpdate; +import org.eclipse.hawkbit.repository.model.Rollout; + +/** + * Builder implementation for {@link Rollout}. + * + */ +public class JpaRolloutBuilder implements RolloutBuilder { + private final DistributionSetManagement distributionSetManagement; + + public JpaRolloutBuilder(final DistributionSetManagement distributionSetManagement) { + this.distributionSetManagement = distributionSetManagement; + } + + @Override + public RolloutUpdate update(final long id) { + return new GenericRolloutUpdate(id); + } + + @Override + public RolloutCreate create() { + return new JpaRolloutCreate(distributionSetManagement); + } + +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaRolloutCreate.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaRolloutCreate.java new file mode 100644 index 0000000000..20fa4f6bdf --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaRolloutCreate.java @@ -0,0 +1,53 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.DistributionSetManagement; +import org.eclipse.hawkbit.repository.builder.AbstractRolloutUpdateCreate; +import org.eclipse.hawkbit.repository.builder.RolloutCreate; +import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; +import org.eclipse.hawkbit.repository.jpa.model.JpaRollout; +import org.eclipse.hawkbit.repository.model.DistributionSet; + +public class JpaRolloutCreate extends AbstractRolloutUpdateCreate implements RolloutCreate { + private final DistributionSetManagement distributionSetManagement; + + JpaRolloutCreate(final DistributionSetManagement distributionSetManagement) { + this.distributionSetManagement = distributionSetManagement; + } + + @Override + public JpaRollout build() { + final JpaRollout rollout = new JpaRollout(); + + rollout.setName(name); + rollout.setDescription(description); + rollout.setDistributionSet(findDistributionSetAndThrowExceptionIfNotFound(set)); + rollout.setTargetFilterQuery(targetFilterQuery); + + if (actionType != null) { + rollout.setActionType(actionType); + } + + if (forcedTime != null) { + rollout.setForcedTime(forcedTime); + } + + return rollout; + } + + private DistributionSet findDistributionSetAndThrowExceptionIfNotFound(final Long setId) { + final DistributionSet set = distributionSetManagement.findDistributionSetById(setId); + + if (set == null) { + throw new EntityNotFoundException("Distribution set cannot be set as it does not exixt" + setId); + } + return set; + } +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaRolloutGroupBuilder.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaRolloutGroupBuilder.java new file mode 100644 index 0000000000..96671113da --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaRolloutGroupBuilder.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.jpa.builder; + +import org.eclipse.hawkbit.repository.builder.RolloutGroupBuilder; +import org.eclipse.hawkbit.repository.builder.RolloutGroupCreate; +import org.eclipse.hawkbit.repository.model.RolloutGroup; + +/** + * Builder implementation for {@link RolloutGroup}. + * + */ +public class JpaRolloutGroupBuilder implements RolloutGroupBuilder { + @Override + public RolloutGroupCreate create() { + return new JpaRolloutGroupCreate(); + } + +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaRolloutGroupCreate.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaRolloutGroupCreate.java new file mode 100644 index 0000000000..66e7f1610e --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaRolloutGroupCreate.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.jpa.builder; + +import org.eclipse.hawkbit.repository.builder.AbstractRolloutGroupCreate; +import org.eclipse.hawkbit.repository.builder.RolloutGroupCreate; +import org.eclipse.hawkbit.repository.jpa.model.JpaRolloutGroup; + +public class JpaRolloutGroupCreate extends AbstractRolloutGroupCreate + implements RolloutGroupCreate { + + @Override + public JpaRolloutGroup build() { + final JpaRolloutGroup group = new JpaRolloutGroup(); + + group.setName(name); + group.setDescription(description); + group.setTargetFilterQuery(targetFilterQuery); + + if (targetPercentage == null) { + targetPercentage = 100F; + } + + group.setTargetPercentage(targetPercentage); + + if (conditions != null) { + group.setSuccessCondition(conditions.getSuccessCondition()); + group.setSuccessConditionExp(conditions.getSuccessConditionExp()); + + group.setSuccessAction(conditions.getSuccessAction()); + group.setSuccessActionExp(conditions.getSuccessActionExp()); + + group.setErrorCondition(conditions.getErrorCondition()); + group.setErrorConditionExp(conditions.getErrorConditionExp()); + + group.setErrorAction(conditions.getErrorAction()); + group.setErrorActionExp(conditions.getErrorActionExp()); + } + + return group; + } + +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaSoftwareModuleBuilder.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaSoftwareModuleBuilder.java new file mode 100644 index 0000000000..853a5971c8 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaSoftwareModuleBuilder.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.builder; + +import org.eclipse.hawkbit.repository.SoftwareManagement; +import org.eclipse.hawkbit.repository.builder.GenericSoftwareModuleUpdate; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleBuilder; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleCreate; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleUpdate; +import org.eclipse.hawkbit.repository.model.SoftwareModule; + +/** + * Builder implementation for {@link SoftwareModule}. + * + */ +public class JpaSoftwareModuleBuilder implements SoftwareModuleBuilder { + + private final SoftwareManagement softwareManagement; + + public JpaSoftwareModuleBuilder(final SoftwareManagement softwareManagement) { + this.softwareManagement = softwareManagement; + } + + @Override + public SoftwareModuleUpdate update(final long id) { + return new GenericSoftwareModuleUpdate(id); + } + + @Override + public SoftwareModuleCreate create() { + return new JpaSoftwareModuleCreate(softwareManagement); + } + +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaSoftwareModuleCreate.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaSoftwareModuleCreate.java new file mode 100644 index 0000000000..eb03cf9fac --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaSoftwareModuleCreate.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.jpa.builder; + +import org.eclipse.hawkbit.repository.SoftwareManagement; +import org.eclipse.hawkbit.repository.builder.AbstractSoftwareModuleUpdateCreate; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleCreate; +import org.eclipse.hawkbit.repository.exception.ConstraintViolationException; +import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; +import org.eclipse.hawkbit.repository.model.SoftwareModuleType; + +/** + * Create/build implementation. + * + */ +public class JpaSoftwareModuleCreate extends AbstractSoftwareModuleUpdateCreate + implements SoftwareModuleCreate { + + private final SoftwareManagement softwareManagement; + + JpaSoftwareModuleCreate(final SoftwareManagement softwareManagement) { + this.softwareManagement = softwareManagement; + } + + @Override + public JpaSoftwareModule build() { + return new JpaSoftwareModule(getSoftwareModuleTypeFromKeyString(type), name, version, description, vendor); + } + + private SoftwareModuleType getSoftwareModuleTypeFromKeyString(final String type) { + if (type == null) { + throw new ConstraintViolationException("type cannot be null"); + } + + final SoftwareModuleType smType = softwareManagement.findSoftwareModuleTypeByKey(type.trim()); + + if (smType == null) { + throw new EntityNotFoundException(type.trim()); + } + + return smType; + } +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaSoftwareModuleTypeBuilder.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaSoftwareModuleTypeBuilder.java new file mode 100644 index 0000000000..afd7eec1b3 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaSoftwareModuleTypeBuilder.java @@ -0,0 +1,33 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.builder.GenericSoftwareModuleTypeUpdate; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeBuilder; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeCreate; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeUpdate; +import org.eclipse.hawkbit.repository.model.SoftwareModuleType; + +/** + * Builder implementation for {@link SoftwareModuleType}. + * + */ +public class JpaSoftwareModuleTypeBuilder implements SoftwareModuleTypeBuilder { + + @Override + public SoftwareModuleTypeUpdate update(final long id) { + return new GenericSoftwareModuleTypeUpdate(id); + } + + @Override + public SoftwareModuleTypeCreate create() { + return new JpaSoftwareModuleTypeCreate(); + } + +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaSoftwareModuleTypeCreate.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaSoftwareModuleTypeCreate.java new file mode 100644 index 0000000000..54fcd3ab56 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaSoftwareModuleTypeCreate.java @@ -0,0 +1,30 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.builder.AbstractSoftwareModuleTypeUpdateCreate; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeCreate; +import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType; + +/** + * Create/build implementation. + * + */ +public class JpaSoftwareModuleTypeCreate extends AbstractSoftwareModuleTypeUpdateCreate + implements SoftwareModuleTypeCreate { + + JpaSoftwareModuleTypeCreate() { + + } + + @Override + public JpaSoftwareModuleType build() { + return new JpaSoftwareModuleType(key, name, description, maxAssignments, colour); + } +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTagBuilder.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTagBuilder.java new file mode 100644 index 0000000000..6291f8717c --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTagBuilder.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.repository.jpa.builder; + +import org.eclipse.hawkbit.repository.builder.GenericTagUpdate; +import org.eclipse.hawkbit.repository.builder.TagBuilder; +import org.eclipse.hawkbit.repository.builder.TagCreate; +import org.eclipse.hawkbit.repository.builder.TagUpdate; + +/** + * Builder implementation for {@link Tag}. + * + */ +public class JpaTagBuilder implements TagBuilder { + + @Override + public TagUpdate update(final long id) { + return new GenericTagUpdate(id); + } + + @Override + public TagCreate create() { + return new JpaTagCreate(); + } + +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTagCreate.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTagCreate.java new file mode 100644 index 0000000000..69759a61e4 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTagCreate.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.jpa.builder; + +import org.eclipse.hawkbit.repository.builder.AbstractTagUpdateCreate; +import org.eclipse.hawkbit.repository.builder.TagCreate; +import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag; +import org.eclipse.hawkbit.repository.jpa.model.JpaTag; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag; +import org.eclipse.hawkbit.repository.model.Tag; + +/** + * Create/build implementation. + * + */ +public class JpaTagCreate extends AbstractTagUpdateCreate implements TagCreate { + JpaTagCreate() { + + } + + public JpaDistributionSetTag buildDistributionSetTag() { + return new JpaDistributionSetTag(name, description, colour); + } + + public JpaTargetTag buildTargetTag() { + return new JpaTargetTag(name, description, colour); + } + + @Override + public Tag build() { + return new JpaTag(name, description, colour); + } +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTargetBuilder.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTargetBuilder.java new file mode 100644 index 0000000000..b9c07b7db5 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTargetBuilder.java @@ -0,0 +1,31 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.builder.TargetBuilder; +import org.eclipse.hawkbit.repository.builder.TargetCreate; +import org.eclipse.hawkbit.repository.builder.TargetUpdate; + +/** + * Builder implementation for {@link Target}. + * + */ +public class JpaTargetBuilder implements TargetBuilder { + + @Override + public TargetUpdate update(final String controllerId) { + return new JpaTargetUpdate(controllerId); + } + + @Override + public TargetCreate create() { + return new JpaTargetCreate(); + } + +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTargetCreate.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTargetCreate.java new file mode 100644 index 0000000000..75d21a1822 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTargetCreate.java @@ -0,0 +1,52 @@ +/** + * 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.builder; + +import org.apache.commons.lang3.StringUtils; +import org.eclipse.hawkbit.repository.builder.AbstractTargetUpdateCreate; +import org.eclipse.hawkbit.repository.builder.TargetCreate; +import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetInfo; +import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; + +/** + * Create/build implementation. + * + */ +public class JpaTargetCreate extends AbstractTargetUpdateCreate implements TargetCreate { + + JpaTargetCreate() { + super(null); + } + + @Override + public JpaTarget build() { + JpaTarget target; + + if (StringUtils.isEmpty(securityToken)) { + target = new JpaTarget(controllerId); + } else { + target = new JpaTarget(controllerId, securityToken); + } + + if (!StringUtils.isEmpty(name)) { + target.setName(name); + } + + target.setDescription(description); + final JpaTargetInfo targetInfo = (JpaTargetInfo) target.getTargetInfo(); + + targetInfo.setAddress(address); + targetInfo.setUpdateStatus(getStatus().orElse(TargetUpdateStatus.UNKNOWN)); + getLastTargetQuery().ifPresent(targetInfo::setLastTargetQuery); + + return target; + } + +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTargetFilterQueryBuilder.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTargetFilterQueryBuilder.java new file mode 100644 index 0000000000..b6a91c8cc2 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTargetFilterQueryBuilder.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.jpa.builder; + +import org.eclipse.hawkbit.repository.DistributionSetManagement; +import org.eclipse.hawkbit.repository.builder.GenericTargetFilterQueryUpdate; +import org.eclipse.hawkbit.repository.builder.TargetFilterQueryBuilder; +import org.eclipse.hawkbit.repository.builder.TargetFilterQueryCreate; +import org.eclipse.hawkbit.repository.builder.TargetFilterQueryUpdate; +import org.eclipse.hawkbit.repository.model.TargetFilterQuery; + +/** + * Builder implementation for {@link TargetFilterQuery}. + * + */ +public class JpaTargetFilterQueryBuilder implements TargetFilterQueryBuilder { + private final DistributionSetManagement distributionSetManagement; + + public JpaTargetFilterQueryBuilder(final DistributionSetManagement distributionSetManagement) { + this.distributionSetManagement = distributionSetManagement; + } + + @Override + public TargetFilterQueryUpdate update(final long id) { + return new GenericTargetFilterQueryUpdate(id); + } + + @Override + public TargetFilterQueryCreate create() { + return new JpaTargetFilterQueryCreate(distributionSetManagement); + } + +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTargetFilterQueryCreate.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTargetFilterQueryCreate.java new file mode 100644 index 0000000000..21d57a70d4 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTargetFilterQueryCreate.java @@ -0,0 +1,47 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.DistributionSetManagement; +import org.eclipse.hawkbit.repository.builder.AbstractTargetFilterQueryUpdateCreate; +import org.eclipse.hawkbit.repository.builder.TargetFilterQueryCreate; +import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; +import org.eclipse.hawkbit.repository.jpa.model.JpaTargetFilterQuery; +import org.eclipse.hawkbit.repository.model.DistributionSet; + +/** + * Create/build implementation. + * + */ +public class JpaTargetFilterQueryCreate extends AbstractTargetFilterQueryUpdateCreate + implements TargetFilterQueryCreate { + + private final DistributionSetManagement distributionSetManagement; + + JpaTargetFilterQueryCreate(final DistributionSetManagement distributionSetManagement) { + this.distributionSetManagement = distributionSetManagement; + } + + @Override + public JpaTargetFilterQuery build() { + + return new JpaTargetFilterQuery(name, query, + getSet().map(this::findDistributionSetAndThrowExceptionIfNotFound).orElse(null)); + } + + private DistributionSet findDistributionSetAndThrowExceptionIfNotFound(final Long setId) { + final DistributionSet set = distributionSetManagement.findDistributionSetById(setId); + + if (set == null) { + throw new EntityNotFoundException("Distribution set cannot be set as it does not exixt" + setId); + } + return set; + } + +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTargetUpdate.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTargetUpdate.java new file mode 100644 index 0000000000..5a6a665a36 --- /dev/null +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTargetUpdate.java @@ -0,0 +1,20 @@ +/** + * 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.builder; + +import org.eclipse.hawkbit.repository.builder.AbstractTargetUpdateCreate; +import org.eclipse.hawkbit.repository.builder.TargetUpdate; + +public class JpaTargetUpdate extends AbstractTargetUpdateCreate implements TargetUpdate { + + JpaTargetUpdate(final String controllerId) { + super(controllerId); + } + +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaBaseEntity.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaBaseEntity.java index 319f9123af..63a7a1bba7 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaBaseEntity.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaBaseEntity.java @@ -120,7 +120,7 @@ public Long getId() { @Override public String toString() { - return "BaseEntity [id=" + id + "]"; + return this.getClass().getSimpleName() + " [id=" + id + "]"; } public void setId(final Long id) { @@ -172,10 +172,7 @@ public boolean equals(final Object obj) { } else if (!id.equals(other.id)) { return false; } - if (optLockRevision != other.optLockRevision) { - return false; - } - return true; + return optLockRevision == other.optLockRevision; } } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedEntity.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedEntity.java index 634d4490fb..449db965ae 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedEntity.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedEntity.java @@ -10,11 +10,11 @@ import javax.persistence.Column; import javax.persistence.MappedSuperclass; -import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.eclipse.hawkbit.repository.model.NamedEntity; import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity; +import org.hibernate.validator.constraints.NotEmpty; /** * {@link TenantAwareBaseEntity} extension for all entities that are named in @@ -29,7 +29,7 @@ public abstract class AbstractJpaNamedEntity extends AbstractJpaTenantAwareBaseE @Column(name = "name", nullable = false, length = 64) @Size(max = 64) - @NotNull + @NotEmpty private String name; @Column(name = "description", nullable = true, length = 512) @@ -66,12 +66,10 @@ 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/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedVersionedEntity.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedVersionedEntity.java index 9e45f3a762..f7690ade8f 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedVersionedEntity.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaNamedVersionedEntity.java @@ -10,11 +10,11 @@ import javax.persistence.Column; import javax.persistence.MappedSuperclass; -import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.eclipse.hawkbit.repository.model.NamedEntity; import org.eclipse.hawkbit.repository.model.NamedVersionedEntity; +import org.hibernate.validator.constraints.NotEmpty; /** * Extension for {@link NamedEntity} that are versioned. @@ -29,7 +29,7 @@ public abstract class AbstractJpaNamedVersionedEntity extends AbstractJpaNamedEn @Column(name = "version", nullable = false, length = 64) @Size(max = 64) - @NotNull + @NotEmpty private String version; /** @@ -55,7 +55,6 @@ public String getVersion() { return version; } - @Override public void setVersion(final String version) { this.version = version; } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/DistributionSetTypeElement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/DistributionSetTypeElement.java index 26a6030787..ca70d00258 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/DistributionSetTypeElement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/DistributionSetTypeElement.java @@ -75,6 +75,11 @@ public DistributionSetTypeElement(final JpaDistributionSetType dsType, final Jpa this.mandatory = mandatory; } + public DistributionSetTypeElement setMandatory(final boolean mandatory) { + this.mandatory = mandatory; + return this; + } + public boolean isMandatory() { return mandatory; } @@ -95,4 +100,35 @@ public DistributionSetTypeElementCompositeKey getKey() { public String toString() { return "DistributionSetTypeElement [mandatory=" + mandatory + ", dsType=" + dsType + ", smType=" + smType + "]"; } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((key == null) ? 0 : key.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final DistributionSetTypeElement other = (DistributionSetTypeElement) obj; + if (key == null) { + if (other.key != null) { + return false; + } + } else if (!key.equals(other.key)) { + return false; + } + return true; + } + } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/DistributionSetTypeElementCompositeKey.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/DistributionSetTypeElementCompositeKey.java index f94a3784aa..3915fc609a 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/DistributionSetTypeElementCompositeKey.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/DistributionSetTypeElementCompositeKey.java @@ -41,7 +41,6 @@ public class DistributionSetTypeElementCompositeKey implements Serializable { * in the key */ DistributionSetTypeElementCompositeKey(final JpaDistributionSetType dsType, final JpaSoftwareModuleType smType) { - super(); this.dsType = dsType.getId(); this.smType = smType.getId(); } @@ -61,4 +60,43 @@ public Long getSmType() { public void setSmType(final Long smType) { this.smType = smType; } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((dsType == null) ? 0 : dsType.hashCode()); + result = prime * result + ((smType == null) ? 0 : smType.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final DistributionSetTypeElementCompositeKey other = (DistributionSetTypeElementCompositeKey) obj; + if (dsType == null) { + if (other.dsType != null) { + return false; + } + } else if (!dsType.equals(other.dsType)) { + return false; + } + if (smType == null) { + if (other.smType != null) { + return false; + } + } else if (!smType.equals(other.smType)) { + return false; + } + return true; + } + } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/DsMetadataCompositeKey.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/DsMetadataCompositeKey.java index 52ad217c08..b186d6f367 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/DsMetadataCompositeKey.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/DsMetadataCompositeKey.java @@ -10,8 +10,6 @@ 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. @@ -34,8 +32,8 @@ public DsMetadataCompositeKey() { * @param key * the key of the meta data */ - public DsMetadataCompositeKey(final DistributionSet distributionSet, final String key) { - this.distributionSet = distributionSet.getId(); + public DsMetadataCompositeKey(final Long distributionSet, final String key) { + this.distributionSet = distributionSet; this.key = key; } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaAction.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaAction.java index 01e4e5676f..8bb30b5114 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaAction.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaAction.java @@ -99,7 +99,6 @@ public DistributionSet getDistributionSet() { return distributionSet; } - @Override public void setDistributionSet(final DistributionSet distributionSet) { this.distributionSet = (JpaDistributionSet) distributionSet; } @@ -113,7 +112,6 @@ public Status getStatus() { return status; } - @Override public void setStatus(final Status status) { this.status = status; } @@ -141,7 +139,6 @@ public List getActionStatus() { return Collections.unmodifiableList(actionStatus); } - @Override public void setTarget(final Target target) { this.target = (JpaTarget) target; } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaActionStatus.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaActionStatus.java index 131ed81137..72670fa412 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaActionStatus.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaActionStatus.java @@ -104,6 +104,35 @@ public JpaActionStatus(final JpaAction action, final Status status, final Long o addMessage(message); } + /** + * Creates a new {@link ActionStatus} object. + * + * @param status + * the status for this action status + * @param occurredAt + * the occurred timestamp + */ + public JpaActionStatus(final Status status, final long occurredAt) { + this.status = status; + this.occurredAt = occurredAt; + } + + /** + * Creates a new {@link ActionStatus} object. + * + * @param status + * the status for this action status + * @param occurredAt + * the occurred timestamp + * @param message + * the message which should be added to this action status + */ + public JpaActionStatus(final Status status, final Long occurredAt, final String message) { + this.status = status; + this.occurredAt = occurredAt; + addMessage(message); + } + /** * JPA default constructor. */ @@ -116,12 +145,10 @@ public Long getOccurredAt() { return occurredAt; } - @Override public void setOccurredAt(final Long occurredAt) { this.occurredAt = occurredAt; } - @Override public final void addMessage(final String message) { if (message != null) { if (messages == null) { @@ -145,7 +172,6 @@ public Action getAction() { return action; } - @Override public void setAction(final Action action) { this.action = (JpaAction) action; } @@ -155,7 +181,6 @@ public Status getStatus() { return status; } - @Override public void setStatus(final Status status) { this.status = status; } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaArtifact.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaArtifact.java index 8472504918..63125e8f5f 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaArtifact.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaArtifact.java @@ -23,6 +23,7 @@ import org.eclipse.hawkbit.artifact.repository.model.DbArtifact; import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.SoftwareModule; +import org.hibernate.validator.constraints.NotEmpty; /** * JPA implementation of {@link LocalArtifact}. @@ -37,14 +38,14 @@ public class JpaArtifact extends AbstractJpaTenantAwareBaseEntity implements Artifact { private static final long serialVersionUID = 1L; - @NotNull @Column(name = "gridfs_file_name", length = 40) @Size(max = 40) + @NotEmpty private String gridFsFileName; - @NotNull @Column(name = "provided_file_name", length = 256) @Size(max = 256) + @NotEmpty private String filename; @ManyToOne(optional = false, cascade = { CascadeType.PERSIST }) diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSet.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSet.java index fe2fc53f38..b57d103a38 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSet.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSet.java @@ -45,7 +45,6 @@ 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.TargetFilterQuery; import org.eclipse.hawkbit.repository.model.TargetInfo; @@ -143,11 +142,15 @@ public JpaDistributionSet() { * of the {@link DistributionSet} * @param moduleList * {@link SoftwareModule}s of the {@link DistributionSet} + * @param requiredMigrationStep + * of the {@link DistributionSet} */ public JpaDistributionSet(final String name, final String version, final String description, - final DistributionSetType type, final Collection moduleList) { + final DistributionSetType type, final Collection moduleList, + final boolean requiredMigrationStep) { super(name, version, description); + this.requiredMigrationStep = requiredMigrationStep; this.type = type; if (moduleList != null) { moduleList.forEach(this::addModule); @@ -157,6 +160,25 @@ public JpaDistributionSet(final String name, final String version, final String } } + /** + * Parameterized constructor. + * + * @param name + * of the {@link DistributionSet} + * @param version + * of the {@link DistributionSet} + * @param description + * of the {@link DistributionSet} + * @param type + * of the {@link DistributionSet} + * @param moduleList + * {@link SoftwareModule}s of the {@link DistributionSet} + */ + public JpaDistributionSet(final String name, final String version, final String description, + final DistributionSetType type, final Collection moduleList) { + this(name, version, description, type, moduleList, false); + } + @Override public Set getTags() { if (tags == null) { @@ -166,7 +188,6 @@ public Set getTags() { return Collections.unmodifiableSet(tags); } - @Override public boolean addTag(final DistributionSetTag tag) { if (tags == null) { tags = new HashSet<>(); @@ -175,7 +196,6 @@ public boolean addTag(final DistributionSetTag tag) { return tags.add(tag); } - @Override public boolean removeTag(final DistributionSetTag tag) { if (tags == null) { return false; @@ -211,13 +231,11 @@ 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; @@ -261,7 +279,6 @@ public Set getModules() { return Collections.unmodifiableSet(modules); } - @Override public boolean addModule(final SoftwareModule softwareModule) { if (modules == null) { modules = new HashSet<>(); @@ -304,7 +321,6 @@ private void checkTypeCompatability(final SoftwareModule softwareModule) { } } - @Override public boolean removeModule(final SoftwareModule softwareModule) { if (modules == null) { return false; @@ -323,21 +339,11 @@ public boolean removeModule(final SoftwareModule softwareModule) { } - @Override - public SoftwareModule findFirstModuleByType(final SoftwareModuleType type) { - if (modules == null) { - return null; - } - - return modules.stream().filter(module -> module.getType().equals(type)).findFirst().orElse(null); - } - @Override public DistributionSetType getType() { return type; } - @Override public void setType(final DistributionSetType type) { this.type = type; } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetMetadata.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetMetadata.java index 3f4323bbec..db8dd7354a 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetMetadata.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetMetadata.java @@ -28,7 +28,7 @@ @IdClass(DsMetadataCompositeKey.class) @Entity @Table(name = "sp_ds_metadata") -public class JpaDistributionSetMetadata extends AbstractJpaMetaData implements DistributionSetMetadata { +public class JpaDistributionSetMetadata extends JpaMetaData implements DistributionSetMetadata { private static final long serialVersionUID = 1L; @Id @@ -46,7 +46,7 @@ public JpaDistributionSetMetadata(final String key, final DistributionSet distri } public DsMetadataCompositeKey getId() { - return new DsMetadataCompositeKey(distributionSet, getKey()); + return new DsMetadataCompositeKey(distributionSet.getId(), getKey()); } public void setDistributionSet(final DistributionSet distributionSet) { diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetTag.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetTag.java index dee17a80e0..a1a9fcbcc6 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetTag.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetTag.java @@ -30,7 +30,7 @@ @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 JpaDistributionSetTag extends AbstractJpaTag implements DistributionSetTag { +public class JpaDistributionSetTag extends JpaTag implements DistributionSetTag { private static final long serialVersionUID = 1L; @ManyToMany(mappedBy = "tags", targetEntity = JpaDistributionSet.class, fetch = FetchType.LAZY) diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetType.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetType.java index 44bed8cce4..cded4d4d52 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetType.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetType.java @@ -28,7 +28,9 @@ import org.apache.commons.collections4.CollectionUtils; 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.hibernate.validator.constraints.NotEmpty; /** * A distribution set type defines which software module types can or have to be @@ -54,6 +56,7 @@ public class JpaDistributionSetType extends AbstractJpaNamedEntity implements Di @Column(name = "type_key", nullable = false, length = 64) @Size(max = 64) + @NotEmpty private String key; @Column(name = "colour", nullable = true, length = 16) @@ -90,13 +93,13 @@ public JpaDistributionSetType(final String key, final String name, final String * of the type * @param description * of the type - * @param color + * @param colour * of the type. It will be null by default */ - public JpaDistributionSetType(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 colour) { super(name, description); this.key = key; - colour = color; + this.colour = colour; } @Override @@ -114,8 +117,8 @@ public Set getMandatoryModuleTypes() { return Collections.emptySet(); } - return elements.stream().filter(element -> element.isMandatory()).map(element -> element.getSmType()) - .collect(Collectors.toSet()); + return elements.stream().filter(DistributionSetTypeElement::isMandatory) + .map(DistributionSetTypeElement::getSmType).collect(Collectors.toSet()); } @Override @@ -124,7 +127,7 @@ public Set getOptionalModuleTypes() { return Collections.emptySet(); } - return elements.stream().filter(element -> !element.isMandatory()).map(element -> element.getSmType()) + return elements.stream().filter(element -> !element.isMandatory()).map(DistributionSetTypeElement::getSmType) .collect(Collectors.toSet()); } @@ -136,7 +139,7 @@ public boolean areModuleEntriesIdentical(final DistributionSetType dsType) { return true; } - return new HashSet(((JpaDistributionSetType) dsType).elements).equals(elements); + return new HashSet<>(((JpaDistributionSetType) dsType).elements).equals(elements); } private boolean isOneModuleListEmpty(final DistributionSetType dsType) { @@ -150,41 +153,42 @@ private boolean areBothModuleListsEmpty(final DistributionSetType dsType) { return CollectionUtils.isEmpty(((JpaDistributionSetType) dsType).elements) && CollectionUtils.isEmpty(elements); } - @Override - public DistributionSetType addOptionalModuleType(final SoftwareModuleType smType) { - if (elements == null) { - elements = new HashSet<>(); - } - - elements.add(new DistributionSetTypeElement(this, (JpaSoftwareModuleType) smType, false)); + public JpaDistributionSetType addOptionalModuleType(final SoftwareModuleType smType) { + return setModuleType(smType, false); + } - return this; + public JpaDistributionSetType addMandatoryModuleType(final SoftwareModuleType smType) { + return setModuleType(smType, true); } - @Override - public DistributionSetType addMandatoryModuleType(final SoftwareModuleType smType) { + private JpaDistributionSetType setModuleType(final SoftwareModuleType smType, final boolean mandatory) { if (elements == null) { elements = new HashSet<>(); + elements.add(new DistributionSetTypeElement(this, (JpaSoftwareModuleType) smType, mandatory)); + return this; } - elements.add(new DistributionSetTypeElement(this, (JpaSoftwareModuleType) smType, true)); + // check if this was in the list before before + final Optional existing = elements.stream() + .filter(element -> element.getSmType().getKey().equals(smType.getKey())).findFirst(); + + if (existing.isPresent()) { + existing.get().setMandatory(mandatory); + } else { + elements.add(new DistributionSetTypeElement(this, (JpaSoftwareModuleType) smType, mandatory)); + } return this; } - @Override - public DistributionSetType removeModuleType(final Long smTypeId) { + public JpaDistributionSetType removeModuleType(final Long smTypeId) { if (elements == null) { return this; } // we search by id (standard equals compares also revison) - final Optional found = elements.stream() - .filter(element -> element.getSmType().getId().equals(smTypeId)).findFirst(); - - if (found.isPresent()) { - elements.remove(found.get()); - } + elements.stream().filter(element -> element.getSmType().getId().equals(smTypeId)).findFirst() + .ifPresent(elements::remove); return this; } @@ -194,14 +198,13 @@ public String getKey() { return key; } - @Override public void setKey(final String key) { this.key = key; } @Override public boolean checkComplete(final DistributionSet distributionSet) { - return distributionSet.getModules().stream().map(module -> module.getType()).collect(Collectors.toList()) + return distributionSet.getModules().stream().map(SoftwareModule::getType).collect(Collectors.toList()) .containsAll(getMandatoryModuleTypes()); } @@ -210,7 +213,6 @@ public String getColour() { return colour; } - @Override public void setColour(final String colour) { this.colour = colour; } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaMetaData.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaMetaData.java similarity index 87% rename from hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaMetaData.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaMetaData.java index c6df089f7d..c5b2bfd6b8 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaMetaData.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaMetaData.java @@ -12,23 +12,23 @@ import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.MappedSuperclass; -import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.eclipse.hawkbit.repository.model.MetaData; +import org.hibernate.validator.constraints.NotEmpty; /** * Meta data for entities. * */ @MappedSuperclass -public abstract class AbstractJpaMetaData implements MetaData { +public class JpaMetaData implements MetaData { private static final long serialVersionUID = 1L; @Id @Column(name = "meta_key", nullable = false, length = 128) @Size(min = 1, max = 128) - @NotNull + @NotEmpty private String key; @Column(name = "meta_value", length = 4000) @@ -36,12 +36,12 @@ public abstract class AbstractJpaMetaData implements MetaData { @Basic private String value; - public AbstractJpaMetaData(final String key, final String value) { + public JpaMetaData(final String key, final String value) { this.key = key; this.value = value; } - public AbstractJpaMetaData() { + public JpaMetaData() { // Default constructor needed for JPA entities } @@ -50,7 +50,6 @@ public String getKey() { return key; } - @Override public void setKey(final String key) { this.key = key; } @@ -60,7 +59,6 @@ public String getValue() { return value; } - @Override public void setValue(final String value) { this.value = value; } @@ -85,7 +83,7 @@ public boolean equals(final Object obj) { if (!(this.getClass().isInstance(obj))) { return false; } - final AbstractJpaMetaData other = (AbstractJpaMetaData) obj; + final JpaMetaData other = (JpaMetaData) obj; if (key == null) { if (other.key != null) { return false; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaRollout.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaRollout.java index ef9fd9cf69..3925a82cbb 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaRollout.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaRollout.java @@ -30,12 +30,13 @@ import org.eclipse.hawkbit.repository.event.remote.entity.RolloutUpdatedEvent; import org.eclipse.hawkbit.repository.model.Action.ActionType; -import org.eclipse.hawkbit.repository.model.helper.EventPublisherHolder; 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; +import org.eclipse.hawkbit.repository.model.helper.EventPublisherHolder; import org.eclipse.persistence.descriptors.DescriptorEvent; +import org.hibernate.validator.constraints.NotEmpty; /** * JPA implementation of a {@link Rollout}. @@ -58,7 +59,7 @@ public class JpaRollout extends AbstractJpaNamedEntity implements Rollout, Event @Column(name = "target_filter", length = 1024, nullable = false) @Size(max = 1024) - @NotNull + @NotEmpty private String targetFilterQuery; @ManyToOne(fetch = FetchType.LAZY) @@ -94,7 +95,6 @@ public DistributionSet getDistributionSet() { return distributionSet; } - @Override public void setDistributionSet(final DistributionSet distributionSet) { this.distributionSet = (JpaDistributionSet) distributionSet; } @@ -113,7 +113,6 @@ public String getTargetFilterQuery() { return targetFilterQuery; } - @Override public void setTargetFilterQuery(final String targetFilterQuery) { this.targetFilterQuery = targetFilterQuery; } @@ -140,7 +139,6 @@ public ActionType getActionType() { return actionType; } - @Override public void setActionType(final ActionType actionType) { this.actionType = actionType; } @@ -150,7 +148,6 @@ public long getForcedTime() { return forcedTime; } - @Override public void setForcedTime(final long forcedTime) { this.forcedTime = forcedTime; } 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 index dbf70b86ee..018ca66edd 100644 --- 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 @@ -24,6 +24,7 @@ import javax.persistence.Table; import javax.persistence.Transient; import javax.persistence.UniqueConstraint; +import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.eclipse.hawkbit.repository.event.remote.entity.RolloutGroupUpdatedEvent; @@ -63,16 +64,19 @@ public class JpaRolloutGroup extends AbstractJpaNamedEntity implements RolloutGr private JpaRolloutGroup parent; @Column(name = "success_condition", nullable = false) + @NotNull private RolloutGroupSuccessCondition successCondition = RolloutGroupSuccessCondition.THRESHOLD; @Column(name = "success_condition_exp", length = 512, nullable = false) @Size(max = 512) + @NotNull private String successConditionExp; @Column(name = "success_action", nullable = false) + @NotNull private RolloutGroupSuccessAction successAction = RolloutGroupSuccessAction.NEXTGROUP; - @Column(name = "success_action_exp", length = 512, nullable = false) + @Column(name = "success_action_exp", length = 512) @Size(max = 512) private String successActionExp; @@ -108,7 +112,6 @@ public Rollout getRollout() { return rollout; } - @Override public void setRollout(final Rollout rollout) { this.rollout = (JpaRollout) rollout; } @@ -118,7 +121,6 @@ public RolloutGroupStatus getStatus() { return status; } - @Override public void setStatus(final RolloutGroupStatus status) { this.status = status; } @@ -145,7 +147,6 @@ public RolloutGroupSuccessCondition getSuccessCondition() { return successCondition; } - @Override public void setSuccessCondition(final RolloutGroupSuccessCondition finishCondition) { successCondition = finishCondition; } @@ -155,7 +156,6 @@ public String getSuccessConditionExp() { return successConditionExp; } - @Override public void setSuccessConditionExp(final String finishExp) { successConditionExp = finishExp; } @@ -165,7 +165,6 @@ public RolloutGroupErrorCondition getErrorCondition() { return errorCondition; } - @Override public void setErrorCondition(final RolloutGroupErrorCondition errorCondition) { this.errorCondition = errorCondition; } @@ -175,7 +174,6 @@ public String getErrorConditionExp() { return errorConditionExp; } - @Override public void setErrorConditionExp(final String errorExp) { errorConditionExp = errorExp; } @@ -185,7 +183,6 @@ public RolloutGroupErrorAction getErrorAction() { return errorAction; } - @Override public void setErrorAction(final RolloutGroupErrorAction errorAction) { this.errorAction = errorAction; } @@ -195,7 +192,6 @@ public String getErrorActionExp() { return errorActionExp; } - @Override public void setErrorActionExp(final String errorActionExp) { this.errorActionExp = errorActionExp; } @@ -219,12 +215,10 @@ public void setTotalTargets(final int totalTargets) { this.totalTargets = totalTargets; } - @Override public void setSuccessAction(final RolloutGroupSuccessAction successAction) { this.successAction = successAction; } - @Override public void setSuccessActionExp(final String successActionExp) { this.successActionExp = successActionExp; } @@ -234,8 +228,7 @@ public String getTargetFilterQuery() { return targetFilterQuery; } - @Override - public void setTargetFilterQuery(String targetFilterQuery) { + public void setTargetFilterQuery(final String targetFilterQuery) { this.targetFilterQuery = targetFilterQuery; } @@ -244,8 +237,7 @@ public float getTargetPercentage() { return targetPercentage; } - @Override - public void setTargetPercentage(float targetPercentage) { + public void setTargetPercentage(final float targetPercentage) { this.targetPercentage = targetPercentage; } @@ -255,7 +247,7 @@ public void setTargetPercentage(float targetPercentage) { @Override public TotalTargetCountStatus getTotalTargetCountStatus() { if (totalTargetCountStatus == null) { - totalTargetCountStatus = new TotalTargetCountStatus(new Long(totalTargets)); + totalTargetCountStatus = new TotalTargetCountStatus(Long.valueOf(totalTargets)); } return totalTargetCountStatus; } @@ -264,7 +256,6 @@ public TotalTargetCountStatus getTotalTargetCountStatus() { * @param totalTargetCountStatus * the totalTargetCountStatus to set */ - @Override public void setTotalTargetCountStatus(final TotalTargetCountStatus totalTargetCountStatus) { this.totalTargetCountStatus = totalTargetCountStatus; } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModule.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModule.java index 096d0460f4..afa252de5b 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModule.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModule.java @@ -108,7 +108,6 @@ public JpaSoftwareModule(final SoftwareModuleType type, final String name, final this.type = (JpaSoftwareModuleType) type; } - @Override public void addArtifact(final Artifact artifact) { if (null == artifacts) { artifacts = new ArrayList<>(4); @@ -148,7 +147,6 @@ public void removeArtifact(final Artifact artifact) { } } - @Override public void setVendor(final String vendor) { this.vendor = vendor; } @@ -174,9 +172,8 @@ public void setDeleted(final boolean deleted) { this.deleted = deleted; } - @Override - public void setType(final SoftwareModuleType type) { - this.type = (JpaSoftwareModuleType) type; + public void setType(final JpaSoftwareModuleType type) { + this.type = type; } public List getMetadata() { diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModuleMetadata.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModuleMetadata.java index 8b085c2ce1..7038ee3396 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModuleMetadata.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModuleMetadata.java @@ -28,7 +28,7 @@ @IdClass(SwMetadataCompositeKey.class) @Entity @Table(name = "sp_sw_metadata") -public class JpaSoftwareModuleMetadata extends AbstractJpaMetaData implements SoftwareModuleMetadata { +public class JpaSoftwareModuleMetadata extends JpaMetaData implements SoftwareModuleMetadata { private static final long serialVersionUID = 1L; @Id @@ -54,7 +54,6 @@ public SoftwareModule getSoftwareModule() { return softwareModule; } - @Override public void setSoftwareModule(final SoftwareModule softwareModule) { this.softwareModule = softwareModule; } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModuleType.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModuleType.java index 5010ae9180..9983e3438a 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModuleType.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaSoftwareModuleType.java @@ -14,10 +14,10 @@ import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.constraints.Min; -import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; +import org.hibernate.validator.constraints.NotEmpty; /** * Type of a software modules. @@ -37,7 +37,7 @@ public class JpaSoftwareModuleType extends AbstractJpaNamedEntity implements Sof @Column(name = "type_key", nullable = false, length = 64) @Size(max = 64) - @NotNull + @NotEmpty private String key; @Column(name = "max_ds_assignments", nullable = false) @@ -84,7 +84,6 @@ public JpaSoftwareModuleType(final String key, final String name, final String d */ public JpaSoftwareModuleType(final String key, final String name, final String description, final int maxAssignments, final String colour) { - super(); this.key = key; this.maxAssignments = maxAssignments; setDescription(description); @@ -99,7 +98,6 @@ public JpaSoftwareModuleType() { // Default Constructor for JPA. } - @Override public void setMaxAssignments(final int maxAssignments) { this.maxAssignments = maxAssignments; } @@ -128,7 +126,6 @@ public String getColour() { return colour; } - @Override public void setColour(final String colour) { this.colour = colour; } @@ -138,7 +135,6 @@ 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/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaTag.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTag.java similarity index 87% rename from hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaTag.java rename to hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTag.java index f759d16fc5..7e0070c9a4 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/AbstractJpaTag.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTag.java @@ -23,14 +23,14 @@ // exception squid:S2160 - BaseEntity equals/hashcode is handling correctly for // sub entities @SuppressWarnings("squid:S2160") -public abstract class AbstractJpaTag extends AbstractJpaNamedEntity implements Tag { +public class JpaTag extends AbstractJpaNamedEntity implements Tag { private static final long serialVersionUID = 1L; @Column(name = "colour", nullable = true, length = 16) @Size(max = 16) private String colour; - protected AbstractJpaTag() { + protected JpaTag() { // Default constructor needed for JPA entities } @@ -44,7 +44,7 @@ protected AbstractJpaTag() { * @param colour * of tag in UI */ - public AbstractJpaTag(final String name, final String description, final String colour) { + public JpaTag(final String name, final String description, final String colour) { super(name, description); this.colour = colour; } @@ -54,7 +54,6 @@ public String getColour() { return colour; } - @Override public void setColour(final String colour) { this.colour = colour; } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTarget.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTarget.java index 90747b493d..eb8fa8cad9 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTarget.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTarget.java @@ -33,7 +33,6 @@ import javax.persistence.Table; import javax.persistence.Transient; import javax.persistence.UniqueConstraint; -import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.eclipse.hawkbit.im.authentication.SpPermission; @@ -51,6 +50,7 @@ import org.eclipse.hawkbit.repository.model.helper.EventPublisherHolder; import org.eclipse.persistence.annotations.CascadeOnDelete; import org.eclipse.persistence.descriptors.DescriptorEvent; +import org.hibernate.validator.constraints.NotEmpty; import org.springframework.data.domain.Persistable; /** @@ -76,7 +76,7 @@ public class JpaTarget extends AbstractJpaNamedEntity implements Persistable getRolloutTargetGroup() { return Collections.unmodifiableList(rolloutTargetGroup); } - @Override public boolean addTag(final TargetTag tag) { if (tags == null) { tags = new HashSet<>(); @@ -183,7 +182,6 @@ public boolean addTag(final TargetTag tag) { return tags.add(tag); } - @Override public boolean removeTag(final TargetTag tag) { if (tags == null) { return false; @@ -266,7 +264,6 @@ public String getSecurityToken() { * @param securityToken * the securityToken to set */ - @Override public void setSecurityToken(final String securityToken) { this.securityToken = securityToken; } @@ -290,7 +287,7 @@ public void fireUpdateEvent(final DescriptorEvent descriptorEvent) { @Override public void fireDeleteEvent(final DescriptorEvent descriptorEvent) { - EventPublisherHolder.getInstance().getEventPublisher() - .publishEvent(new TargetDeletedEvent(getTenant(), getId(), EventPublisherHolder.getInstance().getApplicationId())); + EventPublisherHolder.getInstance().getEventPublisher().publishEvent( + new TargetDeletedEvent(getTenant(), getId(), EventPublisherHolder.getInstance().getApplicationId())); } } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetFilterQuery.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetFilterQuery.java index b7e80cbb3a..faa766348d 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetFilterQuery.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetFilterQuery.java @@ -18,11 +18,11 @@ import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; -import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.TargetFilterQuery; +import org.hibernate.validator.constraints.NotEmpty; /** * Stored target filter. @@ -40,12 +40,12 @@ public class JpaTargetFilterQuery extends AbstractJpaTenantAwareBaseEntity imple @Column(name = "name", length = 64, nullable = false) @Size(max = 64) - @NotNull + @NotEmpty private String name; @Column(name = "query", length = 1024, nullable = false) @Size(max = 1024) - @NotNull + @NotEmpty private String query; @ManyToOne(optional = true, fetch = FetchType.LAZY, targetEntity = JpaDistributionSet.class) @@ -79,10 +79,11 @@ public JpaTargetFilterQuery(final String name, final String query) { * @param autoAssignDistributionSet * of the {@link TargetFilterQuery}. */ - public JpaTargetFilterQuery(String name, String query, JpaDistributionSet autoAssignDistributionSet) { + public JpaTargetFilterQuery(final String name, final String query, + final DistributionSet autoAssignDistributionSet) { this.name = name; this.query = query; - this.autoAssignDistributionSet = autoAssignDistributionSet; + this.autoAssignDistributionSet = (JpaDistributionSet) autoAssignDistributionSet; } @Override @@ -90,7 +91,6 @@ public String getName() { return name; } - @Override public void setName(final String name) { this.name = name; } @@ -100,7 +100,6 @@ public String getQuery() { return query; } - @Override public void setQuery(final String query) { this.query = query; } @@ -110,8 +109,7 @@ public DistributionSet getAutoAssignDistributionSet() { return autoAssignDistributionSet; } - @Override - public void setAutoAssignDistributionSet(DistributionSet distributionSet) { - autoAssignDistributionSet = (JpaDistributionSet)distributionSet; + public void setAutoAssignDistributionSet(final JpaDistributionSet distributionSet) { + this.autoAssignDistributionSet = distributionSet; } } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetInfo.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetInfo.java index 54f5370d1c..fe87b951b2 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetInfo.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetInfo.java @@ -40,20 +40,16 @@ import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; -import org.eclipse.hawkbit.repository.event.remote.entity.TargetUpdatedEvent; -import org.eclipse.hawkbit.repository.exception.InvalidTargetAddressException; import org.eclipse.hawkbit.repository.jpa.model.helper.SystemSecurityContextHolder; 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.repository.model.helper.EventPublisherHolder; import org.eclipse.hawkbit.repository.model.helper.TenantConfigurationManagementHolder; import org.eclipse.hawkbit.tenancy.configuration.DurationHelper; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; import org.eclipse.persistence.annotations.CascadeOnDelete; -import org.eclipse.persistence.descriptors.DescriptorEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Persistable; @@ -71,7 +67,7 @@ @Index(name = "sp_idx_target_info_02", columnList = "target_id,update_status") }) @Entity @EntityListeners(EntityPropertyChangeListener.class) -public class JpaTargetInfo implements Persistable, TargetInfo, EventAwareEntity { +public class JpaTargetInfo implements Persistable, TargetInfo { private static final long serialVersionUID = 1L; private static final Logger LOG = LoggerFactory.getLogger(TargetInfo.class); @@ -176,25 +172,7 @@ public URI getAddress() { } } - /** - * @param address - * the target address to set - * - * @throws IllegalArgumentException - * If the given string violates RFC 2396 - */ - @Override public void setAddress(final String address) { - // check if this is a real URI - if (address != null) { - try { - URI.create(address); - } catch (final IllegalArgumentException e) { - throw new InvalidTargetAddressException( - "The given address " + address + " violates the RFC-2396 specification", e); - } - } - this.address = address; } @@ -330,20 +308,4 @@ public boolean equals(final Object obj) { } return true; } - - @Override - public void fireCreateEvent(final DescriptorEvent descriptorEvent) { - // there is no target info created event - } - - @Override - public void fireUpdateEvent(final DescriptorEvent descriptorEvent) { - EventPublisherHolder.getInstance().getEventPublisher().publishEvent( - new TargetUpdatedEvent(this.getTarget(), EventPublisherHolder.getInstance().getApplicationId())); - } - - @Override - public void fireDeleteEvent(final DescriptorEvent descriptorEvent) { - // there is no target info deleted event - } } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetTag.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetTag.java index a77d4b42db..91fbc16a1a 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetTag.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTargetTag.java @@ -30,7 +30,7 @@ @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 JpaTargetTag extends AbstractJpaTag implements TargetTag { +public class JpaTargetTag extends JpaTag implements TargetTag { private static final long serialVersionUID = 1L; @ManyToMany(mappedBy = "tags", targetEntity = JpaTarget.class, fetch = FetchType.LAZY) diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTenantConfiguration.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTenantConfiguration.java index 3158042267..836052c9e1 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTenantConfiguration.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTenantConfiguration.java @@ -17,6 +17,7 @@ import javax.validation.constraints.Size; import org.eclipse.hawkbit.repository.model.TenantConfiguration; +import org.hibernate.validator.constraints.NotEmpty; /** * A JPA entity which stores the tenant specific configuration. @@ -33,7 +34,7 @@ public class JpaTenantConfiguration extends AbstractJpaTenantAwareBaseEntity imp @Column(name = "conf_key", length = 128, nullable = false) @Size(max = 128) - @NotNull + @NotEmpty private String key; @Column(name = "conf_value", length = 512, nullable = false) @@ -66,7 +67,6 @@ public String getKey() { return key; } - @Override public void setKey(final String key) { this.key = key; } @@ -76,7 +76,6 @@ public String getValue() { return value; } - @Override public void setValue(final String value) { this.value = value; } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTenantMetaData.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTenantMetaData.java index 7fcb3c50e0..8bdd0632d2 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTenantMetaData.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaTenantMetaData.java @@ -76,7 +76,6 @@ public DistributionSetType getDefaultDsType() { return defaultDsType; } - @Override public void setDefaultDsType(final DistributionSetType defaultDsType) { this.defaultDsType = (JpaDistributionSetType) defaultDsType; } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/PauseRolloutGroupAction.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/PauseRolloutGroupAction.java index e20f632f82..fe08fa166f 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/PauseRolloutGroupAction.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/PauseRolloutGroupAction.java @@ -40,10 +40,12 @@ public boolean verifyExpression(final String expression) { } @Override - public void eval(final Rollout rollout, final RolloutGroup rolloutGroup, final String expression) { + public void eval(final Rollout rollout, final RolloutGroup rolloutG, final String expression) { + final JpaRolloutGroup rolloutGroup = (JpaRolloutGroup) rolloutG; + systemSecurityContext.runAsSystem(() -> { rolloutGroup.setStatus(RolloutGroupStatus.ERROR); - rolloutGroupRepository.save((JpaRolloutGroup) rolloutGroup); + rolloutGroupRepository.save(rolloutGroup); rolloutManagement.pauseRollout(rollout); return null; }); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/RolloutGroupConditionEvaluator.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/RolloutGroupConditionEvaluator.java index 0690f72eca..5575d7cff4 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/RolloutGroupConditionEvaluator.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/RolloutGroupConditionEvaluator.java @@ -21,12 +21,8 @@ default boolean verifyExpression(final String expression) { // percentage value between 0 and 100 try { final Integer value = Integer.valueOf(expression); - if (value >= 0 || value <= 100) { - return true; - } - return true; + return value >= 0 && value <= 100; } catch (final NumberFormatException e) { - return false; } } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLUtility.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLUtility.java index 9c7ab5e0a1..d1100aa05a 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLUtility.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLUtility.java @@ -50,8 +50,9 @@ import cz.jirutka.rsql.parser.ast.RSQLVisitor; /** - * A utility class which is able to parse RSQL strings into an spring data {@link Specification} which then can be - * enhanced sql queries to filter entities. RSQL parser library: https://github.com/jirutka/rsql-parser + * A utility class which is able to parse RSQL strings into an spring data + * {@link Specification} which then can be enhanced sql queries to filter + * entities. RSQL parser library: https://github.com/jirutka/rsql-parser * *

    *
  • Equal to : ==
  • @@ -71,13 +72,15 @@ *
  • name==targetId1 or description==plugAndPlay or updateStatus==UNKNOWN
  • *
*

- * There is also a mechanism that allows to refer to known macros that can resolved by an optional {@link StrLookup} - * (cp. {@link VirtualPropertyResolver}).
- * An example that queries for all overdue targets using the ${OVERDUE_TS} placeholder introduced by - * {@link VirtualPropertyResolver} looks like this:
+ * There is also a mechanism that allows to refer to known macros that can + * resolved by an optional {@link StrLookup} (cp. + * {@link VirtualPropertyResolver}).
+ * An example that queries for all overdue targets using the ${OVERDUE_TS} + * placeholder introduced by {@link VirtualPropertyResolver} looks like + * this:
* lastControllerRequestAt=le=${OVERDUE_TS}
- * It is possible to escape a macro expression by using a second '$': $${OVERDUE_TS} would prevent the ${OVERDUE_TS} - * token from being expanded. + * It is possible to escape a macro expression by using a second '$': + * $${OVERDUE_TS} would prevent the ${OVERDUE_TS} token from being expanded. * */ public final class RSQLUtility { @@ -111,7 +114,7 @@ private RSQLUtility() { * if the RSQL syntax is wrong */ public static & FieldNameProvider, T> Specification parse(final String rsql, - final Class fieldNameProvider, VirtualPropertyReplacer virtualPropertyReplacer) { + final Class fieldNameProvider, final VirtualPropertyReplacer virtualPropertyReplacer) { return new RSQLSpecification<>(rsql.toLowerCase(), fieldNameProvider, virtualPropertyReplacer); } @@ -146,7 +149,7 @@ private static final class RSQLSpecification & FieldNameProvid private final VirtualPropertyReplacer virtualPropertyReplacer; private RSQLSpecification(final String rsql, final Class enumType, - VirtualPropertyReplacer virtualPropertyReplacer) { + final VirtualPropertyReplacer virtualPropertyReplacer) { this.rsql = rsql; this.enumType = enumType; this.virtualPropertyReplacer = virtualPropertyReplacer; @@ -193,7 +196,7 @@ private static final class JpqQueryRSQLVisitor & FieldNameProv private final SimpleTypeConverter simpleTypeConverter; private JpqQueryRSQLVisitor(final Root root, final CriteriaBuilder cb, final Class enumType, - VirtualPropertyReplacer virtualPropertyReplacer) { + final VirtualPropertyReplacer virtualPropertyReplacer) { this.root = root; this.cb = cb; this.enumType = enumType; @@ -225,7 +228,7 @@ private static List toSingleList(final Predicate predicate) { private String getAndValidatePropertyFieldName(final A propertyEnum, final ComparisonNode node) { - final String[] graph = node.getSelector().split("\\" + FieldNameProvider.SUB_ATTRIBUTE_SEPERATOR); + final String[] graph = node.getSelector().split("\\" + SUB_ATTRIBUTE_SEPERATOR); validateMapParamter(propertyEnum, node, graph); @@ -281,7 +284,7 @@ private RSQLParameterUnsupportedFieldException createRSQLParameterUnsupportedExc private Path getFieldPath(final A enumField, final String finalProperty) { Path fieldPath = null; - final String[] split = finalProperty.split("\\" + FieldNameProvider.SUB_ATTRIBUTE_SEPERATOR); + final String[] split = finalProperty.split("\\" + SUB_ATTRIBUTE_SEPERATOR); if (split.length == 0) { return root.get(split[0]); } @@ -336,7 +339,7 @@ private List getExpectedFieldList() { final String enumFieldName = enumField.name().toLowerCase(); if (enumField.isMap()) { - return enumFieldName + FieldNameProvider.SUB_ATTRIBUTE_SEPERATOR + "keyName"; + return enumFieldName + SUB_ATTRIBUTE_SEPERATOR + "keyName"; } return enumFieldName; @@ -345,8 +348,7 @@ private List getExpectedFieldList() { final List expectedSubFieldList = Arrays.stream(enumType.getEnumConstants()) .filter(enumField -> !enumField.getSubEntityAttributes().isEmpty()).flatMap(enumField -> { final List subEntity = enumField.getSubEntityAttributes().stream() - .map(fieldName -> enumField.name().toLowerCase() - + FieldNameProvider.SUB_ATTRIBUTE_SEPERATOR + fieldName) + .map(fieldName -> enumField.name().toLowerCase() + SUB_ATTRIBUTE_SEPERATOR + fieldName) .collect(Collectors.toList()); return subEntity.stream(); @@ -357,7 +359,7 @@ private List getExpectedFieldList() { private A getFieldEnumByName(final ComparisonNode node) { String enumName = node.getSelector(); - final String[] graph = enumName.split("\\" + FieldNameProvider.SUB_ATTRIBUTE_SEPERATOR); + final String[] graph = enumName.split("\\" + SUB_ATTRIBUTE_SEPERATOR); if (graph.length != 0) { enumName = graph[0]; } @@ -536,7 +538,7 @@ private Predicate mapToMapPredicate(final ComparisonNode node, final Path findActionsByRolloutAndStatus(final Rollout rollout, final Action.Status actionStatus) { + return actionRepository.findByRolloutAndStatus((JpaRollout) rollout, actionStatus); + } } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ArtifactManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ArtifactManagementTest.java index 0b9bee9390..ac807f7b81 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ArtifactManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ArtifactManagementTest.java @@ -197,46 +197,22 @@ public void deleteDuplicateArtifacts() throws NoSuchAlgorithmException, IOExcept assertThat(binaryArtifactRepository.getArtifactBySha1(((JpaArtifact) result).getGridFsFileName())).isNull(); } - /** - * Test method for - * {@link org.eclipse.hawkbit.repository.ArtifactManagement#findArtifact(java.lang.Long)} - * . - * - * @throws IOException - * @throws NoSuchAlgorithmException - */ @Test @Description("Loads an local artifact based on given ID.") public void findArtifact() throws NoSuchAlgorithmException, IOException { - SoftwareModule sm = new JpaSoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", - "version 1", null, null); - sm = softwareManagement.createSoftwareModule(sm); - - final Artifact result = artifactManagement.createArtifact(new RandomGeneratedInputStream(5 * 1024), sm.getId(), - "file1", false); + final Artifact result = artifactManagement.createArtifact(new RandomGeneratedInputStream(5 * 1024), + testdataFactory.createSoftwareModuleOs().getId(), "file1", false); assertThat(artifactManagement.findArtifact(result.getId())).isEqualTo(result); } - /** - * Test method for - * {@link org.eclipse.hawkbit.repository.ArtifactManagement#loadArtifactBinary(java.lang.Long)} - * . - * - * @throws IOException - * @throws NoSuchAlgorithmException - */ @Test @Description("Loads an artifact binary based on given ID.") public void loadStreamOfArtifact() throws NoSuchAlgorithmException, IOException { - SoftwareModule sm = new JpaSoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", - "version 1", null, null); - sm = softwareManagement.createSoftwareModule(sm); - final byte random[] = RandomStringUtils.random(5 * 1024).getBytes(); - final Artifact result = artifactManagement.createArtifact(new ByteArrayInputStream(random), sm.getId(), "file1", - false); + final Artifact result = artifactManagement.createArtifact(new ByteArrayInputStream(random), + testdataFactory.createSoftwareModuleOs().getId(), "file1", false); try (InputStream fileInputStream = artifactManagement.loadArtifactBinary(result).getFileInputStream()) { assertTrue("The stored binary matches the given binary", @@ -259,11 +235,7 @@ public void loadArtifactBinaryWithoutDownloadArtifactThrowsPermissionDenied() { @Test @Description("Searches an artifact through the relations of a software module.") public void findArtifactBySoftwareModule() { - SoftwareModule sm = new JpaSoftwareModule(osType, "name 1", "version 1", null, null); - sm = softwareManagement.createSoftwareModule(sm); - - SoftwareModule sm2 = new JpaSoftwareModule(osType, "name 2", "version 2", null, null); - sm2 = softwareManagement.createSoftwareModule(sm2); + final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); assertThat(artifactManagement.findArtifactBySoftwareModule(pageReq, sm.getId())).isEmpty(); @@ -276,8 +248,7 @@ public void findArtifactBySoftwareModule() { @Test @Description("Searches an artifact through the relations of a software module and the filename.") public void findByFilenameAndSoftwareModule() { - SoftwareModule sm = new JpaSoftwareModule(osType, "name 1", "version 1", null, null); - sm = softwareManagement.createSoftwareModule(sm); + final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); assertThat(artifactManagement.findByFilenameAndSoftwareModule("file1", sm.getId())).isEmpty(); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ControllerManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ControllerManagementTest.java index 77adfa45b8..22473c43cc 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ControllerManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ControllerManagementTest.java @@ -11,21 +11,23 @@ import static org.fest.assertions.api.Assertions.assertThat; import static org.junit.Assert.fail; -import java.util.ArrayList; -import java.util.List; - import javax.validation.ConstraintViolationException; -import org.apache.commons.lang3.RandomStringUtils; import org.eclipse.hawkbit.repository.RepositoryProperties; -import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus; -import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; +import org.eclipse.hawkbit.repository.event.remote.TargetAssignDistributionSetEvent; +import org.eclipse.hawkbit.repository.event.remote.entity.ActionCreatedEvent; +import org.eclipse.hawkbit.repository.event.remote.entity.ActionUpdatedEvent; +import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetCreatedEvent; +import org.eclipse.hawkbit.repository.event.remote.entity.TargetCreatedEvent; +import org.eclipse.hawkbit.repository.event.remote.entity.TargetUpdatedEvent; +import org.eclipse.hawkbit.repository.jpa.model.JpaAction; 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.TargetUpdateStatus; +import org.eclipse.hawkbit.repository.test.matcher.Expect; +import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents; +import org.eclipse.hawkbit.repository.test.util.TestdataFactory; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -36,41 +38,39 @@ @Features("Component Tests - Repository") @Stories("Controller Management") public class ControllerManagementTest extends AbstractJpaIntegrationTest { + @Autowired private RepositoryProperties repositoryProperties; @Test @Description("Controller adds a new action status.") + @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1), + @Expect(type = DistributionSetCreatedEvent.class, count = 1), + @Expect(type = ActionCreatedEvent.class, count = 1), @Expect(type = ActionUpdatedEvent.class, count = 1), + @Expect(type = TargetUpdatedEvent.class, count = 2), + @Expect(type = TargetAssignDistributionSetEvent.class, count = 1) }) public void controllerAddsActionStatus() { - final Target target = new JpaTarget("4712"); final DistributionSet ds = testdataFactory.createDistributionSet(""); - Target savedTarget = targetManagement.createTarget(target); - - final List toAssign = new ArrayList<>(); - toAssign.add(savedTarget); + Target savedTarget = testdataFactory.createTarget(); assertThat(savedTarget.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.UNKNOWN); - savedTarget = deploymentManagement.assignDistributionSet(ds, toAssign).getAssignedEntity().iterator().next(); - final Action savedAction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0); + savedTarget = assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getAssignedEntity().iterator() + .next(); + final JpaAction savedAction = (JpaAction) deploymentManagement.findActiveActionsByTarget(savedTarget).get(0); assertThat(targetManagement.findTargetByControllerID(savedTarget.getControllerId()).getTargetInfo() .getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); - ActionStatus actionStatusMessage = new JpaActionStatus(savedAction, Action.Status.RUNNING, - System.currentTimeMillis()); - actionStatusMessage.addMessage("foobar"); - savedAction.setStatus(Status.RUNNING); - controllerManagament.addUpdateActionStatus(actionStatusMessage); - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) - .isEqualTo(TargetUpdateStatus.PENDING); - - actionStatusMessage = new JpaActionStatus(savedAction, Action.Status.FINISHED, System.currentTimeMillis()); - actionStatusMessage.addMessage(RandomStringUtils.randomAscii(512)); - savedAction.setStatus(Status.FINISHED); - controllerManagament.addUpdateActionStatus(actionStatusMessage); - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) - .isEqualTo(TargetUpdateStatus.IN_SYNC); + controllerManagament.addUpdateActionStatus( + entityFactory.actionStatus().create(savedAction.getId()).status(Action.Status.RUNNING)); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); + + controllerManagament.addUpdateActionStatus( + entityFactory.actionStatus().create(savedAction.getId()).status(Action.Status.FINISHED)); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC); assertThat(actionStatusRepository.findAll(pageReq).getNumberOfElements()).isEqualTo(3); assertThat(deploymentManagement.findActionStatusByAction(pageReq, savedAction).getNumberOfElements()) @@ -99,52 +99,40 @@ public void testfindOrRegisterTargetIfItDoesNotexist() { @Test @Description("Controller trys to finish an update process after it has been finished by an error action status.") public void tryToFinishUpdateProcessMoreThanOnce() { - - // mock - final Target target = new JpaTarget("Rabbit"); final DistributionSet ds = testdataFactory.createDistributionSet(""); - Target savedTarget = targetManagement.createTarget(target); - final List toAssign = new ArrayList<>(); - toAssign.add(savedTarget); - savedTarget = deploymentManagement.assignDistributionSet(ds, toAssign).getAssignedEntity().iterator().next(); + Target savedTarget = testdataFactory.createTarget(); + savedTarget = assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getAssignedEntity().iterator() + .next(); Action savedAction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0); // test and verify - final ActionStatus actionStatusMessage = new JpaActionStatus(savedAction, Action.Status.RUNNING, - System.currentTimeMillis()); - actionStatusMessage.addMessage("running"); - savedAction = controllerManagament.addUpdateActionStatus(actionStatusMessage); - assertThat(targetManagement.findTargetByControllerID("Rabbit").getTargetInfo().getUpdateStatus()) - .isEqualTo(TargetUpdateStatus.PENDING); - - final ActionStatus actionStatusMessage2 = new JpaActionStatus(savedAction, Action.Status.ERROR, - System.currentTimeMillis()); - actionStatusMessage2.addMessage("error"); - savedAction = controllerManagament.addUpdateActionStatus(actionStatusMessage2); - assertThat(targetManagement.findTargetByControllerID("Rabbit").getTargetInfo().getUpdateStatus()) - .isEqualTo(TargetUpdateStatus.ERROR); + savedAction = controllerManagament.addUpdateActionStatus( + entityFactory.actionStatus().create(savedAction.getId()).status(Action.Status.RUNNING)); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); + + savedAction = controllerManagament.addUpdateActionStatus( + entityFactory.actionStatus().create(savedAction.getId()).status(Action.Status.ERROR)); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getUpdateStatus()).isEqualTo(TargetUpdateStatus.ERROR); // try with disabled late feedback repositoryProperties.setRejectActionStatusForClosedAction(true); - final ActionStatus actionStatusMessage3 = new JpaActionStatus(savedAction, Action.Status.FINISHED, - System.currentTimeMillis()); - actionStatusMessage3.addMessage("finish"); - savedAction = controllerManagament.addUpdateActionStatus(actionStatusMessage3); + savedAction = controllerManagament.addUpdateActionStatus( + entityFactory.actionStatus().create(savedAction.getId()).status(Action.Status.FINISHED)); // test - assertThat(targetManagement.findTargetByControllerID("Rabbit").getTargetInfo().getUpdateStatus()) - .isEqualTo(TargetUpdateStatus.ERROR); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getUpdateStatus()).isEqualTo(TargetUpdateStatus.ERROR); // try with enabled late feedback repositoryProperties.setRejectActionStatusForClosedAction(false); - final ActionStatus actionStatusMessage4 = new JpaActionStatus(savedAction, Action.Status.FINISHED, - System.currentTimeMillis()); - actionStatusMessage4.addMessage("finish"); - controllerManagament.addUpdateActionStatus(actionStatusMessage3); + controllerManagament.addUpdateActionStatus( + entityFactory.actionStatus().create(savedAction.getId()).status(Action.Status.FINISHED)); // test - assertThat(targetManagement.findTargetByControllerID("Rabbit").getTargetInfo().getUpdateStatus()) - .isEqualTo(TargetUpdateStatus.ERROR); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getUpdateStatus()).isEqualTo(TargetUpdateStatus.ERROR); } @@ -154,16 +142,14 @@ public void tryToFinishUpdateProcessMoreThanOnce() { public void sendUpdatesForFinishUpdateProcessDropedIfDisabled() { repositoryProperties.setRejectActionStatusForClosedAction(true); - final Action action = prepareFinishedUpdate("Rabbit"); + final Action action = prepareFinishedUpdate(); - final ActionStatus actionStatusMessage1 = new JpaActionStatus(action, Action.Status.RUNNING, - System.currentTimeMillis()); - actionStatusMessage1.addMessage("got some additional feedback"); - controllerManagament.addUpdateActionStatus(actionStatusMessage1); + controllerManagament.addUpdateActionStatus( + entityFactory.actionStatus().create(action.getId()).status(Action.Status.RUNNING)); // nothing changed as "feedback after close" is disabled - assertThat(targetManagement.findTargetByControllerID("Rabbit").getTargetInfo().getUpdateStatus()) - .isEqualTo(TargetUpdateStatus.IN_SYNC); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC); assertThat(actionStatusRepository.findAll(pageReq).getNumberOfElements()).isEqualTo(3); assertThat(deploymentManagement.findActionStatusByAction(pageReq, action).getNumberOfElements()).isEqualTo(3); } @@ -174,51 +160,15 @@ public void sendUpdatesForFinishUpdateProcessDropedIfDisabled() { public void sendUpdatesForFinishUpdateProcessAcceptedIfEnabled() { repositoryProperties.setRejectActionStatusForClosedAction(false); - Action action = prepareFinishedUpdate("Rabbit"); - - final ActionStatus actionStatusMessage1 = new JpaActionStatus(action, Action.Status.RUNNING, - System.currentTimeMillis()); - actionStatusMessage1.addMessage("got some additional feedback"); - action = controllerManagament.addUpdateActionStatus(actionStatusMessage1); + Action action = prepareFinishedUpdate(); + action = controllerManagament.addUpdateActionStatus( + entityFactory.actionStatus().create(action.getId()).status(Action.Status.RUNNING)); // nothing changed as "feedback after close" is disabled - assertThat(targetManagement.findTargetByControllerID("Rabbit").getTargetInfo().getUpdateStatus()) - .isEqualTo(TargetUpdateStatus.IN_SYNC); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() + .getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC); assertThat(actionStatusRepository.findAll(pageReq).getNumberOfElements()).isEqualTo(4); assertThat(deploymentManagement.findActionStatusByAction(pageReq, action).getNumberOfElements()).isEqualTo(4); } - private Action prepareFinishedUpdate(final String controllerId) { - // mock - final Target target = new JpaTarget(controllerId); - final DistributionSet ds = testdataFactory.createDistributionSet(""); - Target savedTarget = targetManagement.createTarget(target); - final List toAssign = new ArrayList<>(); - toAssign.add(savedTarget); - savedTarget = deploymentManagement.assignDistributionSet(ds, toAssign).getAssignedEntity().iterator().next(); - Action savedAction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0); - - // test and verify - final ActionStatus actionStatusMessage = new JpaActionStatus(savedAction, Action.Status.RUNNING, - System.currentTimeMillis()); - actionStatusMessage.addMessage("running"); - savedAction = controllerManagament.addUpdateActionStatus(actionStatusMessage); - assertThat(targetManagement.findTargetByControllerID(controllerId).getTargetInfo().getUpdateStatus()) - .isEqualTo(TargetUpdateStatus.PENDING); - - final ActionStatus actionStatusMessage2 = new JpaActionStatus(savedAction, Action.Status.FINISHED, - System.currentTimeMillis()); - actionStatusMessage2.addMessage("finish"); - savedAction = controllerManagament.addUpdateActionStatus(actionStatusMessage2); - - // test - assertThat(targetManagement.findTargetByControllerID(controllerId).getTargetInfo().getUpdateStatus()) - .isEqualTo(TargetUpdateStatus.IN_SYNC); - - assertThat(actionStatusRepository.findAll(pageReq).getNumberOfElements()).isEqualTo(3); - assertThat(deploymentManagement.findActionStatusByAction(pageReq, savedAction).getNumberOfElements()) - .isEqualTo(3); - - return savedAction; - } } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DeploymentManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DeploymentManagementTest.java index bd91c82729..d59e77dc8d 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DeploymentManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DeploymentManagementTest.java @@ -30,14 +30,10 @@ 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; -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.DistributionSetAssignmentResult; @@ -56,6 +52,7 @@ import com.google.common.collect.Iterables; import com.google.common.collect.Lists; +import com.google.common.collect.Sets; import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; @@ -93,7 +90,7 @@ public void findActionWithLazyDetails() { 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 Long actionId = assignDistributionSet(testDs, testTarget).getActions().get(0); final Action action = deploymentManagement.findActionWithDetails(actionId); assertThat(action.getDistributionSet()).as("DistributionSet in action").isNotNull(); @@ -110,8 +107,8 @@ public void findActionsWithStatusCountByTarget() { 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)); + final Action action = deploymentManagement + .findActionWithDetails(assignDistributionSet(testDs, testTarget).getActions().get(0)); // save 2 action status actionStatusRepository.save(new JpaActionStatus(action, Status.RETRIEVED, System.currentTimeMillis())); actionStatusRepository.save(new JpaActionStatus(action, Status.RUNNING, System.currentTimeMillis())); @@ -134,7 +131,8 @@ public void assignAndUnassignDistributionSetToTag() { } // not exists assignDS.add(Long.valueOf(100)); - final DistributionSetTag tag = tagManagement.createDistributionSetTag(new JpaDistributionSetTag("Tag1")); + final DistributionSetTag tag = tagManagement + .createDistributionSetTag(entityFactory.tag().create().name("Tag1")); final List assignedDS = distributionSetManagement.assignTag(assignDS, tag); assertThat(assignedDS.size()).as("assigned ds has wrong size").isEqualTo(4); @@ -170,15 +168,15 @@ public void assignAndUnassignDistributionSetToTag() { public void multiAssigmentHistoryOverMultiplePagesResultsInTwoActiveAction() { final DistributionSet cancelDs = testdataFactory.createDistributionSet("Canceled DS", "1.0", - new ArrayList()); + Collections.emptyList()); final DistributionSet cancelDs2 = testdataFactory.createDistributionSet("Canceled DS", "1.2", - new ArrayList()); + Collections.emptyList()); List targets = testdataFactory.createTargets(Constants.MAX_ENTRIES_IN_STATEMENT + 10); - targets = deploymentManagement.assignDistributionSet(cancelDs, targets).getAssignedEntity(); - targets = deploymentManagement.assignDistributionSet(cancelDs2, targets).getAssignedEntity(); + targets = assignDistributionSet(cancelDs, targets).getAssignedEntity(); + targets = assignDistributionSet(cancelDs2, targets).getAssignedEntity(); targetManagement.findAllTargetIds().forEach(targetIdName -> { assertThat(deploymentManagement.findActiveActionsByTarget( @@ -192,35 +190,31 @@ public void multiAssigmentHistoryOverMultiplePagesResultsInTwoActiveAction() { + "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() { - JpaTarget target = new JpaTarget("4712"); + final Action action = prepareFinishedUpdate("4712", "installed", true); + final Target target = action.getTarget(); final DistributionSet dsFirst = testdataFactory.createDistributionSet("", true); - dsFirst.setRequiredMigrationStep(true); final DistributionSet dsSecond = testdataFactory.createDistributionSet("2", true); - final DistributionSet dsInstalled = testdataFactory.createDistributionSet("installed", true); - - ((JpaTargetInfo) target.getTargetInfo()).setInstalledDistributionSet((JpaDistributionSet) dsInstalled); - target = (JpaTarget) targetManagement.createTarget(target); + final DistributionSet dsInstalled = action.getDistributionSet(); // check initial status assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) - .as("target has update status").isEqualTo(TargetUpdateStatus.UNKNOWN); + .as("target has update status").isEqualTo(TargetUpdateStatus.IN_SYNC); // assign the two sets in a row - Action firstAction = assignSet(target, dsFirst); - Action secondAction = assignSet(target, dsSecond); + JpaAction firstAction = assignSet(target, dsFirst); + JpaAction secondAction = assignSet(target, dsSecond); - assertThat(actionRepository.findAll()).as("wrong size of actions").hasSize(2); - assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(2); + assertThat(actionRepository.findAll()).as("wrong size of actions").hasSize(3); + assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(5); // we cancel second -> back to first deploymentManagement.cancelAction(secondAction, targetManagement.findTargetByControllerID(target.getControllerId())); - secondAction = deploymentManagement.findActionWithDetails(secondAction.getId()); + secondAction = (JpaAction) deploymentManagement.findActionWithDetails(secondAction.getId()); // confirm cancellation - secondAction.setStatus(Status.CANCELED); - controllerManagement - .addCancelActionStatus(new JpaActionStatus(secondAction, Status.CANCELED, System.currentTimeMillis())); - assertThat(actionStatusRepository.findAll()).as("wrong size of actions status").hasSize(4); + controllerManagement.addCancelActionStatus( + entityFactory.actionStatus().create(secondAction.getId()).status(Status.CANCELED)); + assertThat(actionStatusRepository.findAll()).as("wrong size of actions status").hasSize(7); assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet()).as("wrong ds") .isEqualTo(dsFirst); assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) @@ -229,12 +223,11 @@ public void manualCancelWithMultipleAssignmentsCancelLastOneFirst() { // we cancel first -> back to installed deploymentManagement.cancelAction(firstAction, targetManagement.findTargetByControllerID(target.getControllerId())); - firstAction = deploymentManagement.findActionWithDetails(firstAction.getId()); + firstAction = (JpaAction) deploymentManagement.findActionWithDetails(firstAction.getId()); // confirm cancellation - firstAction.setStatus(Status.CANCELED); - controllerManagement - .addCancelActionStatus(new JpaActionStatus(firstAction, Status.CANCELED, System.currentTimeMillis())); - assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(6); + controllerManagement.addCancelActionStatus( + entityFactory.actionStatus().create(firstAction.getId()).status(Status.CANCELED)); + assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(9); assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet()) .as("wrong assigned ds").isEqualTo(dsInstalled); assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) @@ -246,35 +239,31 @@ public void manualCancelWithMultipleAssignmentsCancelLastOneFirst() { + "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() { - JpaTarget target = new JpaTarget("4712"); + final Action action = prepareFinishedUpdate("4712", "installed", true); + final Target target = action.getTarget(); final DistributionSet dsFirst = testdataFactory.createDistributionSet("", true); - dsFirst.setRequiredMigrationStep(true); final DistributionSet dsSecond = testdataFactory.createDistributionSet("2", true); - final DistributionSet dsInstalled = testdataFactory.createDistributionSet("installed", true); - - ((JpaTargetInfo) target.getTargetInfo()).setInstalledDistributionSet((JpaDistributionSet) dsInstalled); - target = (JpaTarget) targetManagement.createTarget(target); + final DistributionSet dsInstalled = action.getDistributionSet(); // check initial status assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) - .as("wrong update status").isEqualTo(TargetUpdateStatus.UNKNOWN); + .as("wrong update status").isEqualTo(TargetUpdateStatus.IN_SYNC); // assign the two sets in a row - Action firstAction = assignSet(target, dsFirst); - Action secondAction = assignSet(target, dsSecond); + JpaAction firstAction = assignSet(target, dsFirst); + JpaAction secondAction = assignSet(target, dsSecond); - assertThat(actionRepository.findAll()).as("wrong size of actions").hasSize(2); - assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(2); + assertThat(actionRepository.findAll()).as("wrong size of actions").hasSize(3); + assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(5); // we cancel first -> second is left deploymentManagement.cancelAction(firstAction, targetManagement.findTargetByControllerID(target.getControllerId())); // confirm cancellation - firstAction = deploymentManagement.findActionWithDetails(firstAction.getId()); - firstAction.setStatus(Status.CANCELED); - controllerManagement - .addCancelActionStatus(new JpaActionStatus(firstAction, Status.CANCELED, System.currentTimeMillis())); - assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(4); + firstAction = (JpaAction) deploymentManagement.findActionWithDetails(firstAction.getId()); + controllerManagement.addCancelActionStatus( + entityFactory.actionStatus().create(firstAction.getId()).status(Status.CANCELED)); + assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(7); assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet()) .as("wrong assigned ds").isEqualTo(dsSecond); assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) @@ -283,14 +272,13 @@ public void manualCancelWithMultipleAssignmentsCancelMiddleOneFirst() { // we cancel second -> remain assigned until finished cancellation deploymentManagement.cancelAction(secondAction, targetManagement.findTargetByControllerID(target.getControllerId())); - secondAction = deploymentManagement.findActionWithDetails(secondAction.getId()); - assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(5); + secondAction = (JpaAction) deploymentManagement.findActionWithDetails(secondAction.getId()); + assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(8); assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet()) .as("wrong assigned ds").isEqualTo(dsSecond); // confirm cancellation - secondAction.setStatus(Status.CANCELED); - controllerManagement - .addCancelActionStatus(new JpaActionStatus(secondAction, Status.CANCELED, System.currentTimeMillis())); + controllerManagement.addCancelActionStatus( + entityFactory.actionStatus().create(secondAction.getId()).status(Status.CANCELED)); // cancelled success -> back to dsInstalled assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet()) .as("wrong installed ds").isEqualTo(dsInstalled); @@ -301,26 +289,23 @@ public void manualCancelWithMultipleAssignmentsCancelMiddleOneFirst() { @Test @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 { - - JpaTarget target = new JpaTarget("4712"); - final DistributionSet dsInstalled = testdataFactory.createDistributionSet("installed", true); - ((JpaTargetInfo) target.getTargetInfo()).setInstalledDistributionSet((JpaDistributionSet) dsInstalled); - target = (JpaTarget) targetManagement.createTarget(target); + final Action action = prepareFinishedUpdate("4712", "installed", true); + Target target = action.getTarget(); + final DistributionSet dsInstalled = action.getDistributionSet(); final DistributionSet ds = testdataFactory.createDistributionSet("newDS", true); - ds.setRequiredMigrationStep(true); // verify initial status assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) - .as("wrong target info update status").isEqualTo(TargetUpdateStatus.UNKNOWN); + .as("wrong target info update status").isEqualTo(TargetUpdateStatus.IN_SYNC); Action assigningAction = assignSet(target, ds); // verify assignment - assertThat(actionRepository.findAll()).as("wrong size of action").hasSize(1); - assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(1); + assertThat(actionRepository.findAll()).as("wrong size of action").hasSize(2); + assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(4); - target = (JpaTarget) targetManagement.findTargetByControllerID(target.getControllerId()); + target = targetManagement.findTargetByControllerID(target.getControllerId()); // force quit assignment deploymentManagement.cancelAction(assigningAction, target); @@ -341,24 +326,20 @@ public void forceQuitSetActionToInactive() throws InterruptedException { @Test @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 JpaTarget("4712"); - final DistributionSet dsInstalled = testdataFactory.createDistributionSet("installed", true); - ((JpaTargetInfo) target.getTargetInfo()).setInstalledDistributionSet((JpaDistributionSet) dsInstalled); - target = targetManagement.createTarget(target); + final Action action = prepareFinishedUpdate("4712", "installed", true); + final Target target = action.getTarget(); final DistributionSet ds = testdataFactory.createDistributionSet("newDS", true); - ds.setRequiredMigrationStep(true); // verify initial status assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) - .as("wrong update status").isEqualTo(TargetUpdateStatus.UNKNOWN); + .as("wrong update status").isEqualTo(TargetUpdateStatus.IN_SYNC); final Action assigningAction = assignSet(target, ds); // verify assignment - assertThat(actionRepository.findAll()).as("wrong size of action").hasSize(1); - assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(1); + assertThat(actionRepository.findAll()).as("wrong size of action").hasSize(2); + assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(4); // force quit assignment try { @@ -368,14 +349,14 @@ public void forceQuitNotAllowedThrowsException() { } } - private Action assignSet(final Target target, final DistributionSet ds) { - deploymentManagement.assignDistributionSet(ds.getId(), new String[] { target.getControllerId() }); + private JpaAction assignSet(final Target target, final DistributionSet ds) { + assignDistributionSet(ds.getId(), target.getControllerId()); assertThat( targetManagement.findTargetByControllerID(target.getControllerId()).getTargetInfo().getUpdateStatus()) .as("wrong update status").isEqualTo(TargetUpdateStatus.PENDING); assertThat(targetManagement.findTargetByControllerID(target.getControllerId()).getAssignedDistributionSet()) .as("wrong assigned ds").isEqualTo(ds); - final Action action = actionRepository + final JpaAction action = actionRepository .findByTargetAndDistributionSet(pageReq, (JpaTarget) target, (JpaDistributionSet) ds).getContent() .get(0); assertThat(action).as("action should not be null").isNotNull(); @@ -395,16 +376,15 @@ public void assignDistributionSet2Targets() throws InterruptedException { eventHandlerStub.setExpectedNumberOfEvents(20); final String myCtrlIDPref = "myCtrlID"; - final Iterable savedNakedTargets = targetManagement - .createTargets(testdataFactory.generateTargets(10, myCtrlIDPref, "first description")); + final Iterable savedNakedTargets = testdataFactory.createTargets(10, myCtrlIDPref, "first description"); final String myDeployedCtrlIDPref = "myDeployedCtrlID"; - List savedDeployedTargets = targetManagement - .createTargets(testdataFactory.generateTargets(20, myDeployedCtrlIDPref, "first description")); + List savedDeployedTargets = testdataFactory.createTargets(20, myDeployedCtrlIDPref, + "first description"); final DistributionSet ds = testdataFactory.createDistributionSet(""); - deploymentManagement.assignDistributionSet(ds, savedDeployedTargets); + assignDistributionSet(ds, savedDeployedTargets); // verify that one Action for each assignDistributionSet assertThat(actionRepository.findAll(pageReq).getNumberOfElements()).as("wrong size of actions").isEqualTo(20); @@ -450,18 +430,15 @@ public void failDistributionSetAssigmentThatIsNotComplete() throws InterruptedEx final List targets = testdataFactory.createTargets(10); - final SoftwareModule ah = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); - final SoftwareModule jvm = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(runtimeType, "oracle-jre", "1.7.2", null, "")); - final SoftwareModule os = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(osType, "poky", "3.0.2", null, "")); + final SoftwareModule ah = testdataFactory.createSoftwareModuleApp(); + final SoftwareModule os = testdataFactory.createSoftwareModuleOs(); - final DistributionSet incomplete = distributionSetManagement.createDistributionSet( - new JpaDistributionSet("incomplete", "v1", "", standardDsType, Lists.newArrayList(ah, jvm))); + final DistributionSet incomplete = distributionSetManagement + .createDistributionSet(entityFactory.distributionSet().create().name("incomplete").version("v1") + .type(standardDsType).modules(Lists.newArrayList(ah.getId()))); try { - deploymentManagement.assignDistributionSet(incomplete, targets); + assignDistributionSet(incomplete, targets); fail("expected IncompleteDistributionSetException"); } catch (final IncompleteDistributionSetException ex) { } @@ -471,13 +448,13 @@ public void failDistributionSetAssigmentThatIsNotComplete() throws InterruptedEx final List events = eventHandlerStub.getEvents(5, TimeUnit.SECONDS); assertThat(events).as("events should be empty").isEmpty(); - incomplete.addModule(os); - final DistributionSet nowComplete = distributionSetManagement.updateDistributionSet(incomplete); + final DistributionSet nowComplete = distributionSetManagement.assignSoftwareModules(incomplete.getId(), + Sets.newHashSet(os.getId())); eventHandlerStub.setExpectedNumberOfEvents(10); - assertThat(deploymentManagement.assignDistributionSet(nowComplete, targets).getAssigned()) - .as("assign ds doesn't work").isEqualTo(10); + assertThat(assignDistributionSet(nowComplete, targets).getAssigned()).as("assign ds doesn't work") + .isEqualTo(10); assertTargetAssignDistributionSetEvents(targets, nowComplete, eventHandlerStub.getEvents(15, TimeUnit.SECONDS)); } @@ -590,8 +567,10 @@ public void assignDistributionSetAndAddFinishedActionStatus() { .as("wrong target info update status").isEqualTo(TargetUpdateStatus.PENDING); } - final List updatedTsDsA = sendUpdateActionStatusToTargets(dsA, deployResWithDsA.getDeployedTargets(), - Status.FINISHED, new String[] { "alles gut" }); + final List updatedTsDsA = testdataFactory + .sendUpdateActionStatusToTargets(deployResWithDsA.getDeployedTargets(), Status.FINISHED, + Collections.singletonList("alles gut")) + .stream().map(action -> action.getTarget()).collect(Collectors.toList()); // verify, that dsA is deployed correctly assertThat(updatedTsDsA).as("ds is not deployed correctly").isEqualTo(deployResWithDsA.getDeployedTargets()); @@ -609,8 +588,8 @@ public void assignDistributionSetAndAddFinishedActionStatus() { // remove updActB from // activeActions, add a corresponding cancelAction and another // UpdateAction for dsA - final Iterable deployed2DS = deploymentManagement - .assignDistributionSet(dsA, deployResWithDsB.getDeployedTargets()).getAssignedEntity(); + final Iterable deployed2DS = assignDistributionSet(dsA, deployResWithDsB.getDeployedTargets()) + .getAssignedEntity(); actionRepository.findByDistributionSet(pageRequest, dsA).getContent().get(1); // get final updated version of targets @@ -666,7 +645,7 @@ public void deleteDistributionSet() { distributionSetManagement.deleteDistributionSet(ds.getId()); final DistributionSet foundDS = distributionSetManagement.findDistributionSetById(ds.getId()); assertThat(foundDS).as("founded should not be null").isNotNull(); - assertThat(foundDS.isDeleted()).as("founded ds should be deleted").isTrue(); + assertThat(foundDS.isDeleted()).as("found ds should be deleted").isTrue(); } // verify that deleted attribute is used correctly @@ -678,8 +657,8 @@ public void deleteDistributionSet() { assertThat(allFoundDS).as("wrong size of founded ds").hasSize(noOfDistributionSets); for (final DistributionSet ds : deploymentResult.getDistributionSets()) { - sendUpdateActionStatusToTargets(ds, deploymentResult.getDeployedTargets(), Status.FINISHED, - "blabla alles gut"); + testdataFactory.sendUpdateActionStatusToTargets(deploymentResult.getDeployedTargets(), Status.FINISHED, + Collections.singletonList("blabla alles gut")); } // try to delete again distributionSetManagement.deleteDistributionSet(deploymentResult.getDistributionSetIDs() @@ -713,8 +692,8 @@ public void deletesTargetsAndVerifyCascadeDeletes() { deployedTargetPrefix, noOfDeployedTargets, noOfDistributionSets, "myTestDS"); for (final DistributionSet ds : deploymentResult.getDistributionSets()) { - sendUpdateActionStatusToTargets(ds, deploymentResult.getDeployedTargets(), Status.FINISHED, - "blabla alles gut"); + testdataFactory.sendUpdateActionStatusToTargets(deploymentResult.getDeployedTargets(), Status.FINISHED, + Collections.singletonList("blabla alles gut")); } assertThat(targetManagement.countTargetsAll()).as("size of targets is wrong").isNotZero(); @@ -728,47 +707,17 @@ public void deletesTargetsAndVerifyCascadeDeletes() { assertThat(actionStatusRepository.count()).as("size of action status is wrong").isZero(); } - 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((JpaTarget) t); - for (final Action action : findByTarget) { - result.add(sendUpdateActionStatusToTarget(status, action, t, msgs)); - } - } - return result; - } - - private Target sendUpdateActionStatusToTarget(final Status status, final Action updActA, final Target t, - final String... msgs) { - updActA.setStatus(status); - - 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); - return targetManagement.findTargetByControllerID(t.getControllerId()); - } - @Test @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 = testdataFactory.createDistributionSet("a"); final DistributionSet dsB = testdataFactory.createDistributionSet("b"); - Target targ = targetManagement.createTarget(testdataFactory.generateTarget("target-id-A", "first description")); - - List targs = new ArrayList<>(); - targs.add(targ); + List targs = Lists.newArrayList(testdataFactory.createTarget("target-id-A")); // doing the assignment - targs = deploymentManagement.assignDistributionSet(dsA, targs).getAssignedEntity(); - targ = targetManagement.findTargetByControllerID(targs.iterator().next().getControllerId()); + targs = assignDistributionSet(dsA, targs).getAssignedEntity(); + Target targ = targetManagement.findTargetByControllerID(targs.iterator().next().getControllerId()); // checking the revisions of the created entities // verifying that the revision of the object and the revision within the @@ -789,11 +738,8 @@ public void alternatingAssignmentAndAddUpdateActionStatus() { .as("Installed distribution set of action should be null").isNotNull(); final Page updAct = actionRepository.findByDistributionSet(pageReq, (JpaDistributionSet) dsA); - final Action action = updAct.getContent().get(0); - action.setStatus(Status.FINISHED); - final ActionStatus statusMessage = new JpaActionStatus((JpaAction) action, Status.FINISHED, - System.currentTimeMillis(), ""); - controllerManagament.addUpdateActionStatus(statusMessage); + controllerManagament.addUpdateActionStatus( + entityFactory.actionStatus().create(updAct.getContent().get(0).getId()).status(Status.FINISHED)); targ = targetManagement.findTargetByControllerID(targ.getControllerId()); @@ -805,8 +751,7 @@ public void alternatingAssignmentAndAddUpdateActionStatus() { assertEquals("wrong assigned ds", dsA, targ.getAssignedDistributionSet()); assertEquals("wrong installed ds", dsA, targ.getTargetInfo().getInstalledDistributionSet()); - targs = deploymentManagement.assignDistributionSet(dsB.getId(), new String[] { "target-id-A" }) - .getAssignedEntity(); + targs = assignDistributionSet(dsB.getId(), "target-id-A").getAssignedEntity(); targ = targs.iterator().next(); @@ -828,15 +773,12 @@ public void alternatingAssignmentAndAddUpdateActionStatus() { public void checkThatDsRevisionsIsNotChangedWithTargetAssignment() { final DistributionSet dsA = testdataFactory.createDistributionSet("a"); testdataFactory.createDistributionSet("b"); - Target targ = targetManagement.createTarget(testdataFactory.generateTarget("target-id-A", "first description")); + final Target targ = testdataFactory.createTarget("target-id-A"); assertThat(dsA.getOptLockRevision()).as("lock revision is wrong").isEqualTo( distributionSetManagement.findDistributionSetByIdWithDetails(dsA.getId()).getOptLockRevision()); - final List targs = new ArrayList<>(); - targs.add(targ); - final Iterable savedTargs = deploymentManagement.assignDistributionSet(dsA, targs).getAssignedEntity(); - targ = savedTargs.iterator().next(); + assignDistributionSet(dsA, Lists.newArrayList(targ)); assertThat(dsA.getOptLockRevision()).as("lock revision is wrong").isEqualTo( distributionSetManagement.findDistributionSetByIdWithDetails(dsA.getId()).getOptLockRevision()); @@ -846,12 +788,13 @@ public void checkThatDsRevisionsIsNotChangedWithTargetAssignment() { @Description("Tests the switch from a soft to hard update by API") public void forceSoftAction() { // prepare - final Target target = targetManagement.createTarget(new JpaTarget("knownControllerId")); + final Target target = testdataFactory.createTarget("knownControllerId"); final DistributionSet ds = testdataFactory.createDistributionSet("a"); // assign ds to create an action final DistributionSetAssignmentResult assignDistributionSet = deploymentManagement.assignDistributionSet( ds.getId(), ActionType.SOFT, - org.eclipse.hawkbit.repository.model.RepositoryModelConstants.NO_FORCE_TIME, target.getControllerId()); + org.eclipse.hawkbit.repository.model.RepositoryModelConstants.NO_FORCE_TIME, + Lists.newArrayList(target.getControllerId())); final Action action = deploymentManagement.findActionWithDetails(assignDistributionSet.getActions().get(0)); // verify preparation Action findAction = deploymentManagement.findAction(action.getId()); @@ -869,12 +812,13 @@ public void forceSoftAction() { @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 JpaTarget("knownControllerId")); + final Target target = testdataFactory.createTarget("knownControllerId"); final DistributionSet ds = testdataFactory.createDistributionSet("a"); // assign ds to create an action final DistributionSetAssignmentResult assignDistributionSet = deploymentManagement.assignDistributionSet( ds.getId(), ActionType.FORCED, - org.eclipse.hawkbit.repository.model.RepositoryModelConstants.NO_FORCE_TIME, target.getControllerId()); + org.eclipse.hawkbit.repository.model.RepositoryModelConstants.NO_FORCE_TIME, + Lists.newArrayList(target.getControllerId())); final Action action = deploymentManagement.findActionWithDetails(assignDistributionSet.getActions().get(0)); // verify perparation Action findAction = deploymentManagement.findAction(action.getId()); @@ -916,11 +860,11 @@ public void forceAlreadyForcedActionNothingChanges() { private DeploymentResult prepareComplexRepo(final String undeployedTargetPrefix, final int noOfUndeployedTargets, final String deployedTargetPrefix, final int noOfDeployedTargets, final int noOfDistributionSets, final String distributionSetPrefix) { - final Iterable nakedTargets = targetManagement.createTargets( - testdataFactory.generateTargets(noOfUndeployedTargets, undeployedTargetPrefix, "first description")); + final Iterable nakedTargets = testdataFactory.createTargets(noOfUndeployedTargets, + undeployedTargetPrefix, "first description"); - List deployedTargets = targetManagement.createTargets( - testdataFactory.generateTargets(noOfDeployedTargets, deployedTargetPrefix, "first description")); + List deployedTargets = testdataFactory.createTargets(noOfDeployedTargets, deployedTargetPrefix, + "first description"); // creating 10 DistributionSets final Collection dsList = testdataFactory.createDistributionSets(distributionSetPrefix, @@ -931,7 +875,7 @@ private DeploymentResult prepareComplexRepo(final String undeployedTargetPrefix, // assigning all DistributionSet to the Target in the list // deployedTargets for (final DistributionSet ds : dsList) { - deployedTargets = deploymentManagement.assignDistributionSet(ds, deployedTargets).getAssignedEntity(); + deployedTargets = assignDistributionSet(ds, deployedTargets).getAssignedEntity(); } final DeploymentResult deploymentResult = new DeploymentResult(deployedTargets, nakedTargets, dsList, @@ -962,10 +906,6 @@ private void assertTargetAssignDistributionSetEvents(final List targets, } } - /** - * - * - */ private class DeploymentResult { final List deployedTargetIDs = new ArrayList<>(); final List undeployedTargetIDs = new ArrayList<>(); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DistributionSetManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DistributionSetManagementTest.java index c5b730beef..ad91ba3788 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DistributionSetManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DistributionSetManagementTest.java @@ -13,38 +13,25 @@ import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.Iterator; import java.util.List; +import java.util.stream.Collectors; import org.eclipse.hawkbit.repository.DistributionSetManagement; -import org.eclipse.hawkbit.repository.exception.DistributionSetTypeUndefinedException; +import org.eclipse.hawkbit.repository.builder.DistributionSetCreate; 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.JpaRollout; -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.DistributionSetAssignmentResult; 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.Rollout; -import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupErrorAction; -import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupErrorCondition; -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.test.util.WithUser; @@ -54,6 +41,7 @@ import org.springframework.data.domain.PageRequest; import com.google.common.collect.Lists; +import com.google.common.collect.Sets; import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; @@ -70,44 +58,41 @@ 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 JpaDistributionSetType("updatableType", "to be deleted", "")); + DistributionSetType updatableType = distributionSetManagement.createDistributionSetType( + entityFactory.distributionSetType().create().key("updatableType").name("to be deleted")); assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes()) .isEmpty(); // add OS - updatableType.addMandatoryModuleType(osType); - updatableType = distributionSetManagement.updateDistributionSetType(updatableType); + updatableType = distributionSetManagement.assignMandatorySoftwareModuleTypes(updatableType.getId(), + Sets.newHashSet(osType.getId())); assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes()) .containsOnly(osType); // add JVM - updatableType.addMandatoryModuleType(runtimeType); - updatableType = distributionSetManagement.updateDistributionSetType(updatableType); + updatableType = distributionSetManagement.assignMandatorySoftwareModuleTypes(updatableType.getId(), + Sets.newHashSet(runtimeType.getId())); assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes()) .containsOnly(osType, runtimeType); // remove OS - updatableType.removeModuleType(osType.getId()); - updatableType = distributionSetManagement.updateDistributionSetType(updatableType); + updatableType = distributionSetManagement.unassignSoftwareModuleType(updatableType.getId(), osType.getId()); assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes()) .containsOnly(runtimeType); } @Test - @Description("Tests the successfull update of used distribution set type meta data hich is in fact allowed.") + @Description("Tests the successfull update of used distribution set type meta data which is in fact allowed.") public void updateAssignedDistributionSetTypeMetaData() { - final DistributionSetType nonUpdatableType = distributionSetManagement - .createDistributionSetType(new JpaDistributionSetType("updatableType", "to be deletd", "")); + final DistributionSetType nonUpdatableType = distributionSetManagement.createDistributionSetType(entityFactory + .distributionSetType().create().key("updatableType").name("to be deleted").colour("test123")); assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes()) .isEmpty(); - distributionSetManagement - .createDistributionSet(new JpaDistributionSet("newtypesoft", "1", "", nonUpdatableType, null)); - - nonUpdatableType.setDescription("a new description"); - nonUpdatableType.setColour("test123"); + distributionSetManagement.createDistributionSet(entityFactory.distributionSet().create().name("newtypesoft") + .version("1").type(nonUpdatableType.getKey())); - distributionSetManagement.updateDistributionSetType(nonUpdatableType); + distributionSetManagement.updateDistributionSetType( + entityFactory.distributionSetType().update(nonUpdatableType.getId()).description("a new description")); assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getDescription()) .isEqualTo("a new description"); @@ -118,17 +103,16 @@ public void updateAssignedDistributionSetTypeMetaData() { @Test @Description("Tests the unsuccessfull update of used distribution set type (module addition).") public void addModuleToAssignedDistributionSetTypeFails() { - final DistributionSetType nonUpdatableType = distributionSetManagement - .createDistributionSetType(new JpaDistributionSetType("updatableType", "to be deletd", "")); + final DistributionSetType nonUpdatableType = distributionSetManagement.createDistributionSetType( + entityFactory.distributionSetType().create().key("updatableType").name("to be deleted")); assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes()) .isEmpty(); - distributionSetManagement - .createDistributionSet(new JpaDistributionSet("newtypesoft", "1", "", nonUpdatableType, null)); - - nonUpdatableType.addMandatoryModuleType(osType); + distributionSetManagement.createDistributionSet(entityFactory.distributionSet().create().name("newtypesoft") + .version("1").type(nonUpdatableType.getKey())); try { - distributionSetManagement.updateDistributionSetType(nonUpdatableType); + distributionSetManagement.assignMandatorySoftwareModuleTypes(nonUpdatableType.getId(), + Sets.newHashSet(osType.getId())); fail("Should not have worked as DS is in use."); } catch (final EntityReadOnlyException e) { @@ -139,19 +123,18 @@ public void addModuleToAssignedDistributionSetTypeFails() { @Test @Description("Tests the unsuccessfull update of used distribution set type (module removal).") public void removeModuleToAssignedDistributionSetTypeFails() { - DistributionSetType nonUpdatableType = distributionSetManagement - .createDistributionSetType(new JpaDistributionSetType("updatableType", "to be deletd", "")); + DistributionSetType nonUpdatableType = distributionSetManagement.createDistributionSetType( + entityFactory.distributionSetType().create().key("updatableType").name("to be deleted")); assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes()) .isEmpty(); - nonUpdatableType.addMandatoryModuleType(osType); - nonUpdatableType = distributionSetManagement.updateDistributionSetType(nonUpdatableType); - distributionSetManagement - .createDistributionSet(new JpaDistributionSet("newtypesoft", "1", "", nonUpdatableType, null)); + nonUpdatableType = distributionSetManagement.assignMandatorySoftwareModuleTypes(nonUpdatableType.getId(), + Sets.newHashSet(osType.getId())); + distributionSetManagement.createDistributionSet(entityFactory.distributionSet().create().name("newtypesoft") + .version("1").type(nonUpdatableType.getKey())); - nonUpdatableType.removeModuleType(osType.getId()); try { - distributionSetManagement.updateDistributionSetType(nonUpdatableType); + distributionSetManagement.unassignSoftwareModuleType(nonUpdatableType.getId(), osType.getId()); fail("Should not have worked as DS is in use."); } catch (final EntityReadOnlyException e) { @@ -162,7 +145,8 @@ public void removeModuleToAssignedDistributionSetTypeFails() { @Description("Tests the successfull deletion of unused (hard delete) distribution set types.") public void deleteUnassignedDistributionSetType() { final JpaDistributionSetType hardDelete = (JpaDistributionSetType) distributionSetManagement - .createDistributionSetType(new JpaDistributionSetType("deleted", "to be deleted", "")); + .createDistributionSetType( + entityFactory.distributionSetType().create().key("delete").name("to be deleted")); assertThat(distributionSetTypeRepository.findAll()).contains(hardDelete); distributionSetManagement.deleteDistributionSetType(hardDelete); @@ -174,11 +158,12 @@ public void deleteUnassignedDistributionSetType() { @Description("Tests the successfull deletion of used (soft delete) distribution set types.") public void deleteAssignedDistributionSetType() { final JpaDistributionSetType softDelete = (JpaDistributionSetType) distributionSetManagement - .createDistributionSetType(new JpaDistributionSetType("softdeleted", "to be deletd", "")); + .createDistributionSetType( + entityFactory.distributionSetType().create().key("softdeleted").name("to be deleted")); assertThat(distributionSetTypeRepository.findAll()).contains(softDelete); - distributionSetManagement - .createDistributionSet(new JpaDistributionSet("newtypesoft", "1", "", softDelete, null)); + distributionSetManagement.createDistributionSet( + entityFactory.distributionSet().create().name("softdeleted").version("1").type(softDelete.getKey())); distributionSetManagement.deleteDistributionSetType(softDelete); assertThat(distributionSetManagement.findDistributionSetTypeByKey("softdeleted").isDeleted()).isEqualTo(true); @@ -201,7 +186,7 @@ public void createDuplicateDistributionSetsFailsWithException() { @Description("Verifies that a DS is of default type if not specified explicitly at creation time.") public void createDistributionSetWithImplicitType() { final DistributionSet set = distributionSetManagement - .createDistributionSet(new JpaDistributionSet("newtypesoft", "1", "", null, null)); + .createDistributionSet(entityFactory.distributionSet().create().name("newtypesoft").version("1")); assertThat(set.getType()).as("Type should be equal to default type of tenant") .isEqualTo(systemManagement.getTenantMetadata().getDefaultDsType()); @@ -212,12 +197,12 @@ public void createDistributionSetWithImplicitType() { @Description("Verifies that multiple DS are of default type if not specified explicitly at creation time.") public void createMultipleDistributionSetsWithImplicitType() { - List sets = new ArrayList<>(); + final List creates = Lists.newArrayListWithExpectedSize(10); for (int i = 0; i < 10; i++) { - sets.add(new JpaDistributionSet("another DS" + i, "X" + i, "", null, null)); + creates.add(entityFactory.distributionSet().create().name("newtypesoft" + i).version("1" + i)); } - sets = distributionSetManagement.createDistributionSets(sets); + final List sets = distributionSetManagement.createDistributionSets(creates); assertThat(sets).as("Type should be equal to default type of tenant").are(new Condition() { @Override @@ -228,20 +213,6 @@ public boolean matches(final DistributionSet value) { } - @Test - @Description("Verifies that a DS entity cannot be used for creation.") - public void createDistributionSetFailsOnExistingEntity() { - final DistributionSet set = distributionSetManagement - .createDistributionSet(new JpaDistributionSet("newtypesoft", "1", "", null, null)); - - try { - distributionSetManagement.createDistributionSet(set); - fail("Should not have worked to create based on a persisted entity."); - } catch (final EntityAlreadyExistsException e) { - - } - } - @Test @Description("Checks that metadata for a distribution set can be created.") public void createDistributionSetMetadata() { @@ -251,8 +222,8 @@ public void createDistributionSetMetadata() { final DistributionSet ds = testdataFactory.createDistributionSet("testDs"); final DistributionSetMetadata metadata = new JpaDistributionSetMetadata(knownKey, ds, knownValue); - final JpaDistributionSetMetadata createdMetadata = (JpaDistributionSetMetadata) distributionSetManagement - .createDistributionSetMetadata(metadata); + final JpaDistributionSetMetadata createdMetadata = (JpaDistributionSetMetadata) createDistributionSetMetadata( + ds.getId(), metadata); assertThat(createdMetadata).isNotNull(); assertThat(createdMetadata.getId().getKey()).isEqualTo(knownKey); @@ -264,67 +235,34 @@ public void createDistributionSetMetadata() { @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 JpaTarget("4711"); - target = targetManagement.createTarget(target); - - SoftwareModule ah2 = new JpaSoftwareModule(appType, "agent-hub2", "1.0.5", null, ""); - SoftwareModule os2 = new JpaSoftwareModule(osType, "poky2", "3.0.3", null, ""); + final Target target = testdataFactory.createTarget(); DistributionSet ds = testdataFactory.createDistributionSet("ds-1"); - ah2 = softwareManagement.createSoftwareModule(ah2); - os2 = softwareManagement.createSoftwareModule(os2); + final SoftwareModule ah2 = testdataFactory.createSoftwareModuleApp(); + final SoftwareModule os2 = testdataFactory.createSoftwareModuleOs(); // update is allowed as it is still not assigned to a target - ds.addModule(ah2); - ds = distributionSetManagement.updateDistributionSet(ds); + ds = distributionSetManagement.assignSoftwareModules(ds.getId(), Sets.newHashSet(ah2.getId())); // assign target - deploymentManagement.assignDistributionSet(ds.getId(), target.getControllerId()); + assignDistributionSet(ds.getId(), target.getControllerId()); ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId()); - // description change is still allowed - ds.setDescription("a different desc"); - ds = distributionSetManagement.updateDistributionSet(ds); - - // description change is still allowed - ds.setName("a new name"); - ds = distributionSetManagement.updateDistributionSet(ds); - - // description change is still allowed - ds.setVersion("a new version"); - ds = distributionSetManagement.updateDistributionSet(ds); - // not allowed as it is assigned now - ds.addModule(os2); try { - ds = distributionSetManagement.updateDistributionSet(ds); - fail("Expected EntityLockedException"); - } catch (final EntityLockedException e) { + ds = distributionSetManagement.assignSoftwareModules(ds.getId(), Sets.newHashSet(os2.getId())); + fail("Expected EntityReadOnlyException"); + } catch (final EntityReadOnlyException e) { } // not allowed as it is assigned now - ds.removeModule(ds.findFirstModuleByType(appType)); - try { - ds = distributionSetManagement.updateDistributionSet(ds); - fail("Expected EntityLockedException"); - } catch (final EntityLockedException e) { - - } - } - - @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 JpaDistributionSet(); - final SoftwareModule module = new JpaSoftwareModule(appType, "agent-hub2", "1.0.5", null, ""); - - // update data try { - testSet.addModule(module); - fail("Should not have worked as DS type is undefined."); - } catch (final DistributionSetTypeUndefinedException e) { + ds = distributionSetManagement.unassignSoftwareModule(ds.getId(), + ds.findFirstModuleByType(appType).getId()); + fail("Expected EntityReadOnlyException"); + } catch (final EntityReadOnlyException e) { } } @@ -332,13 +270,18 @@ public void updateDistributionSetModuleWithUndefinedTypeFails() { @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 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, ""); + final DistributionSet set = distributionSetManagement + .createDistributionSet(entityFactory.distributionSet().create().name("agent-hub2").version("1.0.5") + .type(distributionSetManagement.createDistributionSetType(entityFactory.distributionSetType() + .create().key("test").name("test").mandatory(Lists.newArrayList(osType.getId()))) + .getKey())); + + final SoftwareModule module = softwareManagement.createSoftwareModule( + entityFactory.softwareModule().create().name("agent-hub2").version("1.0.5").type(appType.getKey())); // update data try { - set.addModule(module); + distributionSetManagement.assignSoftwareModules(set.getId(), Sets.newHashSet(module.getId())); fail("Should not have worked as module type is not in DS type."); } catch (final UnsupportedSoftwareModuleForThisDistributionSetException e) { @@ -349,40 +292,30 @@ public void updateDistributionSetUnsupportedModuleFails() { @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 JpaTarget("4711"); - target = targetManagement.createTarget(target); - - SoftwareModule os2 = new JpaSoftwareModule(osType, "poky2", "3.0.3", null, ""); - final SoftwareModule app2 = new JpaSoftwareModule(appType, "app2", "3.0.3", null, ""); - + final Target target = testdataFactory.createTarget(); DistributionSet ds = testdataFactory.createDistributionSet(""); - - os2 = softwareManagement.createSoftwareModule(os2); + final SoftwareModule os = testdataFactory.createSoftwareModuleOs(); // update data // legal update of module addition - ds.addModule(os2); - distributionSetManagement.updateDistributionSet(ds); + distributionSetManagement.assignSoftwareModules(ds.getId(), Sets.newHashSet(os.getId())); ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId()); - assertThat(ds.findFirstModuleByType(osType)).isEqualTo(os2); + assertThat(ds.findFirstModuleByType(osType)).isEqualTo(os); // legal update of module removal - ds.removeModule(ds.findFirstModuleByType(appType)); - distributionSetManagement.updateDistributionSet(ds); + distributionSetManagement.unassignSoftwareModule(ds.getId(), ds.findFirstModuleByType(appType).getId()); ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId()); assertThat(ds.findFirstModuleByType(appType)).isNull(); // Update description - ds.setDescription("a new description"); - distributionSetManagement.updateDistributionSet(ds); + distributionSetManagement + .updateDistributionSet(entityFactory.distributionSet().update(ds.getId()).name("a new name") + .description("a new description").version("a new version").requiredMigrationStep(true)); ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId()); assertThat(ds.getDescription()).isEqualTo("a new description"); - - // Update name - ds.setName("a new name"); - distributionSetManagement.updateDistributionSet(ds); - ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId()); assertThat(ds.getName()).isEqualTo("a new name"); + assertThat(ds.getVersion()).isEqualTo("a new version"); + assertThat(ds.isRequiredMigrationStep()).isTrue(); } @Test @@ -399,22 +332,16 @@ public void updateDistributionSetMetadata() throws InterruptedException { assertThat(ds.getOptLockRevision()).isEqualTo(1); // create an DS meta data entry - final DistributionSetMetadata dsMetadata = distributionSetManagement - .createDistributionSetMetadata(new JpaDistributionSetMetadata(knownKey, ds, knownValue)); + createDistributionSetMetadata(ds.getId(), new JpaDistributionSetMetadata(knownKey, ds, knownValue)); DistributionSet changedLockRevisionDS = distributionSetManagement.findDistributionSetById(ds.getId()); assertThat(changedLockRevisionDS.getOptLockRevision()).isEqualTo(2); - // modifying the meta data value - dsMetadata.setValue(knownUpdateValue); - dsMetadata.setKey(knownKey); - ((JpaDistributionSetMetadata) dsMetadata).setDistributionSet(changedLockRevisionDS); - Thread.sleep(100); // update the DS metadata final JpaDistributionSetMetadata updated = (JpaDistributionSetMetadata) distributionSetManagement - .updateDistributionSetMetadata(dsMetadata); + .updateDistributionSetMetadata(ds.getId(), entityFactory.generateMetadata(knownKey, knownUpdateValue)); // we are updating the sw meta data so also modifying the base software // module so opt lock // revision must be three @@ -435,8 +362,7 @@ public void findDistributionSetsAllOrderedByLinkTarget() { final List buildDistributionSets = testdataFactory.createDistributionSets("dsOrder", 10); - final List buildTargetFixtures = targetManagement - .createTargets(testdataFactory.generateTargets(5, "tOrder", "someDesc")); + final List buildTargetFixtures = testdataFactory.createTargets(5, "tOrder", "someDesc"); final Iterator dsIterator = buildDistributionSets.iterator(); final Iterator tIterator = buildTargetFixtures.iterator(); @@ -448,14 +374,13 @@ public void findDistributionSetsAllOrderedByLinkTarget() { final Target tSecond = tIterator.next(); // set assigned - deploymentManagement.assignDistributionSet(dsSecond.getId(), tSecond.getControllerId()); - deploymentManagement.assignDistributionSet(dsThree.getId(), tFirst.getControllerId()); + assignDistributionSet(dsSecond.getId(), tSecond.getControllerId()); + assignDistributionSet(dsThree.getId(), tFirst.getControllerId()); // set installed - final ArrayList installedDSSecond = new ArrayList<>(); - installedDSSecond.add(tSecond); - sendUpdateActionStatusToTargets(dsSecond, installedDSSecond, Status.FINISHED, "some message"); + testdataFactory.sendUpdateActionStatusToTargets(Collections.singleton(tSecond), Status.FINISHED, + Lists.newArrayList("some message")); - deploymentManagement.assignDistributionSet(dsFour.getId(), tSecond.getControllerId()); + assignDistributionSet(dsFour.getId(), tSecond.getControllerId()); final DistributionSetFilterBuilder distributionSetFilterBuilder = new DistributionSetFilterBuilder() .setIsDeleted(false).setIsComplete(true).setSelectDSWithNoTag(Boolean.FALSE); @@ -479,28 +404,32 @@ public void findDistributionSetsAllOrderedByLinkTarget() { @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 JpaDistributionSetTag("DistributionSetTag-A")); + .createDistributionSetTag(entityFactory.tag().create().name("DistributionSetTag-A")); final DistributionSetTag dsTagB = tagManagement - .createDistributionSetTag(new JpaDistributionSetTag("DistributionSetTag-B")); + .createDistributionSetTag(entityFactory.tag().create().name("DistributionSetTag-B")); final DistributionSetTag dsTagC = tagManagement - .createDistributionSetTag(new JpaDistributionSetTag("DistributionSetTag-C")); - final DistributionSetTag dsTagD = tagManagement - .createDistributionSetTag(new JpaDistributionSetTag("DistributionSetTag-D")); + .createDistributionSetTag(entityFactory.tag().create().name("DistributionSetTag-C")); + tagManagement.createDistributionSetTag(entityFactory.tag().create().name("DistributionSetTag-D")); Collection ds100Group1 = testdataFactory.createDistributionSets("", 100); Collection ds100Group2 = testdataFactory.createDistributionSets("test2", 100); DistributionSet dsDeleted = testdataFactory.createDistributionSet("deleted"); - final DistributionSet dsInComplete = distributionSetManagement - .createDistributionSet(new JpaDistributionSet("notcomplete", "1", "", standardDsType, null)); + final DistributionSet dsInComplete = distributionSetManagement.createDistributionSet(entityFactory + .distributionSet().create().name("notcomplete").version("1").type(standardDsType.getKey())); - final DistributionSetType newType = distributionSetManagement.createDistributionSetType( - new JpaDistributionSetType("foo", "bar", "test").addMandatoryModuleType(osType) - .addOptionalModuleType(appType).addOptionalModuleType(runtimeType)); + DistributionSetType newType = distributionSetManagement.createDistributionSetType( + entityFactory.distributionSetType().create().key("foo").name("bar").description("test")); - final DistributionSet dsNewType = distributionSetManagement - .createDistributionSet(new JpaDistributionSet("newtype", "1", "", newType, dsDeleted.getModules())); + distributionSetManagement.assignMandatorySoftwareModuleTypes(newType.getId(), + Lists.newArrayList(osType.getId())); + newType = distributionSetManagement.assignOptionalSoftwareModuleTypes(newType.getId(), + Lists.newArrayList(appType.getId(), runtimeType.getId())); - deploymentManagement.assignDistributionSet(dsDeleted, Lists.newArrayList(testdataFactory.createTargets(5))); + final DistributionSet dsNewType = distributionSetManagement.createDistributionSet( + entityFactory.distributionSet().create().name("newtype").version("1").type(newType.getKey()).modules( + dsDeleted.getModules().stream().map(SoftwareModule::getId).collect(Collectors.toList()))); + + assignDistributionSet(dsDeleted, Lists.newArrayList(testdataFactory.createTargets(5))); distributionSetManagement.deleteDistributionSet(dsDeleted); dsDeleted = distributionSetManagement.findDistributionSetById(dsDeleted.getId()); @@ -515,7 +444,7 @@ public void searchDistributionSetsOnFilters() { assertThat(distributionSetRepository.findAll()).hasSize(203); // Find all - List expected = new ArrayList(); + List expected = Lists.newArrayListWithExpectedSize(203); expected.addAll(ds100Group1); expected.addAll(ds100Group2); expected.add(dsDeleted); @@ -539,7 +468,7 @@ public void searchDistributionSetsOnFilters() { .hasSize(202); // search for completed - expected = new ArrayList(); + expected = new ArrayList<>(); expected.addAll(ds100Group1); expected.addAll(ds100Group2); expected.add(dsDeleted); @@ -551,7 +480,7 @@ public void searchDistributionSetsOnFilters() { .containsOnly(expected.toArray(new DistributionSet[0])); distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.FALSE); - expected = new ArrayList(); + expected = new ArrayList<>(); expected.add(dsInComplete); assertThat(distributionSetManagement .findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(1) @@ -604,7 +533,7 @@ public void searchDistributionSetsOnFilters() { .findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(0); // combine deleted and complete - expected = new ArrayList(); + expected = new ArrayList<>(); expected.addAll(ds100Group1); expected.addAll(ds100Group2); expected.add(dsNewType); @@ -615,14 +544,14 @@ public void searchDistributionSetsOnFilters() { .findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(201) .containsOnly(expected.toArray(new DistributionSet[0])); - expected = new ArrayList(); + expected = new ArrayList<>(); expected.add(dsInComplete); distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.FALSE); assertThat(distributionSetManagement .findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(1) .containsOnly(expected.toArray(new DistributionSet[0])); - expected = new ArrayList(); + expected = new ArrayList<>(); expected.add(dsDeleted); distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE) .setIsDeleted(Boolean.TRUE); @@ -710,18 +639,6 @@ private DistributionSetFilterBuilder getDistributionSetFilterBuilder() { return new DistributionSetFilterBuilder(); } - 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((JpaTarget) t); - for (final Action action : findByTarget) { - result.add(sendUpdateActionStatusToTarget(status, action, t, msgs)); - } - } - return result; - } - @Test @Description("Simple DS load without the related data that should be loaded lazy.") public void findDistributionSetsWithoutLazy() { @@ -759,16 +676,14 @@ public void findAllDistributionSetMetadataByDsId() { for (int index = 0; index < 10; index++) { - ds1 = distributionSetManagement - .createDistributionSetMetadata(new JpaDistributionSetMetadata("key" + index, ds1, "value" + index)) - .getDistributionSet(); + ds1 = createDistributionSetMetadata(ds1.getId(), + new JpaDistributionSetMetadata("key" + index, ds1, "value" + index)).getDistributionSet(); } for (int index = 0; index < 20; index++) { - ds2 = distributionSetManagement - .createDistributionSetMetadata(new JpaDistributionSetMetadata("key" + index, ds2, "value" + index)) - .getDistributionSet(); + ds2 = createDistributionSetMetadata(ds2.getId(), + new JpaDistributionSetMetadata("key" + index, ds2, "value" + index)).getDistributionSet(); } final Page metadataOfDs1 = distributionSetManagement @@ -799,11 +714,8 @@ public void deleteAssignedDistributionSet() { // create assigned DS dsToTargetAssigned = distributionSetManagement.findDistributionSetByNameAndVersion(dsToTargetAssigned.getName(), dsToTargetAssigned.getVersion()); - final Target target = new JpaTarget("4712"); - final Target savedTarget = targetManagement.createTarget(target); - final List toAssign = new ArrayList<>(); - toAssign.add(savedTarget); - deploymentManagement.assignDistributionSet(dsToTargetAssigned, toAssign); + final Target savedTarget = testdataFactory.createTarget(); + assignDistributionSet(dsToTargetAssigned.getId(), savedTarget.getControllerId()); // create assigned rollout createRolloutByVariables("test", "test", 5, "name==*", dsToRolloutAssigned, "50", "5"); @@ -827,47 +739,15 @@ public void verifyDistributionSetAssignmentResultNotContainsAlreadyAssignedTarge // create assigned DS dsToTargetAssigned = distributionSetManagement.findDistributionSetByNameAndVersion(dsToTargetAssigned.getName(), dsToTargetAssigned.getVersion()); - final Target target = new JpaTarget("4712"); - final Target savedTarget = targetManagement.createTarget(target); - final List toAssign = Lists.newArrayList(savedTarget); - DistributionSetAssignmentResult assignmentResult = deploymentManagement - .assignDistributionSet(dsToTargetAssigned, toAssign); + final Target savedTarget = testdataFactory.createTarget(); + DistributionSetAssignmentResult assignmentResult = assignDistributionSet(dsToTargetAssigned.getId(), + savedTarget.getControllerId()); assertThat(assignmentResult.getAssignedEntity()).hasSize(1); - assignmentResult = deploymentManagement.assignDistributionSet(dsToTargetAssigned, toAssign); + assignmentResult = assignDistributionSet(dsToTargetAssigned.getId(), savedTarget.getControllerId()); assertThat(assignmentResult.getAssignedEntity()).hasSize(0); assertThat(distributionSetRepository.findAll()).hasSize(1); } - 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 RolloutGroupConditionBuilder() - .successCondition(RolloutGroupSuccessCondition.THRESHOLD, successCondition) - .errorCondition(RolloutGroupErrorCondition.THRESHOLD, errorCondition) - .errorAction(RolloutGroupErrorAction.PAUSE, null).build(); - final Rollout rolloutToCreate = new JpaRollout(); - rolloutToCreate.setName(rolloutName); - rolloutToCreate.setDescription(rolloutDescription); - rolloutToCreate.setTargetFilterQuery(filterQuery); - rolloutToCreate.setDistributionSet(distributionSet); - return rolloutManagement.createRollout(rolloutToCreate, groupSize, conditions); - } - - private Target sendUpdateActionStatusToTarget(final Status status, final Action updActA, final Target t, - final String... msgs) { - updActA.setStatus(status); - - 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); - return targetManagement.findTargetByControllerID(t.getControllerId()); - } - } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ReportManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ReportManagementTest.java index 0d93383041..2860c95b3e 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ReportManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ReportManagementTest.java @@ -14,20 +14,17 @@ import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; -import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; +import java.util.Collections; import java.util.List; import java.util.stream.Collectors; 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.DistributionSetAssignmentResult; import org.eclipse.hawkbit.repository.model.SoftwareModule; @@ -59,6 +56,8 @@ @Stories("Report Management") public class ReportManagementTest extends AbstractJpaIntegrationTest { + private static final String TEST_MESSAGE = "some message"; + @Autowired private ReportManagement reportManagement; @@ -86,7 +85,7 @@ public void targetsCreatedOverPeriod() { for (int month = 0; month < maxMonthBackAmountCreateTargets; month++) { dynamicDateTimeProvider.nowMinusMonths(month); - targetManagement.createTarget(new JpaTarget("t" + month)); + testdataFactory.createTarget("t" + month); } final LocalDateTime to = LocalDateTime.now(); @@ -108,7 +107,7 @@ public void targetsCreatedOverPeriod() { // check cache evict for (int month = 0; month < maxMonthBackAmountCreateTargets; month++) { dynamicDateTimeProvider.nowMinusMonths(month); - targetManagement.createTarget(new JpaTarget("t2" + month)); + testdataFactory.createTarget("t2" + month); } targetsCreatedOverPeriod = reportManagement.targetsCreatedOverPeriod(DateTypes.perMonth(), from, to); for (final DataReportSeriesItem reportItem : targetsCreatedOverPeriod.getData()) { @@ -137,8 +136,8 @@ public void targetsFeedbackOverPeriod() { for (int month = 0; month < maxMonthBackAmountCreateTargets; month++) { dynamicDateTimeProvider.nowMinusMonths(month); - final Target createTarget = targetManagement.createTarget(new JpaTarget("t" + month)); - final DistributionSetAssignmentResult result = deploymentManagement.assignDistributionSet(distributionSet, + final Target createTarget = testdataFactory.createTarget("t" + month); + final DistributionSetAssignmentResult result = assignDistributionSet(distributionSet, Lists.newArrayList(createTarget)); controllerManagament.registerRetrieved( deploymentManagement.findActionWithDetails(result.getActions().get(0)), @@ -159,8 +158,8 @@ public void targetsFeedbackOverPeriod() { // check cache evict for (int month = 0; month < maxMonthBackAmountCreateTargets; month++) { dynamicDateTimeProvider.nowMinusMonths(month); - final Target createTarget = targetManagement.createTarget(new JpaTarget("t2" + month)); - final DistributionSetAssignmentResult result = deploymentManagement.assignDistributionSet(distributionSet, + final Target createTarget = testdataFactory.createTarget("t2" + month); + final DistributionSetAssignmentResult result = assignDistributionSet(distributionSet, Lists.newArrayList(createTarget)); controllerManagament.registerRetrieved( deploymentManagement.findActionWithDetails(result.getActions().get(0)), @@ -176,43 +175,40 @@ public void targetsFeedbackOverPeriod() { @Test @Description("Tests correct statistics calculation including a correct cache evict.") public void distributionUsageInstalled() { - 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 Target knownTarget1 = testdataFactory.createTarget("t1"); + final Target knownTarget2 = testdataFactory.createTarget("t2"); + final Target knownTarget3 = testdataFactory.createTarget("t3"); + final Target knownTarget4 = testdataFactory.createTarget("t4"); + final Target knownTarget5 = testdataFactory.createTarget("t5"); 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(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))); + final DistributionSet distributionSet1 = testdataFactory.createDistributionSet("ds1", "0.0.0", standardDsType, + Lists.newArrayList(os, jvm, ah)); + final DistributionSet distributionSet11 = testdataFactory.createDistributionSet("ds1", "0.0.1", standardDsType, + Lists.newArrayList(os, jvm, ah)); + final DistributionSet distributionSet2 = testdataFactory.createDistributionSet("ds2", "0.0.2", standardDsType, + Lists.newArrayList(os, jvm, ah)); + final DistributionSet distributionSet3 = testdataFactory.createDistributionSet("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()); - deploymentManagement.assignDistributionSet(distributionSet1.getId(), knownTarget2.getControllerId()); - deploymentManagement.assignDistributionSet(distributionSet11.getId(), knownTarget3.getControllerId()); + assignDistributionSet(distributionSet1.getId(), knownTarget1.getControllerId()); + assignDistributionSet(distributionSet1.getId(), knownTarget2.getControllerId()); + assignDistributionSet(distributionSet11.getId(), knownTarget3.getControllerId()); // ds2=[target4] - deploymentManagement.assignDistributionSet(distributionSet2.getId(), knownTarget4.getControllerId()); + assignDistributionSet(distributionSet2.getId(), knownTarget4.getControllerId()); // ds3=[target5] --> ONLY ASSIGNED AND NOT INSTALLED - deploymentManagement.assignDistributionSet(distributionSet3.getId(), knownTarget5.getControllerId()); + assignDistributionSet(distributionSet3.getId(), knownTarget5.getControllerId()); // set installed status - sendUpdateActionStatusToTargets(distributionSet1, Lists.newArrayList(knownTarget1, knownTarget2), - Status.FINISHED, "some message"); - sendUpdateActionStatusToTargets(distributionSet11, Lists.newArrayList(knownTarget3), Status.FINISHED, - "some message"); - sendUpdateActionStatusToTargets(distributionSet2, Lists.newArrayList(knownTarget4), Status.FINISHED, - "some message"); + testdataFactory.sendUpdateActionStatusToTargets( + Lists.newArrayList(knownTarget1, knownTarget2, knownTarget3, knownTarget4), Status.FINISHED, + Collections.singletonList(TEST_MESSAGE)); List> distributionUsage = reportManagement.distributionUsageInstalled(100); @@ -249,10 +245,10 @@ public void distributionUsageInstalled() { } // Test cache evict - final Target knownTarget6 = targetManagement.createTarget(new JpaTarget("t6")); - deploymentManagement.assignDistributionSet(distributionSet1.getId(), knownTarget6.getControllerId()); - sendUpdateActionStatusToTargets(distributionSet1, Lists.newArrayList(knownTarget6), Status.FINISHED, - "some message"); + final Target knownTarget6 = testdataFactory.createTarget("t6"); + assignDistributionSet(distributionSet1.getId(), knownTarget6.getControllerId()); + testdataFactory.sendUpdateActionStatusToTargets(Lists.newArrayList(knownTarget6), Status.FINISHED, + Collections.singletonList(TEST_MESSAGE)); distributionUsage = reportManagement.distributionUsageInstalled(100); for (final InnerOuterDataReportSeries innerOuterDataReportSeries : distributionUsage) { final DataReportSeriesItem dataReportSeriesItem = innerOuterDataReportSeries.getInnerSeries() @@ -347,32 +343,31 @@ public void targetStatusReport() { @Test @Description("Tests correct statistics calculation including a correct cache evict.") public void topXDistributionUsage() { - - 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 knownTarget1 = testdataFactory.createTarget("t1"); + final Target knownTarget2 = testdataFactory.createTarget("t2"); + final Target knownTarget3 = testdataFactory.createTarget("t3"); + final Target knownTarget4 = testdataFactory.createTarget("t4"); 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(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))); + final DistributionSet distributionSet1 = testdataFactory.createDistributionSet("ds1", "0.0.0", standardDsType, + Lists.newArrayList(os, jvm, ah)); + final DistributionSet distributionSet11 = testdataFactory.createDistributionSet("ds1", "0.0.1", standardDsType, + Lists.newArrayList(os, jvm, ah)); + final DistributionSet distributionSet2 = testdataFactory.createDistributionSet("ds2", "0.0.2", standardDsType, + Lists.newArrayList(os, jvm, ah)); + final DistributionSet distributionSet3 = testdataFactory.createDistributionSet("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()); - deploymentManagement.assignDistributionSet(distributionSet1.getId(), knownTarget2.getControllerId()); - deploymentManagement.assignDistributionSet(distributionSet11.getId(), knownTarget3.getControllerId()); + assignDistributionSet(distributionSet1.getId(), knownTarget1.getControllerId()); + assignDistributionSet(distributionSet1.getId(), knownTarget2.getControllerId()); + assignDistributionSet(distributionSet11.getId(), knownTarget3.getControllerId()); // ds2=[target4] - deploymentManagement.assignDistributionSet(distributionSet2.getId(), knownTarget4.getControllerId()); + assignDistributionSet(distributionSet2.getId(), knownTarget4.getControllerId()); // expect: ds1(0.0.0)=[target1,target2], ds1(0.0.1)=[target3], // ds2=[target4], ds3=[] @@ -415,8 +410,8 @@ public void topXDistributionUsage() { } // test cache evict - final Target knownTarget5 = targetManagement.createTarget(new JpaTarget("t5")); - deploymentManagement.assignDistributionSet(distributionSet1.getId(), knownTarget5.getControllerId()); + final Target knownTarget5 = testdataFactory.createTarget("t5"); + assignDistributionSet(distributionSet1.getId(), knownTarget5.getControllerId()); distributionUsage = reportManagement.distributionUsageAssigned(100); for (final InnerOuterDataReportSeries innerOuterDataReportSeries : distributionUsage) { final DataReportSeriesItem dataReportSeriesItem = innerOuterDataReportSeries.getInnerSeries() @@ -486,7 +481,7 @@ public void targetsCreatedOverPeriodMultiTenancyAware() throws Exception { // create targets for another tenant securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", "anotherTenant"), () -> { for (int index = 0; index < targetCreateAmount; index++) { - targetManagement.createTarget(new JpaTarget("t" + index)); + testdataFactory.createTarget("t" + index); } return null; }); @@ -509,8 +504,7 @@ public void targetsCreatedOverPeriodMultiTenancyAware() throws Exception { private void createTargets(final String prefix, final int amount, final LocalDateTime lastTargetQuery) { for (int index = 0; index < amount; index++) { - final Target target = new JpaTarget(prefix + index); - final JpaTarget createTarget = (JpaTarget) targetManagement.createTarget(target); + final JpaTarget createTarget = (JpaTarget) testdataFactory.createTarget(prefix + index); if (lastTargetQuery != null) { final JpaTargetInfo targetInfo = (JpaTargetInfo) createTarget.getTargetInfo(); targetInfo.setNew(false); @@ -531,42 +525,10 @@ private void createTargetsWithStatus(final String prefix, final long amount, fin } } - 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((JpaTarget) t); - for (final Action action : findByTarget) { - result.add(sendUpdateActionStatusToTarget(status, action, t, msgs)); - } - } - return result; - } - - private Target sendUpdateActionStatusToTarget(final Status status, final Action updActA, final Target t, - final String... msgs) { - updActA.setStatus(status); - - 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); - return targetManagement.findTargetByControllerID(t.getControllerId()); - } - private class DynamicDateTimeProvider implements DateTimeProvider { private Calendar datetime = Calendar.getInstance(); - /* - * (non-Javadoc) - * - * @see org.springframework.data.auditing.DateTimeProvider#getNow() - */ @Override public Calendar getNow() { return datetime; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/RolloutManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/RolloutManagementTest.java index aada8a6ebb..7ce1d6f549 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/RolloutManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/RolloutManagementTest.java @@ -21,12 +21,12 @@ import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.RolloutGroupManagement; import org.eclipse.hawkbit.repository.RolloutManagement; +import org.eclipse.hawkbit.repository.builder.RolloutCreate; +import org.eclipse.hawkbit.repository.builder.RolloutGroupCreate; +import org.eclipse.hawkbit.repository.exception.ConstraintViolationException; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; import org.eclipse.hawkbit.repository.exception.RolloutIllegalStateException; -import org.eclipse.hawkbit.repository.exception.RolloutVerificationException; 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; @@ -116,11 +116,10 @@ public void startRolloutSetFirstGroupAndActionsInRunningStateAndOthersInSchedule .as("group which should be in scheduled state is in " + group.getStatus() + " state")); // verify that the first group actions has been started and are in state // running - final List runningActions = deploymentManagement.findActionsByRolloutAndStatus(createdRollout, - Status.RUNNING); + final List runningActions = findActionsByRolloutAndStatus(createdRollout, Status.RUNNING); assertThat(runningActions).hasSize(amountTargetsForRollout / amountGroups); // the rest targets are only scheduled - assertThat(deploymentManagement.findActionsByRolloutAndStatus(createdRollout, Status.SCHEDULED)) + assertThat(findActionsByRolloutAndStatus(createdRollout, Status.SCHEDULED)) .hasSize(amountTargetsForRollout - (amountTargetsForRollout / amountGroups)); } @@ -135,14 +134,12 @@ public void checkRunningRolloutsDoesNotStartNextGroupIfFinishConditionIsNotHit() final Rollout createdRollout = createAndStartRollout(amountTargetsForRollout, amountOtherTargets, amountGroups, successCondition, errorCondition); - final List runningActions = deploymentManagement.findActionsByRolloutAndStatus(createdRollout, - Status.RUNNING); + final List runningActions = findActionsByRolloutAndStatus(createdRollout, Status.RUNNING); // finish one action should be sufficient due the finish condition is at // 50% final JpaAction action = (JpaAction) runningActions.get(0); - action.setStatus(Status.FINISHED); controllerManagament - .addUpdateActionStatus(new JpaActionStatus(action, Status.FINISHED, System.currentTimeMillis(), "")); + .addUpdateActionStatus(entityFactory.actionStatus().create(action.getId()).status(Status.FINISHED)); // check running rollouts again, now the finish condition should be hit // and should start the next group @@ -258,10 +255,8 @@ private void verifyRolloutAndAllGroupsAreFinished(final Rollout createdRollout) } private void finishAction(final Action action) { - final JpaAction jpaAction = (JpaAction) action; - action.setStatus(Status.FINISHED); controllerManagament - .addUpdateActionStatus(new JpaActionStatus(jpaAction, Status.FINISHED, System.currentTimeMillis(), "")); + .addUpdateActionStatus(entityFactory.actionStatus().create(action.getId()).status(Status.FINISHED)); } @Test @@ -277,14 +272,12 @@ public void checkErrorHitOfGroupCallsErrorActionToPauseTheRollout() { // set both actions in error state so error condition is hit and error // action is executed - final List runningActions = deploymentManagement.findActionsByRolloutAndStatus(createdRollout, - Status.RUNNING); + final List runningActions = findActionsByRolloutAndStatus(createdRollout, Status.RUNNING); // finish actions with error for (final Action action : runningActions) { - action.setStatus(Status.ERROR); - controllerManagament.addUpdateActionStatus( - new JpaActionStatus((JpaAction) action, Status.ERROR, System.currentTimeMillis(), "")); + controllerManagament + .addUpdateActionStatus(entityFactory.actionStatus().create(action.getId()).status(Status.ERROR)); } // check running rollouts again, now the error condition should be hit @@ -320,13 +313,11 @@ public void errorActionPausesRolloutAndRolloutGetsResumedStartsNextScheduledGrou // set both actions in error state so error condition is hit and error // action is executed - final List runningActions = deploymentManagement.findActionsByRolloutAndStatus(createdRollout, - Status.RUNNING); + final List runningActions = findActionsByRolloutAndStatus(createdRollout, Status.RUNNING); // finish actions with error for (final Action action : runningActions) { - action.setStatus(Status.ERROR); - controllerManagament.addUpdateActionStatus( - new JpaActionStatus((JpaAction) action, Status.ERROR, System.currentTimeMillis(), "")); + controllerManagament + .addUpdateActionStatus(entityFactory.actionStatus().create(action.getId()).status(Status.ERROR)); } // check running rollouts again, now the error condition should be hit @@ -553,8 +544,7 @@ public void targetsOfRolloutGetsManuelDsAssignment() { createdRollout = rolloutManagement.findRolloutById(createdRollout.getId()); // 5 targets are running - final List runningActions = deploymentManagement.findActionsByRolloutAndStatus(createdRollout, - Status.RUNNING); + final List runningActions = findActionsByRolloutAndStatus(createdRollout, Status.RUNNING); assertThat(runningActions.size()).isEqualTo(5); // 5 targets are in the group and the DS has been assigned @@ -568,12 +558,12 @@ public void targetsOfRolloutGetsManuelDsAssignment() { assertThat(assignedDs.getId()).isEqualTo(ds.getId()); } - final List targetToCancel = new ArrayList(); + final List targetToCancel = new ArrayList<>(); targetToCancel.add(targetList.get(0)); targetToCancel.add(targetList.get(1)); targetToCancel.add(targetList.get(2)); final DistributionSet dsForCancelTest = testdataFactory.createDistributionSet("dsForTest"); - deploymentManagement.assignDistributionSet(dsForCancelTest, targetToCancel); + assignDistributionSet(dsForCancelTest, targetToCancel); // 5 targets are canceling but still have the status running and 5 are // still in SCHEDULED final Map validationMap = createInitStatusMap(); @@ -964,7 +954,7 @@ public void findRolloutGroupTargetsWithRsqlParam() { Rollout myRollout = createTestRolloutWithTargetsAndDistributionSet(amountTargetsForRollout, amountGroups, successCondition, errorCondition, rolloutName, rolloutName); - targetManagement.createTargets(testdataFactory.generateTargets(amountOtherTargets, "others-", "rollout")); + testdataFactory.createTargets(amountOtherTargets, "others-", "rollout"); final String rsqlParam = "controllerId==*MyRoll*"; @@ -1010,7 +1000,7 @@ public void createRolloutNotMatchingTargets() { createRolloutByVariables(rolloutName, "desc", amountGroups, "id==notExisting", distributionSet, successCondition, errorCondition); fail("Was able to create a Rollout without targets."); - } catch(RolloutVerificationException e) { + } catch (final ConstraintViolationException e) { // OK } @@ -1025,17 +1015,17 @@ public void createDuplicateRollout() { final String errorCondition = "80"; final String rolloutName = "rolloutTest4"; - targetManagement.createTargets(testdataFactory.generateTargets(amountTargetsForRollout, "dup-ro-", "rollout")); + testdataFactory.createTargets(amountTargetsForRollout, "dup-ro-", "rollout"); final DistributionSet distributionSet = testdataFactory.createDistributionSet("dsFor" + rolloutName); - createRolloutByVariables(rolloutName, "desc", amountGroups, "id==dup-ro-*", distributionSet, - successCondition, errorCondition); + createRolloutByVariables(rolloutName, "desc", amountGroups, "id==dup-ro-*", distributionSet, successCondition, + errorCondition); try { createRolloutByVariables(rolloutName, "desc", amountGroups, "id==dup-ro-*", distributionSet, successCondition, errorCondition); fail("Was able to create a duplicate Rollout."); - } catch(EntityAlreadyExistsException e) { + } catch (final EntityAlreadyExistsException e) { // OK } @@ -1051,15 +1041,14 @@ public void createAndStartRolloutWithEmptyGroups() throws Exception { final String rolloutName = "rolloutTestG"; final String targetPrefixName = rolloutName; final DistributionSet distributionSet = testdataFactory.createDistributionSet("dsFor" + rolloutName); - targetManagement.createTargets( - testdataFactory.generateTargets(amountTargetsForRollout, targetPrefixName + "-", targetPrefixName)); + testdataFactory.createTargets(amountTargetsForRollout, targetPrefixName + "-", targetPrefixName); Rollout myRollout = createRolloutByVariables(rolloutName, "desc", amountGroups, "controllerId==" + targetPrefixName + "-*", distributionSet, successCondition, errorCondition); assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.READY); - List groups = myRollout.getRolloutGroups(); + final List groups = myRollout.getRolloutGroups(); assertThat(groups.get(0).getStatus()).isEqualTo(RolloutGroupStatus.READY); assertThat(groups.get(0).getTotalTargets()).isEqualTo(1); assertThat(groups.get(1).getStatus()).isEqualTo(RolloutGroupStatus.READY); @@ -1076,7 +1065,8 @@ public void createAndStartRolloutWithEmptyGroups() throws Exception { // Run here, because scheduler is disabled during tests rolloutManagement.checkStartingRollouts(0); - SuccessConditionRolloutStatus conditionRolloutStatus = new SuccessConditionRolloutStatus(RolloutStatus.RUNNING); + final SuccessConditionRolloutStatus conditionRolloutStatus = new SuccessConditionRolloutStatus( + RolloutStatus.RUNNING); assertThat(MultipleInvokeHelper.doWithTimeout(new RolloutStatusCallable(myRollout.getId()), conditionRolloutStatus, 15000, 500)).as("Rollout status").isNotNull(); @@ -1100,8 +1090,7 @@ public void createAndStartRollout() throws Exception { final String rolloutName = "rolloutTest"; final String targetPrefixName = rolloutName; final DistributionSet distributionSet = testdataFactory.createDistributionSet("dsFor" + rolloutName); - targetManagement.createTargets( - testdataFactory.generateTargets(amountTargetsForRollout, targetPrefixName + "-", targetPrefixName)); + testdataFactory.createTargets(amountTargetsForRollout, targetPrefixName + "-", targetPrefixName); Rollout myRollout = createRolloutByVariables(rolloutName, "desc", amountGroups, "controllerId==" + targetPrefixName + "-*", distributionSet, successCondition, errorCondition); @@ -1112,7 +1101,7 @@ public void createAndStartRollout() throws Exception { // Run here, because scheduler is disabled during tests rolloutManagement.checkStartingRollouts(0); - SuccessConditionRolloutStatus conditionRolloutTargetCount = new SuccessConditionRolloutStatus( + final SuccessConditionRolloutStatus conditionRolloutTargetCount = new SuccessConditionRolloutStatus( RolloutStatus.RUNNING); assertThat(MultipleInvokeHelper.doWithTimeout(new RolloutStatusCallable(myRollout.getId()), conditionRolloutTargetCount, 15000, 500)).as("Rollout status").isNotNull(); @@ -1138,42 +1127,41 @@ public void createRolloutWithGroupDefinition() throws Exception { final int percentTargetsInGroup3 = 100; final int countTargetsInGroup2 = (int) Math - .ceil((double) percentTargetsInGroup2 / 100 * (double) amountTargetsInGroup1and2); + .ceil((double) percentTargetsInGroup2 / 100 * amountTargetsInGroup1and2); final int countTargetsInGroup3 = amountTargetsInGroup1and2 - countTargetsInGroup2; - final RolloutGroupConditions conditions = new RolloutGroupConditionBuilder().build(); + final RolloutGroupConditions conditions = new RolloutGroupConditionBuilder().withDefaults().build(); // Generate Targets for group 2 and 3 and generate the Rollout - Rollout myRollout = generateTargetsAndRollout(rolloutName, amountTargetsInGroup1and2); + final RolloutCreate rolloutcreate = generateTargetsAndRollout(rolloutName, amountTargetsInGroup1and2); // Generate Targets for group 1 - targetManagement.createTargets( - testdataFactory.generateTargets(amountTargetsInGroup1, rolloutName + "-gr1-", rolloutName)); + testdataFactory.createTargets(amountTargetsInGroup1, rolloutName + "-gr1-", rolloutName); - List rolloutGroups = new ArrayList<>(3); + final List rolloutGroups = new ArrayList<>(3); rolloutGroups.add(generateRolloutGroup(0, percentTargetsInGroup1, "id==" + rolloutName + "-gr1-*")); rolloutGroups.add(generateRolloutGroup(1, percentTargetsInGroup2, null)); rolloutGroups.add(generateRolloutGroup(2, percentTargetsInGroup3, null)); - myRollout = rolloutManagement.createRollout(myRollout, rolloutGroups, conditions); + Rollout myRollout = rolloutManagement.createRollout(rolloutcreate, rolloutGroups, conditions); myRollout = rolloutManagement.findRolloutById(myRollout.getId()); assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.CREATING); - for (RolloutGroup group : myRollout.getRolloutGroups()) { + for (final RolloutGroup group : myRollout.getRolloutGroups()) { assertThat(group.getStatus()).isEqualTo(RolloutGroupStatus.CREATING); } // Generate Targets that must not be addressed by the rollout, because // they were added after the rollout was created TimeUnit.SECONDS.sleep(1); - targetManagement.createTargets(testdataFactory.generateTargets(10, rolloutName + "-notIn-", rolloutName)); + testdataFactory.createTargets(10, rolloutName + "-notIn-", rolloutName); - rolloutManagement.fillRolloutGroupsWithTargets(myRollout); + rolloutManagement.fillRolloutGroupsWithTargets(myRollout.getId()); myRollout = rolloutManagement.findRolloutById(myRollout.getId()); assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.READY); assertThat(myRollout.getTotalTargets()).isEqualTo(amountTargetsInGroup1and2 + amountTargetsInGroup1); - List groups = myRollout.getRolloutGroups(); + final List groups = myRollout.getRolloutGroups(); assertThat(groups.get(0).getStatus()).isEqualTo(RolloutGroupStatus.READY); assertThat(groups.get(0).getTotalTargets()).isEqualTo(amountTargetsInGroup1); @@ -1193,17 +1181,17 @@ public void createRolloutWithGroupsNotMatchingTargets() throws Exception { final int percentTargetsInGroup1 = 20; final int percentTargetsInGroup2 = 50; - final RolloutGroupConditions conditions = new RolloutGroupConditionBuilder().build(); - Rollout myRollout = generateTargetsAndRollout(rolloutName, amountTargetsForRollout); + final RolloutGroupConditions conditions = new RolloutGroupConditionBuilder().withDefaults().build(); + final RolloutCreate myRollout = generateTargetsAndRollout(rolloutName, amountTargetsForRollout); - List rolloutGroups = new ArrayList<>(2); + final List rolloutGroups = new ArrayList<>(2); rolloutGroups.add(generateRolloutGroup(0, percentTargetsInGroup1, null)); rolloutGroups.add(generateRolloutGroup(1, percentTargetsInGroup2, null)); try { rolloutManagement.createRollout(myRollout, rolloutGroups, conditions); fail("Was able to create a Rollout with groups that are not addressing all targets"); - } catch(RolloutVerificationException e) { + } catch (final ConstraintViolationException e) { // OK } @@ -1217,17 +1205,17 @@ public void createRolloutWithIllegalPercentage() throws Exception { final int percentTargetsInGroup1 = 101; final int percentTargetsInGroup2 = 50; - final RolloutGroupConditions conditions = new RolloutGroupConditionBuilder().build(); - Rollout myRollout = generateTargetsAndRollout(rolloutName, amountTargetsForRollout); + final RolloutGroupConditions conditions = new RolloutGroupConditionBuilder().withDefaults().build(); + final RolloutCreate myRollout = generateTargetsAndRollout(rolloutName, amountTargetsForRollout); - List rolloutGroups = new ArrayList<>(2); + final List rolloutGroups = new ArrayList<>(2); rolloutGroups.add(generateRolloutGroup(0, percentTargetsInGroup1, null)); rolloutGroups.add(generateRolloutGroup(1, percentTargetsInGroup2, null)); try { rolloutManagement.createRollout(myRollout, rolloutGroups, conditions); fail("Was able to create a Rollout with groups that have illegal percentages"); - } catch(RolloutVerificationException e) { + } catch (final ConstraintViolationException e) { // OK } @@ -1240,13 +1228,13 @@ public void createRolloutWithIllegalAmountOfGroups() throws Exception { final int amountTargetsForRollout = 10; final int illegalGroupAmount = 501; - final RolloutGroupConditions conditions = new RolloutGroupConditionBuilder().build(); - Rollout myRollout = generateTargetsAndRollout(rolloutName, amountTargetsForRollout); + final RolloutGroupConditions conditions = new RolloutGroupConditionBuilder().withDefaults().build(); + final RolloutCreate myRollout = generateTargetsAndRollout(rolloutName, amountTargetsForRollout); try { rolloutManagement.createRollout(myRollout, illegalGroupAmount, conditions); fail("Was able to create a Rollout with too many groups"); - } catch(RolloutVerificationException e) { + } catch (final ConstraintViolationException e) { // OK } @@ -1262,18 +1250,15 @@ public void createAndStartRolloutDuringCreationFails() throws Exception { final String rolloutName = "rolloutTestGC"; final String targetPrefixName = rolloutName; final DistributionSet distributionSet = testdataFactory.createDistributionSet("dsFor" + rolloutName); - targetManagement.createTargets( - testdataFactory.generateTargets(amountTargetsForRollout, targetPrefixName + "-", targetPrefixName)); + testdataFactory.createTargets(amountTargetsForRollout, targetPrefixName + "-", targetPrefixName); - final RolloutGroupConditions conditions = new RolloutGroupConditionBuilder() + final RolloutGroupConditions conditions = new RolloutGroupConditionBuilder().withDefaults() .successCondition(RolloutGroupSuccessCondition.THRESHOLD, successCondition) .errorCondition(RolloutGroupErrorCondition.THRESHOLD, errorCondition) .errorAction(RolloutGroupErrorAction.PAUSE, null).build(); - final Rollout rolloutToCreate = new JpaRollout(); - rolloutToCreate.setName(rolloutName); - rolloutToCreate.setDescription("some description"); - rolloutToCreate.setTargetFilterQuery("id==" + targetPrefixName + "-*"); - rolloutToCreate.setDistributionSet(distributionSet); + final RolloutCreate rolloutToCreate = entityFactory.rollout().create().name(rolloutName) + .description("some description").targetFilterQuery("id==" + targetPrefixName + "-*") + .set(distributionSet); Rollout myRollout = rolloutManagement.createRollout(rolloutToCreate, amountGroups, conditions); myRollout = rolloutManagement.findRolloutById(myRollout.getId()); @@ -1283,38 +1268,27 @@ public void createAndStartRolloutDuringCreationFails() throws Exception { try { rolloutManagement.startRollout(myRollout); fail("Was able to start a Rollout in CREATING status"); - } catch(RolloutIllegalStateException e) { + } catch (final RolloutIllegalStateException e) { // OK } } - private RolloutGroup generateRolloutGroup(final int index, Integer percentage, String targetFilter) { - RolloutGroup group = entityFactory.generateRolloutGroup(); - group.setName("Group" + index); - group.setDescription("Group" + index + "desc"); - if (percentage != null) { - group.setTargetPercentage(percentage); - } - if (targetFilter != null) { - group.setTargetFilterQuery(targetFilter); - } - return group; + private RolloutGroupCreate generateRolloutGroup(final int index, final Integer percentage, + final String targetFilter) { + return entityFactory.rolloutGroup().create().name("Group" + index).description("Group" + index + "desc") + .targetPercentage(Float.valueOf(percentage)).targetFilterQuery(targetFilter); + } - private Rollout generateTargetsAndRollout(final String rolloutName, final int amountTargetsForRollout) { + private RolloutCreate generateTargetsAndRollout(final String rolloutName, final int amountTargetsForRollout) { final DistributionSet distributionSet = testdataFactory.createDistributionSet("dsFor" + rolloutName); - targetManagement.createTargets( - testdataFactory.generateTargets(amountTargetsForRollout, rolloutName + "-", rolloutName)); + testdataFactory.createTargets(amountTargetsForRollout, rolloutName + "-", rolloutName); - Rollout myRollout = entityFactory.generateRollout(); - myRollout.setName(rolloutName); - myRollout.setDescription("This is a test description for the rollout"); - myRollout.setTargetFilterQuery("controllerId==" + rolloutName + "-*"); - myRollout.setDistributionSet(distributionSet); - - return myRollout; + return entityFactory.rollout().create().name(rolloutName) + .description("This is a test description for the rollout") + .targetFilterQuery("controllerId==" + rolloutName + "-*").set(distributionSet); } private void validateRolloutGroupActionStatus(final RolloutGroup rolloutGroup, @@ -1345,10 +1319,10 @@ private Rollout createSimpleTestRolloutWithTargetsAndDistributionSet(final int a 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 DistributionSet rolloutDS = testdataFactory.createDistributionSet("rolloutDS", "0.0.0", standardDsType, + Lists.newArrayList(os, jvm, ah)); + testdataFactory.createTargets(amountTargetsForRollout, "rollout-", "rollout"); + testdataFactory.createTargets(amountOtherTargets, "others-", "rollout"); final String filterQuery = "controllerId==rollout-*"; return createRolloutByVariables("test-rollout-name-1", "test-rollout-description-1", groupSize, filterQuery, rolloutDS, successCondition, errorCondition); @@ -1358,49 +1332,27 @@ private Rollout createTestRolloutWithTargetsAndDistributionSet(final int amountT final int groupSize, final String successCondition, final String errorCondition, final String rolloutName, final String targetPrefixName) { final DistributionSet dsForRolloutTwo = testdataFactory.createDistributionSet("dsFor" + rolloutName); - targetManagement.createTargets( - testdataFactory.generateTargets(amountTargetsForRollout, targetPrefixName + "-", targetPrefixName)); + testdataFactory.createTargets(amountTargetsForRollout, targetPrefixName + "-", targetPrefixName); return createRolloutByVariables(rolloutName, rolloutName + "description", groupSize, "controllerId==" + targetPrefixName + "-*", dsForRolloutTwo, successCondition, errorCondition); } - 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 RolloutGroupConditionBuilder() - .successCondition(RolloutGroupSuccessCondition.THRESHOLD, successCondition) - .errorCondition(RolloutGroupErrorCondition.THRESHOLD, errorCondition) - .errorAction(RolloutGroupErrorAction.PAUSE, null).build(); - final Rollout rolloutToCreate = new JpaRollout(); - rolloutToCreate.setName(rolloutName); - rolloutToCreate.setDescription(rolloutDescription); - rolloutToCreate.setTargetFilterQuery(filterQuery); - rolloutToCreate.setDistributionSet(distributionSet); - final Rollout rollout = rolloutManagement.createRollout(rolloutToCreate, groupSize, conditions); - - // Run here, because Scheduler is disabled during tests - rolloutManagement.fillRolloutGroupsWithTargets(rolloutManagement.findRolloutById(rollout.getId())); - - return rolloutManagement.findRolloutById(rollout.getId()); - } - private int changeStatusForAllRunningActions(final Rollout rollout, final Status status) { - final List runningActions = deploymentManagement.findActionsByRolloutAndStatus(rollout, Status.RUNNING); + final List runningActions = findActionsByRolloutAndStatus(rollout, Status.RUNNING); for (final Action action : runningActions) { - action.setStatus(status); - controllerManagament.addUpdateActionStatus( - new JpaActionStatus((JpaAction) action, status, System.currentTimeMillis(), "")); + controllerManagament + .addUpdateActionStatus(entityFactory.actionStatus().create(action.getId()).status(status)); } return runningActions.size(); } private int changeStatusForRunningActions(final Rollout rollout, final Status status, final int amountOfTargetsToGetChanged) { - final List runningActions = deploymentManagement.findActionsByRolloutAndStatus(rollout, Status.RUNNING); + final List runningActions = findActionsByRolloutAndStatus(rollout, Status.RUNNING); assertThat(runningActions.size()).isGreaterThanOrEqualTo(amountOfTargetsToGetChanged); for (int i = 0; i < amountOfTargetsToGetChanged; i++) { controllerManagament.addUpdateActionStatus( - new JpaActionStatus((JpaAction) runningActions.get(i), status, System.currentTimeMillis(), "")); + entityFactory.actionStatus().create(runningActions.get(i).getId()).status(status)); } return runningActions.size(); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SoftwareManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SoftwareManagementTest.java index 4d45770622..ded5016d46 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SoftwareManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SoftwareManagementTest.java @@ -14,7 +14,6 @@ import java.io.ByteArrayInputStream; import java.io.IOException; -import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; @@ -22,12 +21,11 @@ import javax.validation.ConstraintViolationException; import org.apache.commons.lang3.RandomUtils; +import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeCreate; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.jpa.model.JpaArtifact; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; -import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType; -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; @@ -57,27 +55,14 @@ @Stories("Software Management") public class SoftwareManagementTest extends AbstractJpaIntegrationTest { - @Test - @Description("Try to update non updatable fields results in repository doing nothing.") - public void updateTypeNonUpdateableFieldsFails() { - final SoftwareModuleType created = softwareManagement - .createSoftwareModuleType(new JpaSoftwareModuleType("test-key", "test-name", "test-desc", 1)); - - created.setName("a new name"); - final SoftwareModuleType updated = softwareManagement.updateSoftwareModuleType(created); - - assertThat(updated.getOptLockRevision()) - .as("Expected version number of updated entitity to be equal to created version") - .isEqualTo(created.getOptLockRevision()); - } - @Test @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 JpaSoftwareModuleType("test-key", "test-name", "test-desc", 1)); + final SoftwareModuleType created = softwareManagement.createSoftwareModuleType( + entityFactory.softwareModuleType().create().key("test-key").name("test-name")); - final SoftwareModuleType updated = softwareManagement.updateSoftwareModuleType(created); + final SoftwareModuleType updated = softwareManagement + .updateSoftwareModuleType(entityFactory.softwareModuleType().update(created.getId())); assertThat(updated.getOptLockRevision()) .as("Expected version number of updated entitity to be equal to created version") @@ -87,13 +72,11 @@ public void updateNothingResultsInUnchangedRepositoryForType() { @Test @Description("Calling update for changed fields results in change in the repository.") public void updateSoftareModuleTypeFieldsToNewValue() { - final SoftwareModuleType created = softwareManagement - .createSoftwareModuleType(new JpaSoftwareModuleType("test-key", "test-name", "test-desc", 1)); + final SoftwareModuleType created = softwareManagement.createSoftwareModuleType( + entityFactory.softwareModuleType().create().key("test-key").name("test-name")); - created.setDescription("changed"); - created.setColour("changed"); - - final SoftwareModuleType updated = softwareManagement.updateSoftwareModuleType(created); + final SoftwareModuleType updated = softwareManagement.updateSoftwareModuleType( + entityFactory.softwareModuleType().update(created.getId()).description("changed").colour("changed")); assertThat(updated.getOptLockRevision()).as("Expected version number of updated entitity is") .isEqualTo(created.getOptLockRevision() + 1); @@ -101,27 +84,13 @@ public void updateSoftareModuleTypeFieldsToNewValue() { assertThat(updated.getColour()).as("Updated vendor is").isEqualTo("changed"); } - @Test - @Description("Try to update non updatable fields results in repository doing nothing.") - public void updateNonUpdateableFieldsFails() { - final SoftwareModule ah = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); - - ah.setName("a new name"); - final SoftwareModule updated = softwareManagement.updateSoftwareModule(ah); - - assertThat(updated.getOptLockRevision()) - .as("Expected version number of updated entitity to be equal to created version") - .isEqualTo(ah.getOptLockRevision()); - } - @Test @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 JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + final SoftwareModule ah = testdataFactory.createSoftwareModuleOs(); - final SoftwareModule updated = softwareManagement.updateSoftwareModule(ah); + final SoftwareModule updated = softwareManagement + .updateSoftwareModule(entityFactory.softwareModule().update(ah.getId())); assertThat(updated.getOptLockRevision()) .as("Expected version number of updated entitity to be equal to created version") @@ -131,12 +100,10 @@ public void updateNothingResultsInUnchangedRepository() { @Test @Description("Calling update for changed fields results in change in the repository.") public void updateSoftareModuleFieldsToNewValue() { - final SoftwareModule ah = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", "test desc", "test vendor")); + final SoftwareModule ah = testdataFactory.createSoftwareModuleOs(); - ah.setDescription("changed"); - ah.setVendor("changed"); - final SoftwareModule updated = softwareManagement.updateSoftwareModule(ah); + final SoftwareModule updated = softwareManagement.updateSoftwareModule( + entityFactory.softwareModule().update(ah.getId()).description("changed").vendor("changed")); assertThat(updated.getOptLockRevision()).as("Expected version number of updated entitity is") .isEqualTo(ah.getOptLockRevision() + 1); @@ -147,38 +114,9 @@ public void updateSoftareModuleFieldsToNewValue() { @Test @Description("Create Software Module call fails when called for existing entity.") public void createModuleCallFailsForExistingModule() { - final SoftwareModule ah = softwareManagement - .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."); - } catch (final EntityAlreadyExistsException e) { - - } - } - - @Test - @Description("Create Software Modules call fails when called for existing entities.") - public void createModulesCallFailsForExistingModule() { - final List modules = softwareManagement.createSoftwareModule( - 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."); - } catch (final EntityAlreadyExistsException e) { - - } - } - - @Test - @Description("Create Software Module Type call fails when called for existing entity.") - public void createModuleTypeCallFailsForExistingType() { - final SoftwareModuleType created = softwareManagement - .createSoftwareModuleType(new JpaSoftwareModuleType("test-key", "test-name", "test-desc", 1)); - + testdataFactory.createSoftwareModuleOs(); try { - softwareManagement.createSoftwareModuleType(created); + testdataFactory.createSoftwareModuleOs(); fail("Should not have worked as module already exists."); } catch (final EntityAlreadyExistsException e) { @@ -188,10 +126,11 @@ public void createModuleTypeCallFailsForExistingType() { @Test @Description("Create Software Module Types call fails when called for existing entities.") public void createModuleTypesCallFailsForExistingTypes() { - final List created = softwareManagement.createSoftwareModuleType( - Lists.newArrayList(new JpaSoftwareModuleType("test-key-bumlux", "test-name", "test-desc", 1), - new JpaSoftwareModuleType("test-key-bumlux2", "test-name2", "test-desc", 1))); + final List created = Lists.newArrayList( + entityFactory.softwareModuleType().create().key("test-key").name("test-name"), + entityFactory.softwareModuleType().create().key("test-key2").name("test-name2")); + softwareManagement.createSoftwareModuleType(created); try { softwareManagement.createSoftwareModuleType(created); fail("Should not have worked as module already exists."); @@ -200,38 +139,23 @@ public void createModuleTypesCallFailsForExistingTypes() { } } - @Test - @Description("Calling update for changing fields to null results in change in the repository.") - public void eraseSoftareModuleFields() { - final SoftwareModule ah = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", "test desc", "test vendor")); - - ah.setDescription(null); - ah.setVendor(null); - final SoftwareModule updated = softwareManagement.updateSoftwareModule(ah); - - assertThat(updated.getOptLockRevision()).as("Expected version number of updated entitity is") - .isEqualTo(ah.getOptLockRevision() + 1); - assertThat(updated.getDescription()).as("Updated description is").isNull(); - assertThat(updated.getVendor()).as("Updated vendor is").isNull(); - } - @Test @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 JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); - final SoftwareModule jvm = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(runtimeType, "oracle-jre", "1.7.2", null, "")); - final SoftwareModule os = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(osType, "poky", "3.0.2", null, "")); - - final SoftwareModule ah2 = softwareManagement - .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 JpaTarget target = (JpaTarget) targetManagement.createTarget(new JpaTarget("test123")); + final SoftwareModule ah = softwareManagement.createSoftwareModule( + entityFactory.softwareModule().create().type(appType).name("agent-hub").version("1.0.1")); + final SoftwareModule jvm = softwareManagement.createSoftwareModule( + entityFactory.softwareModule().create().type(runtimeType).name("oracle-jre").version("1.7.2")); + final SoftwareModule os = softwareManagement.createSoftwareModule( + entityFactory.softwareModule().create().type(osType).name("poky").version("3.0.2")); + + final SoftwareModule ah2 = softwareManagement.createSoftwareModule( + entityFactory.softwareModule().create().type(appType).name("agent-hub").version("1.0.2")); + JpaDistributionSet ds = (JpaDistributionSet) distributionSetManagement + .createDistributionSet(entityFactory.distributionSet().create().name("ds-1").version("1.0.1") + .type(standardDsType).modules(Lists.newArrayList(os.getId(), jvm.getId(), ah2.getId()))); + + final JpaTarget target = (JpaTarget) testdataFactory.createTarget(); ds = (JpaDistributionSet) assignSet(target, ds).getDistributionSet(); // standard searches @@ -262,7 +186,7 @@ public void findSoftwareModuleByFilters() { } private Action assignSet(final JpaTarget target, final JpaDistributionSet ds) { - deploymentManagement.assignDistributionSet(ds.getId(), new String[] { target.getControllerId() }); + assignDistributionSet(ds.getId(), target.getControllerId()); assertThat( targetManagement.findTargetByControllerID(target.getControllerId()).getTargetInfo().getUpdateStatus()) .isEqualTo(TargetUpdateStatus.PENDING); @@ -277,13 +201,8 @@ private Action assignSet(final JpaTarget target, final JpaDistributionSet ds) { @Description("Searches for software modules based on a list of IDs.") public void findSoftwareModulesById() { - final List modules = new ArrayList<>(); - - 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); + final List modules = Lists.newArrayList(testdataFactory.createSoftwareModuleOs().getId(), + testdataFactory.createSoftwareModuleApp().getId(), 624355263L); assertThat(softwareManagement.findSoftwareModulesById(modules)).hasSize(2); } @@ -292,14 +211,11 @@ public void findSoftwareModulesById() { @Description("Searches for software modules by type.") public void findSoftwareModulesByType() { // found in test - final SoftwareModule one = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(osType, "one", "one", null, "")); - final SoftwareModule two = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(osType, "two", "two", null, "")); + final SoftwareModule one = testdataFactory.createSoftwareModuleOs("one"); + final SoftwareModule two = testdataFactory.createSoftwareModuleOs("two"); // ignored - softwareManagement.deleteSoftwareModule(softwareManagement - .createSoftwareModule(new JpaSoftwareModule(osType, "deleted", "deleted", null, "")).getId()); - softwareManagement.createSoftwareModule(new JpaSoftwareModule(appType, "three", "3.0.2", null, "")); + softwareManagement.deleteSoftwareModule(testdataFactory.createSoftwareModuleOs("deleted").getId()); + testdataFactory.createSoftwareModuleApp(); assertThat(softwareManagement.findSoftwareModulesByType(pageReq, osType.getId()).getContent()) .as("Expected to find the following number of modules:").hasSize(2).as("with the following elements") @@ -310,11 +226,11 @@ public void findSoftwareModulesByType() { @Description("Counts all software modules in the repsitory that are not marked as deleted.") public void countSoftwareModulesAll() { // found in test - softwareManagement.createSoftwareModule(new JpaSoftwareModule(osType, "one", "one", null, "")); - softwareManagement.createSoftwareModule(new JpaSoftwareModule(appType, "two", "two", null, "")); + final SoftwareModule one = testdataFactory.createSoftwareModuleOs("one"); + final SoftwareModule two = testdataFactory.createSoftwareModuleOs("two"); + final SoftwareModule deleted = testdataFactory.createSoftwareModuleOs("deleted"); // ignored - softwareManagement.deleteSoftwareModule(softwareManagement - .createSoftwareModule(new JpaSoftwareModule(osType, "deleted", "deleted", null, "")).getId()); + softwareManagement.deleteSoftwareModule(deleted.getId()); assertThat(softwareManagement.countSoftwareModulesAll()).as("Expected to find the following number of modules:") .isEqualTo(2); @@ -327,7 +243,7 @@ public void deleteAssignedAndUnassignedSoftwareModuleTypes() { appType); SoftwareModuleType type = softwareManagement.createSoftwareModuleType( - new JpaSoftwareModuleType("bundle", "OSGi Bundle", "fancy stuff", Integer.MAX_VALUE)); + entityFactory.softwareModuleType().create().key("bundle").name("OSGi Bundle")); assertThat(softwareManagement.findSoftwareModuleTypesAll(pageReq)).hasSize(4).contains(osType, runtimeType, appType, type); @@ -340,13 +256,13 @@ public void deleteAssignedAndUnassignedSoftwareModuleTypes() { (JpaSoftwareModuleType) runtimeType, (JpaSoftwareModuleType) appType); type = softwareManagement.createSoftwareModuleType( - new JpaSoftwareModuleType("bundle2", "OSGi Bundle2", "fancy stuff", Integer.MAX_VALUE)); + entityFactory.softwareModuleType().create().key("bundle2").name("OSGi Bundle2")); assertThat(softwareManagement.findSoftwareModuleTypesAll(pageReq)).hasSize(4).contains(osType, runtimeType, appType, type); - softwareManagement - .createSoftwareModule(new JpaSoftwareModule(type, "Test SM", "1.0", "cool module", "from meeee")); + softwareManagement.createSoftwareModule( + entityFactory.softwareModule().create().type(type).name("Test SM").version("1.0")); // delete assigned softwareManagement.deleteSoftwareModuleType(type); @@ -388,15 +304,11 @@ public void hardDeleteOfNotAssignedArtifact() { @Description("Deletes an artifact, which is assigned to a DistributionSet") public void softDeleteOfAssignedArtifact() { - // Init DistributionSet - final DistributionSet disSet = distributionSetManagement - .createDistributionSet(new JpaDistributionSet("ds1", "v1.0", "test ds", standardDsType, null)); - // [STEP1]: Create SoftwareModuleX with ArtifactX SoftwareModule assignedModule = createSoftwareModuleWithArtifacts(osType, "moduleX", "3.0.2", 2); // [STEP2]: Assign SoftwareModule to DistributionSet - distributionSetManagement.assignSoftwareModules(disSet, Sets.newHashSet(assignedModule)); + testdataFactory.createDistributionSet(Sets.newHashSet(assignedModule)); // [STEP3]: Delete the assigned SoftwareModule softwareManagement.deleteSoftwareModule(assignedModule.getId()); @@ -423,19 +335,17 @@ public void softDeleteOfAssignedArtifact() { @Description("Delete an artifact, which has been assigned to a rolled out DistributionSet in the past") public void softDeleteOfHistoricalAssignedArtifact() { - // Init target and DistributionSet - final Target target = targetManagement.createTarget(new JpaTarget("test123")); - final DistributionSet disSet = distributionSetManagement - .createDistributionSet(new JpaDistributionSet("ds1", "v1.0", "test ds", standardDsType, null)); + // Init target + final Target target = testdataFactory.createTarget(); // [STEP1]: Create SoftwareModuleX and include the new ArtifactX SoftwareModule assignedModule = createSoftwareModuleWithArtifacts(osType, "moduleX", "3.0.2", 2); // [STEP2]: Assign SoftwareModule to DistributionSet - distributionSetManagement.assignSoftwareModules(disSet, Sets.newHashSet(assignedModule)); + final DistributionSet disSet = testdataFactory.createDistributionSet(Sets.newHashSet(assignedModule)); // [STEP3]: Assign DistributionSet to a Device - deploymentManagement.assignDistributionSet(disSet, Lists.newArrayList(target)); + assignDistributionSet(disSet, Lists.newArrayList(target)); // [STEP4]: Delete the DistributionSet distributionSetManagement.deleteDistributionSet(disSet); @@ -509,11 +419,7 @@ public void deleteMultipleSoftwareModulesWhichShareAnArtifact() throws IOExcepti // Init artifact binary data, target and DistributionSets final byte[] source = RandomUtils.nextBytes(1024); - final Target target = targetManagement.createTarget(new JpaTarget("test123")); - final DistributionSet disSetX = distributionSetManagement - .createDistributionSet(new JpaDistributionSet("dsX", "v1.0", "test dsX", standardDsType, null)); - final DistributionSet disSetY = distributionSetManagement - .createDistributionSet(new JpaDistributionSet("dsY", "v1.0", "test dsY", standardDsType, null)); + final Target target = testdataFactory.createTarget(); // [STEP1]: Create SoftwareModuleX and add a new ArtifactX SoftwareModule moduleX = createSoftwareModuleWithArtifacts(osType, "modulex", "v1.0", 0); @@ -530,12 +436,12 @@ public void deleteMultipleSoftwareModulesWhichShareAnArtifact() throws IOExcepti final Artifact artifactY = moduleY.getArtifacts().iterator().next(); // [STEP3]: Assign SoftwareModuleX to DistributionSetX and to target - distributionSetManagement.assignSoftwareModules(disSetX, Sets.newHashSet(moduleX)); - deploymentManagement.assignDistributionSet(disSetX, Lists.newArrayList(target)); + final DistributionSet disSetX = testdataFactory.createDistributionSet(Sets.newHashSet(moduleX), "X"); + assignDistributionSet(disSetX, Lists.newArrayList(target)); // [STEP4]: Assign SoftwareModuleY to DistributionSet and to target - distributionSetManagement.assignSoftwareModules(disSetY, Sets.newHashSet(moduleY)); - deploymentManagement.assignDistributionSet(disSetY, Lists.newArrayList(target)); + final DistributionSet disSetY = testdataFactory.createDistributionSet(Sets.newHashSet(moduleY), "Y"); + assignDistributionSet(disSetY, Lists.newArrayList(target)); // [STEP5]: Delete SoftwareModuleX softwareManagement.deleteSoftwareModule(moduleX.getId()); @@ -568,8 +474,8 @@ private SoftwareModule createSoftwareModuleWithArtifacts(final SoftwareModuleTyp final long countSoftwareModule = softwareModuleRepository.count(); // create SoftwareModule - SoftwareModule softwareModule = softwareManagement.createSoftwareModule( - new JpaSoftwareModule(type, name, version, "description of artifact " + name, "")); + SoftwareModule softwareModule = softwareManagement.createSoftwareModule(entityFactory.softwareModule().create() + .type(type).name(name).version(version).description("description of artifact " + name)); for (int i = 0; i < numberArtifacts; i++) { artifactManagement.createArtifact(new RandomGeneratedInputStream(5 * 1024), softwareModule.getId(), @@ -587,9 +493,7 @@ private SoftwareModule createSoftwareModuleWithArtifacts(final SoftwareModuleTyp assertArtfiactNotNull(artifacts.toArray(new Artifact[artifacts.size()])); } - artifacts.forEach(artifact -> { - assertThat(artifactRepository.findOne(artifact.getId())).isNotNull(); - }); + artifacts.forEach(artifact -> assertThat(artifactRepository.findOne(artifact.getId())).isNotNull()); return softwareModule; } @@ -612,35 +516,34 @@ private void assertArtfiactNull(final Artifact... results) { @Description("Test verfies that results are returned based on given filter parameters and in the specified order.") public void findSoftwareModuleOrderByDistributionModuleNameAscModuleVersionAsc() { // test meta data - final SoftwareModuleType testType = softwareManagement - .createSoftwareModuleType(new JpaSoftwareModuleType("thetype", "thename", "desc", 100)); - final DistributionSetType testDsType = distributionSetManagement - .createDistributionSetType(new JpaDistributionSetType("key", "name", "desc") - .addMandatoryModuleType(osType).addOptionalModuleType(testType)); + final SoftwareModuleType testType = softwareManagement.createSoftwareModuleType( + entityFactory.softwareModuleType().create().key("thetype").name("thename").maxAssignments(100)); + DistributionSetType testDsType = distributionSetManagement + .createDistributionSetType(entityFactory.distributionSetType().create().key("key").name("name")); + + distributionSetManagement.assignMandatorySoftwareModuleTypes(testDsType.getId(), + Lists.newArrayList(osType.getId())); + testDsType = distributionSetManagement.assignOptionalSoftwareModuleTypes(testDsType.getId(), + Lists.newArrayList(testType.getId())); // found in test - final SoftwareModule unassigned = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(testType, "asis", "found", null, "")); - final SoftwareModule one = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(testType, "found", "b", null, "")); - final SoftwareModule two = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(testType, "found", "c", null, "")); - final SoftwareModule differentName = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(testType, "differentname", "d", null, "")); + final SoftwareModule unassigned = testdataFactory.createSoftwareModule("thetype", "unassignedfound"); + final SoftwareModule one = testdataFactory.createSoftwareModule("thetype", "bfound"); + final SoftwareModule two = testdataFactory.createSoftwareModule("thetype", "cfound"); + final SoftwareModule differentName = testdataFactory.createSoftwareModule("thetype", "a"); // ignored - final SoftwareModule deleted = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(testType, "deleted", "deleted", null, "")); - final SoftwareModule four = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(osType, "sdfjhsdj", "e", null, "")); + final SoftwareModule deleted = testdataFactory.createSoftwareModule("thetype", "deleted"); + final SoftwareModule four = testdataFactory.createSoftwareModuleOs("e"); - final DistributionSet set = distributionSetManagement.createDistributionSet(new JpaDistributionSet("set", "1", - "desc", testDsType, Lists.newArrayList(one, two, deleted, four, differentName))); + final DistributionSet set = distributionSetManagement.createDistributionSet( + entityFactory.distributionSet().create().name("set").version("1").type(testDsType).modules(Lists + .newArrayList(one.getId(), two.getId(), deleted.getId(), four.getId(), differentName.getId()))); softwareManagement.deleteSoftwareModule(deleted.getId()); // with filter on name, version and module type assertThat(softwareManagement.findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(pageReq, - set.getId(), "found", testType.getId()).getContent()) + set.getId(), "%found%", testType.getId()).getContent()) .as("Found modules with given name, given module type and the assigned ones first") .containsExactly(new AssignedSoftwareModule(one, true), new AssignedSoftwareModule(two, true), new AssignedSoftwareModule(unassigned, false)); @@ -663,34 +566,34 @@ public void findSoftwareModuleOrderByDistributionModuleNameAscModuleVersionAsc() @Test @Description("Checks that number of modules is returned as expected based on given filters.") public void countSoftwareModuleByFilters() { - // test meta data - final SoftwareModuleType testType = softwareManagement - .createSoftwareModuleType(new JpaSoftwareModuleType("thetype", "thename", "desc", 100)); - final DistributionSetType testDsType = distributionSetManagement - .createDistributionSetType(new JpaDistributionSetType("key", "name", "desc") - .addMandatoryModuleType(osType).addOptionalModuleType(testType)); + final SoftwareModuleType testType = softwareManagement.createSoftwareModuleType( + entityFactory.softwareModuleType().create().key("thetype").name("thename").maxAssignments(100)); + DistributionSetType testDsType = distributionSetManagement + .createDistributionSetType(entityFactory.distributionSetType().create().key("key").name("name")); - // test modules - softwareManagement.createSoftwareModule(new JpaSoftwareModule(testType, "asis", "found", null, "")); - final SoftwareModule one = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(testType, "found", "b", null, "")); - final SoftwareModule two = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(testType, "found", "c", null, "")); - final SoftwareModule differentName = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(testType, "differentname", "d", null, "")); - final SoftwareModule four = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(osType, "found", "3.0.2", null, "")); + distributionSetManagement.assignMandatorySoftwareModuleTypes(testDsType.getId(), + Lists.newArrayList(osType.getId())); + testDsType = distributionSetManagement.assignOptionalSoftwareModuleTypes(testDsType.getId(), + Lists.newArrayList(testType.getId())); - // one soft deleted - final SoftwareModule deleted = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(testType, "deleted", "deleted", null, "")); - distributionSetManagement.createDistributionSet(new JpaDistributionSet("set", "1", "desc", testDsType, - Lists.newArrayList(one, two, deleted, four, differentName))); + // found in test + testdataFactory.createSoftwareModule("thetype", "unassignedfound"); + final SoftwareModule one = testdataFactory.createSoftwareModule("thetype", "bfound"); + final SoftwareModule two = testdataFactory.createSoftwareModule("thetype", "cfound"); + final SoftwareModule differentName = testdataFactory.createSoftwareModule("thetype", "d"); + + // ignored + final SoftwareModule deleted = testdataFactory.createSoftwareModule("thetype", "deleted"); + final SoftwareModule four = testdataFactory.createSoftwareModuleOs("e"); + + distributionSetManagement.createDistributionSet( + entityFactory.distributionSet().create().name("set").version("1").type(testDsType).modules(Lists + .newArrayList(one.getId(), two.getId(), deleted.getId(), four.getId(), differentName.getId()))); softwareManagement.deleteSoftwareModule(deleted.getId()); // test - assertThat(softwareManagement.countSoftwareModuleByFilters("found", testType.getId())) + assertThat(softwareManagement.countSoftwareModuleByFilters("%found%", testType.getId())) .as("Number of modules with given name or version and type").isEqualTo(3); assertThat(softwareManagement.countSoftwareModuleByFilters(null, testType.getId())) .as("Number of modules with given type").isEqualTo(4); @@ -701,19 +604,11 @@ public void countSoftwareModuleByFilters() { @Test @Description("Verfies that all undeleted software modules are found in the repository.") public void countSoftwareModuleTypesAll() { - final SoftwareModuleType testType = softwareManagement - .createSoftwareModuleType(new JpaSoftwareModuleType("thetype", "thename", "desc", 100)); - final DistributionSetType testDsType = distributionSetManagement - .createDistributionSetType(new JpaDistributionSetType("key", "name", "desc") - .addMandatoryModuleType(osType).addOptionalModuleType(testType)); - final SoftwareModule four = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(osType, "found", "3.0.2", null, "")); + testdataFactory.createSoftwareModuleOs(); // one soft deleted - final SoftwareModule deleted = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(testType, "deleted", "deleted", null, "")); - distributionSetManagement.createDistributionSet( - new JpaDistributionSet("set", "1", "desc", testDsType, Lists.newArrayList(deleted, four))); + final SoftwareModule deleted = testdataFactory.createSoftwareModuleApp(); + testdataFactory.createDistributionSet(Lists.newArrayList(deleted)); softwareManagement.deleteSoftwareModule(deleted.getId()); assertThat(softwareManagement.countSoftwareModulesAll()).as("Number of undeleted modules").isEqualTo(1); @@ -723,9 +618,11 @@ public void countSoftwareModuleTypesAll() { @Test @Description("Checks that software module typeis found based on given name.") public void findSoftwareModuleTypeByName() { + testdataFactory.createSoftwareModuleOs(); final SoftwareModuleType found = softwareManagement - .createSoftwareModuleType(new JpaSoftwareModuleType("thetype", "thename", "desc", 100)); - softwareManagement.createSoftwareModuleType(new JpaSoftwareModuleType("thetype2", "anothername", "desc", 100)); + .createSoftwareModuleType(entityFactory.softwareModuleType().create().key("thetype").name("thename")); + softwareManagement.createSoftwareModuleType( + entityFactory.softwareModuleType().create().key("thetype2").name("anothername")); assertThat(softwareManagement.findSoftwareModuleTypeByName("thename")).as("Type with given name") .isEqualTo(found); @@ -735,9 +632,10 @@ public void findSoftwareModuleTypeByName() { @Description("Verfies that it is not possible to create a type that alrady exists.") public void createSoftwareModuleTypeFailsWithExistingEntity() { final SoftwareModuleType created = softwareManagement - .createSoftwareModuleType(new JpaSoftwareModuleType("thetype", "thename", "desc", 100)); + .createSoftwareModuleType(entityFactory.softwareModuleType().create().key("thetype").name("thename")); try { - softwareManagement.createSoftwareModuleType(created); + softwareManagement.createSoftwareModuleType( + entityFactory.softwareModuleType().create().key("thetype").name("thename")); fail("should not have worked as module type already exists"); } catch (final EntityAlreadyExistsException e) { @@ -749,10 +647,11 @@ public void createSoftwareModuleTypeFailsWithExistingEntity() { @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 JpaSoftwareModuleType("thetype", "thename", "desc", 100)); + .createSoftwareModuleType(entityFactory.softwareModuleType().create().key("thetype").name("thename")); try { softwareManagement.createSoftwareModuleType( - Lists.newArrayList(created, new JpaSoftwareModuleType("anothertype", "anothername", "desc", 100))); + Lists.newArrayList(entityFactory.softwareModuleType().create().key("thetype").name("thename"), + entityFactory.softwareModuleType().create().key("anothertype").name("anothername"))); fail("should not have worked as module type already exists"); } catch (final EntityAlreadyExistsException e) { @@ -763,7 +662,8 @@ public void createSoftwareModuleTypesFailsWithExistingEntity() { @Description("Verifies that the creation of a softwareModuleType is failing because of invalid max assignment") public void createSoftwareModuleTypesFailsWithInvalidMaxAssignment() { try { - softwareManagement.createSoftwareModuleType(new JpaSoftwareModuleType("type", "name", "desc", 0)); + softwareManagement.createSoftwareModuleType( + entityFactory.softwareModuleType().create().key("type").name("name").maxAssignments(0)); fail("should not have worked as max assignment is invalid. Should be greater than 0."); } catch (final ConstraintViolationException e) { @@ -774,8 +674,8 @@ public void createSoftwareModuleTypesFailsWithInvalidMaxAssignment() { @Description("Verfies that multiple types are created as requested.") public void createMultipleSoftwareModuleTypes() { final List created = softwareManagement.createSoftwareModuleType( - Lists.newArrayList(new JpaSoftwareModuleType("thetype", "thename", "desc", 100), - new JpaSoftwareModuleType("thetype2", "thename2", "desc2", 100))); + Lists.newArrayList(entityFactory.softwareModuleType().create().key("thetype").name("thename"), + entityFactory.softwareModuleType().create().key("thetype2").name("thename2"))); assertThat(created.size()).as("Number of created types").isEqualTo(2); assertThat(softwareManagement.countSoftwareModuleTypesAll()).as("Number of types in repository").isEqualTo(5); @@ -784,23 +684,14 @@ public void createMultipleSoftwareModuleTypes() { @Test @Description("Verfies that software modules are resturned that are assigned to given DS.") public void findSoftwareModuleByAssignedTo() { - // test meta data - final SoftwareModuleType testType = softwareManagement - .createSoftwareModuleType(new JpaSoftwareModuleType("thetype", "thename", "desc", 100)); - final DistributionSetType testDsType = distributionSetManagement - .createDistributionSetType(new JpaDistributionSetType("key", "name", "desc") - .addMandatoryModuleType(osType).addOptionalModuleType(testType)); - // test modules - softwareManagement.createSoftwareModule(new JpaSoftwareModule(testType, "asis", "found", null, "")); - final SoftwareModule one = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(testType, "found", "b", null, "")); + final SoftwareModule one = testdataFactory.createSoftwareModuleOs(); + testdataFactory.createSoftwareModuleOs("notassigned"); // one soft deleted - final SoftwareModule deleted = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(testType, "deleted", "deleted", null, "")); - final DistributionSet set = distributionSetManagement.createDistributionSet( - new JpaDistributionSet("set", "1", "desc", testDsType, Lists.newArrayList(one, deleted))); + final SoftwareModule deleted = testdataFactory.createSoftwareModuleApp(); + final DistributionSet set = distributionSetManagement.createDistributionSet(entityFactory.distributionSet() + .create().name("set").version("1").modules(Lists.newArrayList(one.getId(), deleted.getId()))); softwareManagement.deleteSoftwareModule(deleted.getId()); assertThat(softwareManagement.findSoftwareModuleByAssignedTo(pageReq, set).getContent()) @@ -817,8 +708,7 @@ public void createSoftwareModuleMetadata() { final String knownKey2 = "myKnownKey2"; final String knownValue2 = "myKnownValue2"; - final SoftwareModule ah = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + final SoftwareModule ah = testdataFactory.createSoftwareModuleApp(); assertThat(ah.getOptLockRevision()).isEqualTo(1); @@ -827,7 +717,7 @@ public void createSoftwareModuleMetadata() { final SoftwareModuleMetadata swMetadata2 = new JpaSoftwareModuleMetadata(knownKey2, ah, knownValue2); final List softwareModuleMetadata = softwareManagement - .createSoftwareModuleMetadata(Lists.newArrayList(swMetadata1, swMetadata2)); + .createSoftwareModuleMetadata(ah.getId(), Lists.newArrayList(swMetadata1, swMetadata2)); final SoftwareModule changedLockRevisionModule = softwareManagement.findSoftwareModuleById(ah.getId()); assertThat(changedLockRevisionModule.getOptLockRevision()).isEqualTo(2); @@ -847,13 +737,14 @@ public void createSoftwareModuleMetadataFailsIfKeyExists() { final String knownValue1 = "myKnownValue1"; final String knownValue2 = "myKnownValue2"; - final SoftwareModule ah = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + final SoftwareModule ah = testdataFactory.createSoftwareModuleApp(); - softwareManagement.createSoftwareModuleMetadata(new JpaSoftwareModuleMetadata(knownKey1, ah, knownValue1)); + softwareManagement.createSoftwareModuleMetadata(ah.getId(), + entityFactory.generateMetadata(knownKey1, knownValue1)); try { - softwareManagement.createSoftwareModuleMetadata(new JpaSoftwareModuleMetadata(knownKey1, ah, knownValue2)); + softwareManagement.createSoftwareModuleMetadata(ah.getId(), + entityFactory.generateMetadata(knownKey1, knownValue2)); fail("should not have worked as module metadata already exists"); } catch (final EntityAlreadyExistsException e) { @@ -869,14 +760,13 @@ public void updateSoftwareModuleMetadata() throws InterruptedException { final String knownUpdateValue = "myNewUpdatedValue"; // create a base software module - final SoftwareModule ah = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + final SoftwareModule ah = testdataFactory.createSoftwareModuleApp(); // initial opt lock revision must be 1 assertThat(ah.getOptLockRevision()).isEqualTo(1); // create an software module meta data entry final List softwareModuleMetadata = softwareManagement.createSoftwareModuleMetadata( - Collections.singleton(new JpaSoftwareModuleMetadata(knownKey, ah, knownValue))); + ah.getId(), Collections.singleton(entityFactory.generateMetadata(knownKey, knownValue))); assertThat(softwareModuleMetadata).hasSize(1); // base software module should have now the opt lock revision one // because we are modifying the @@ -884,15 +774,10 @@ public void updateSoftwareModuleMetadata() throws InterruptedException { SoftwareModule changedLockRevisionModule = softwareManagement.findSoftwareModuleById(ah.getId()); assertThat(changedLockRevisionModule.getOptLockRevision()).isEqualTo(2); - // modifying the meta data value - softwareModuleMetadata.get(0).setValue(knownUpdateValue); - softwareModuleMetadata.get(0).setSoftwareModule(softwareManagement.findSoftwareModuleById(ah.getId())); - softwareModuleMetadata.get(0).setKey(knownKey); - // update the software module metadata Thread.sleep(100); - final SoftwareModuleMetadata updated = softwareManagement - .updateSoftwareModuleMetadata(softwareModuleMetadata.get(0)); + final SoftwareModuleMetadata updated = softwareManagement.updateSoftwareModuleMetadata(ah.getId(), + entityFactory.generateMetadata(knownKey, knownUpdateValue)); // we are updating the sw meta data so also modiying the base software // module so opt lock // revision must be two @@ -912,10 +797,10 @@ public void deleteSoftwareModuleMetadata() { final String knownKey1 = "myKnownKey1"; final String knownValue1 = "myKnownValue1"; - SoftwareModule ah = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + SoftwareModule ah = testdataFactory.createSoftwareModuleApp(); - ah = softwareManagement.createSoftwareModuleMetadata(new JpaSoftwareModuleMetadata(knownKey1, ah, knownValue1)) + ah = softwareManagement + .createSoftwareModuleMetadata(ah.getId(), entityFactory.generateMetadata(knownKey1, knownValue1)) .getSoftwareModule(); assertThat(softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(ah.getId())) @@ -933,10 +818,10 @@ public void findSoftwareModuleMetadataFailsIfEntryDoesNotExist() { final String knownKey1 = "myKnownKey1"; final String knownValue1 = "myKnownValue1"; - SoftwareModule ah = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + SoftwareModule ah = testdataFactory.createSoftwareModuleApp(); - ah = softwareManagement.createSoftwareModuleMetadata(new JpaSoftwareModuleMetadata(knownKey1, ah, knownValue1)) + ah = softwareManagement + .createSoftwareModuleMetadata(ah.getId(), entityFactory.generateMetadata(knownKey1, knownValue1)) .getSoftwareModule(); try { @@ -951,22 +836,18 @@ public void findSoftwareModuleMetadataFailsIfEntryDoesNotExist() { @Description("Queries and loads the metadata related to a given software module.") public void findAllSoftwareModuleMetadataBySwId() { - SoftwareModule sw1 = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + SoftwareModule sw1 = testdataFactory.createSoftwareModuleApp(); - SoftwareModule sw2 = softwareManagement - .createSoftwareModule(new JpaSoftwareModule(osType, "os", "1.0.1", null, "")); + SoftwareModule sw2 = testdataFactory.createSoftwareModuleOs(); for (int index = 0; index < 10; index++) { - sw1 = softwareManagement - .createSoftwareModuleMetadata(new JpaSoftwareModuleMetadata("key" + index, sw1, "value" + index)) - .getSoftwareModule(); + sw1 = softwareManagement.createSoftwareModuleMetadata(sw1.getId(), + entityFactory.generateMetadata("key" + index, "value" + index)).getSoftwareModule(); } for (int index = 0; index < 20; index++) { - sw2 = softwareManagement - .createSoftwareModuleMetadata(new JpaSoftwareModuleMetadata("key" + index, sw2, "value" + index)) - .getSoftwareModule(); + sw2 = softwareManagement.createSoftwareModuleMetadata(sw2.getId(), + new JpaSoftwareModuleMetadata("key" + index, sw2, "value" + index)).getSoftwareModule(); } final Page metadataOfSw1 = softwareManagement diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SystemManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SystemManagementTest.java index 4f6d5c91d1..b488ee14dc 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SystemManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SystemManagementTest.java @@ -114,7 +114,7 @@ private byte[] createTestTenantsForSystemStatistics(final int tenants, final int final DistributionSet ds = testdataFactory .createDistributionSet("to be deployed" + x, true); - deploymentManagement.assignDistributionSet(ds, createdTargets); + assignDistributionSet(ds, createdTargets); } } } @@ -127,8 +127,7 @@ private byte[] createTestTenantsForSystemStatistics(final int tenants, final int } private List createTestTargets(final int targets) { - return targetManagement - .createTargets(testdataFactory.generateTargets(targets, "testTargetOfTenant", "testTargetOfTenant")); + return testdataFactory.createTargets(targets, "testTargetOfTenant", "testTargetOfTenant"); } private void createTestArtifact(final byte[] random) { diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TagManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TagManagementTest.java index a1511a0ae7..5b41a33b18 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TagManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TagManagementTest.java @@ -20,7 +20,6 @@ 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; @@ -63,11 +62,11 @@ public void createAndAssignAndDeleteDistributionSetTags() { final Collection dsBCs = testdataFactory.createDistributionSets("DS-BC", 13); final Collection dsABCs = testdataFactory.createDistributionSets("DS-ABC", 9); - 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")); + final DistributionSetTag tagA = tagManagement.createDistributionSetTag(entityFactory.tag().create().name("A")); + final DistributionSetTag tagB = tagManagement.createDistributionSetTag(entityFactory.tag().create().name("B")); + final DistributionSetTag tagC = tagManagement.createDistributionSetTag(entityFactory.tag().create().name("C")); + final DistributionSetTag tagX = tagManagement.createDistributionSetTag(entityFactory.tag().create().name("X")); + final DistributionSetTag tagY = tagManagement.createDistributionSetTag(entityFactory.tag().create().name("Y")); distributionSetManagement.toggleTagAssignment(dsAs, tagA); distributionSetManagement.toggleTagAssignment(dsBs, tagB); @@ -162,7 +161,7 @@ public void assignAndUnassignDistributionSetTags() { final Collection groupB = testdataFactory.createDistributionSets("unassigned", 20); final DistributionSetTag tag = tagManagement - .createDistributionSetTag(new JpaDistributionSetTag("tag1", "tagdesc1", "")); + .createDistributionSetTag(entityFactory.tag().create().name("tag1").description("tagdesc1")); // toggle A only -> A is now assigned DistributionSetTagAssignmentResult result = distributionSetManagement.toggleTagAssignment(groupA, tag); @@ -200,10 +199,11 @@ public void assignAndUnassignDistributionSetTags() { @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(testdataFactory.generateTargets(20, "")); - final List groupB = targetManagement.createTargets(testdataFactory.generateTargets(20, "groupb")); + final List groupA = testdataFactory.createTargets(20); + final List groupB = testdataFactory.createTargets(20, "groupb", "groupb"); - final TargetTag tag = tagManagement.createTargetTag(new JpaTargetTag("tag1", "tagdesc1", "")); + final TargetTag tag = tagManagement + .createTargetTag(entityFactory.tag().create().name("tag1").description("tagdesc1")); // toggle A only -> A is now assigned TargetTagAssignmentResult result = targetManagement.toggleTagAssignment(groupA, tag); @@ -256,7 +256,8 @@ public void findAllTargetTags() { @Test @Description("Ensures that a created tag is persisted in the repository as defined.") public void createTargetTag() { - final Tag tag = tagManagement.createTargetTag(new JpaTargetTag("kai1", "kai2", "colour")); + final Tag tag = tagManagement + .createTargetTag(entityFactory.tag().create().name("kai1").description("kai2").colour("colour")); assertThat(targetTagRepository.findByNameEquals("kai1").getDescription()).as("wrong tag ed").isEqualTo("kai2"); assertThat(tagManagement.findTargetTag("kai1").getColour()).as("wrong tag found").isEqualTo("colour"); @@ -295,10 +296,9 @@ public void updateTargetTag() { // change data final TargetTag savedAssigned = tags.iterator().next(); - savedAssigned.setName("test123"); // persist - tagManagement.updateTargetTag(savedAssigned); + tagManagement.updateTargetTag(entityFactory.tag().update(savedAssigned.getId()).name("test123")); // check data assertThat(targetTagRepository.findAll()).as("Wrong target tag size").hasSize(tags.size()); @@ -311,7 +311,8 @@ public void updateTargetTag() { @Test @Description("Ensures that a created tag is persisted in the repository as defined.") public void createDistributionSetTag() { - final Tag tag = tagManagement.createDistributionSetTag(new JpaDistributionSetTag("kai1", "kai2", "colour")); + final Tag tag = tagManagement.createDistributionSetTag( + entityFactory.tag().create().name("kai1").description("kai2").colour("colour")); assertThat(distributionSetTagRepository.findByNameEquals("kai1").getDescription()).as("wrong tag found") .isEqualTo("kai2"); @@ -355,10 +356,10 @@ public void deleteDistributionSetTag() { @Test @Description("Ensures that a tag cannot be created if one exists already with that name (ecpects EntityAlreadyExistsException).") public void failedDuplicateTargetTagNameException() { - tagManagement.createTargetTag(new JpaTargetTag("A")); + tagManagement.createTargetTag(entityFactory.tag().create().name("A")); try { - tagManagement.createTargetTag(new JpaTargetTag("A")); + tagManagement.createTargetTag(entityFactory.tag().create().name("A")); fail("should not have worked as tag already exists"); } catch (final EntityAlreadyExistsException e) { @@ -368,12 +369,11 @@ public void failedDuplicateTargetTagNameException() { @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 JpaTargetTag("A")); - final TargetTag tag = tagManagement.createTargetTag(new JpaTargetTag("B")); - tag.setName("A"); + tagManagement.createTargetTag(entityFactory.tag().create().name("A")); + final TargetTag tag = tagManagement.createTargetTag(entityFactory.tag().create().name("B")); try { - tagManagement.updateTargetTag(tag); + tagManagement.updateTargetTag(entityFactory.tag().update(tag.getId()).name("A")); fail("should not have worked as tag already exists"); } catch (final EntityAlreadyExistsException e) { @@ -383,9 +383,9 @@ public void failedDuplicateTargetTagNameExceptionAfterUpdate() { @Test @Description("Ensures that a tag cannot be created if one exists already with that name (ecpects EntityAlreadyExistsException).") public void failedDuplicateDsTagNameException() { - tagManagement.createDistributionSetTag(new JpaDistributionSetTag("A")); + tagManagement.createDistributionSetTag(entityFactory.tag().create().name("A")); try { - tagManagement.createDistributionSetTag(new JpaDistributionSetTag("A")); + tagManagement.createDistributionSetTag(entityFactory.tag().create().name("A")); fail("should not have worked as tag already exists"); } catch (final EntityAlreadyExistsException e) { @@ -395,12 +395,11 @@ public void failedDuplicateDsTagNameException() { @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 JpaDistributionSetTag("A")); - final DistributionSetTag tag = tagManagement.createDistributionSetTag(new JpaDistributionSetTag("B")); - tag.setName("A"); + tagManagement.createDistributionSetTag(entityFactory.tag().create().name("A")); + final DistributionSetTag tag = tagManagement.createDistributionSetTag(entityFactory.tag().create().name("B")); try { - tagManagement.updateDistributionSetTag(tag); + tagManagement.updateDistributionSetTag(entityFactory.tag().update(tag.getId()).name("A")); fail("should not have worked as tag already exists"); } catch (final EntityAlreadyExistsException e) { @@ -416,10 +415,9 @@ public void updateDistributionSetTag() { // change data final DistributionSetTag savedAssigned = tags.iterator().next(); - savedAssigned.setName("test123"); // persist - tagManagement.updateDistributionSetTag(savedAssigned); + tagManagement.updateDistributionSetTag(entityFactory.tag().update(savedAssigned.getId()).name("test123")); // check data assertThat(tagManagement.findAllDistributionSetTags()).as("Wrong size of ds tags").hasSize(tags.size()); @@ -439,7 +437,7 @@ public void findDistributionSetTagsAll() { private List createTargetsWithTags() { final List targets = testdataFactory.createTargets(20); - final Iterable tags = tagManagement.createTargetTags(testdataFactory.generateTargetTags(20)); + final Iterable tags = testdataFactory.createTargetTags(20, ""); tags.forEach(tag -> targetManagement.toggleTagAssignment(targets, tag)); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryManagementTest.java index 3bf0d6ea0b..557b230fb6 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryManagementTest.java @@ -21,8 +21,6 @@ import org.eclipse.hawkbit.repository.TargetFilterQueryManagement; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException; -import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; -import org.eclipse.hawkbit.repository.jpa.model.JpaTargetFilterQuery; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetFilterQuery; @@ -46,8 +44,8 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest @Description("Test creation of target filter query.") public void createTargetFilterQuery() { final String filterName = "new target filter"; - final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement - .createTargetFilterQuery(new JpaTargetFilterQuery(filterName, "name==PendingTargets001")); + final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement.createTargetFilterQuery( + entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001")); assertEquals("Retrieved newly created custom target filter", targetFilterQuery, targetFilterQueryManagement.findTargetFilterQueryByName(filterName)); } @@ -56,13 +54,13 @@ public void createTargetFilterQuery() { @Description("Test searching a target filter query.") public void searchTargetFilterQuery() { final String filterName = "targetFilterQueryName"; - final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement - .createTargetFilterQuery(new JpaTargetFilterQuery(filterName, "name==PendingTargets001")); + final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement.createTargetFilterQuery( + entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001")); - targetFilterQueryManagement - .createTargetFilterQuery(new JpaTargetFilterQuery("someOtherFilter", "name==PendingTargets002")); + targetFilterQueryManagement.createTargetFilterQuery( + entityFactory.targetFilterQuery().create().name("someOtherFilter").query("name==PendingTargets002")); - List results = targetFilterQueryManagement + final List results = targetFilterQueryManagement .findTargetFilterQueryByFilter(new PageRequest(0, 10), "name==" + filterName).getContent(); assertEquals("Search result should have 1 result", 1, results.size()); assertEquals("Retrieved newly created custom target filter", targetFilterQuery, results.get(0)); @@ -81,12 +79,12 @@ public void searchTargetFilterQueryInvalidField() { @Description("Checks if the EntityAlreadyExistsException is thrown if a targetfilterquery with the same name are created more than once.") public void createDuplicateTargetFilterQuery() { final String filterName = "new target filter duplicate"; - targetFilterQueryManagement - .createTargetFilterQuery(new JpaTargetFilterQuery(filterName, "name==PendingTargets001")); + targetFilterQueryManagement.createTargetFilterQuery( + entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001")); try { - targetFilterQueryManagement - .createTargetFilterQuery(new JpaTargetFilterQuery(filterName, "name==PendingTargets001")); + targetFilterQueryManagement.createTargetFilterQuery( + entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001")); fail("should not have worked as query already exists"); } catch (final EntityAlreadyExistsException e) { @@ -97,8 +95,8 @@ public void createDuplicateTargetFilterQuery() { @Description("Test deletion of target filter query.") public void deleteTargetFilterQuery() { final String filterName = "delete_target_filter_query"; - final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement - .createTargetFilterQuery(new JpaTargetFilterQuery(filterName, "name==PendingTargets001")); + final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement.createTargetFilterQuery( + entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001")); targetFilterQueryManagement.deleteTargetFilterQuery(targetFilterQuery.getId()); assertEquals("Returns null as the target filter is deleted", null, targetFilterQueryManagement.findTargetFilterQueryById(targetFilterQuery.getId())); @@ -109,12 +107,12 @@ public void deleteTargetFilterQuery() { @Description("Test updation of target filter query.") public void updateTargetFilterQuery() { final String filterName = "target_filter_01"; - final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement - .createTargetFilterQuery(new JpaTargetFilterQuery(filterName, "name==PendingTargets001")); + final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement.createTargetFilterQuery( + entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001")); final String newQuery = "status==UNKNOWN"; - targetFilterQuery.setQuery(newQuery); - targetFilterQueryManagement.updateTargetFilterQuery(targetFilterQuery); + targetFilterQueryManagement.updateTargetFilterQuery( + entityFactory.targetFilterQuery().update(targetFilterQuery.getId()).query(newQuery)); assertEquals("Returns updated target filter query", newQuery, targetFilterQueryManagement.findTargetFilterQueryByName(filterName).getQuery()); @@ -124,20 +122,17 @@ public void updateTargetFilterQuery() { @Description("Test assigning a distribution set") public void assignDistributionSet() { final String filterName = "target_filter_02"; - final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement - .createTargetFilterQuery(new JpaTargetFilterQuery(filterName, "name==PendingTargets001")); + final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement.createTargetFilterQuery( + entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001")); - final DistributionSet distributionSet = distributionSetManagement.createDistributionSet(new JpaDistributionSet( - "dist_Set_01", "0.1", "", null, null - )); + final DistributionSet distributionSet = testdataFactory.createDistributionSet(); - targetFilterQuery.setAutoAssignDistributionSet(distributionSet); - targetFilterQueryManagement.updateTargetFilterQuery(targetFilterQuery); + targetFilterQueryManagement.updateTargetFilterQueryAutoAssignDS(targetFilterQuery.getId(), + distributionSet.getId()); - TargetFilterQuery tfq = targetFilterQueryManagement.findTargetFilterQueryByName(filterName); + final TargetFilterQuery tfq = targetFilterQueryManagement.findTargetFilterQueryByName(filterName); - assertEquals("Returns correct distribution set", distributionSet, - tfq.getAutoAssignDistributionSet()); + assertEquals("Returns correct distribution set", distributionSet, tfq.getAutoAssignDistributionSet()); } @@ -145,20 +140,17 @@ public void assignDistributionSet() { @Description("Test removing distribution set while it has a relation to a target filter query") public void removeAssignDistributionSet() { final String filterName = "target_filter_03"; - final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement - .createTargetFilterQuery(new JpaTargetFilterQuery(filterName, "name==PendingTargets001")); + final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement.createTargetFilterQuery( + entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001")); - final DistributionSet distributionSet = distributionSetManagement.createDistributionSet(new JpaDistributionSet( - "dist_Set_02", "0.1", "", null, null - )); + final DistributionSet distributionSet = testdataFactory.createDistributionSet(); - targetFilterQuery.setAutoAssignDistributionSet(distributionSet); - targetFilterQueryManagement.updateTargetFilterQuery(targetFilterQuery); + targetFilterQueryManagement.updateTargetFilterQueryAutoAssignDS(targetFilterQuery.getId(), + distributionSet.getId()); // Check if target filter query is there TargetFilterQuery tfq = targetFilterQueryManagement.findTargetFilterQueryByName(filterName); - assertEquals("Returns correct distribution set", distributionSet, - tfq.getAutoAssignDistributionSet()); + assertEquals("Returns correct distribution set", distributionSet, tfq.getAutoAssignDistributionSet()); distributionSetManagement.deleteDistributionSet(distributionSet); @@ -173,15 +165,17 @@ public void removeAssignDistributionSet() { @Description("Test to implicitly remove the auto assign distribution set when the ds is soft deleted") public void implicitlyRemoveAssignDistributionSet() { final String filterName = "target_filter_03"; - DistributionSet distributionSet = testdataFactory.createDistributionSet("dist_set"); - Target target = testdataFactory.createTarget(); + final DistributionSet distributionSet = testdataFactory.createDistributionSet("dist_set"); + final Target target = testdataFactory.createTarget(); // Assign the distribution set to an target, to force a soft delete in a // later step - deploymentManagement.assignDistributionSet(distributionSet.getId(), target.getControllerId()); + assignDistributionSet(distributionSet.getId(), target.getControllerId()); - targetFilterQueryManagement.createTargetFilterQuery( - new JpaTargetFilterQuery(filterName, "name==PendingTargets001", (JpaDistributionSet) distributionSet)); + targetFilterQueryManagement.updateTargetFilterQueryAutoAssignDS(targetFilterQueryManagement + .createTargetFilterQuery( + entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001")) + .getId(), distributionSet.getId()); // Check if target filter query is there with the distribution set TargetFilterQuery tfq = targetFilterQueryManagement.findTargetFilterQueryByName(filterName); @@ -208,19 +202,24 @@ public void findFiltersWithDistributionSet() { assertEquals(0L, targetFilterQueryManagement.countAllTargetFilterQuery().longValue()); - targetFilterQueryManagement.createTargetFilterQuery(new JpaTargetFilterQuery("a", "name==*")); - targetFilterQueryManagement.createTargetFilterQuery(new JpaTargetFilterQuery("b", "name==*")); + targetFilterQueryManagement + .createTargetFilterQuery(entityFactory.targetFilterQuery().create().name("a").query("name==*")); + targetFilterQueryManagement + .createTargetFilterQuery(entityFactory.targetFilterQuery().create().name("b").query("name==*")); - final DistributionSet distributionSet = distributionSetManagement - .createDistributionSet(new JpaDistributionSet("dist_Set_01", "0.1", "", null, null)); - final DistributionSet distributionSet2 = distributionSetManagement - .createDistributionSet(new JpaDistributionSet("dist_Set_02", "0.1", "", null, null)); + final DistributionSet distributionSet = testdataFactory.createDistributionSet(); + final DistributionSet distributionSet2 = testdataFactory.createDistributionSet("2"); - final TargetFilterQuery tfq = targetFilterQueryManagement.createTargetFilterQuery( - new JpaTargetFilterQuery("c", "name==x", (JpaDistributionSet) distributionSet)); + final TargetFilterQuery tfq = targetFilterQueryManagement + .updateTargetFilterQueryAutoAssignDS( + targetFilterQueryManagement.createTargetFilterQuery( + entityFactory.targetFilterQuery().create().name("c").query("name==x")).getId(), + distributionSet.getId()); - final TargetFilterQuery tfq2 = targetFilterQueryManagement.createTargetFilterQuery( - new JpaTargetFilterQuery(filterName, "name==z*", (JpaDistributionSet) distributionSet2)); + final TargetFilterQuery tfq2 = targetFilterQueryManagement.updateTargetFilterQueryAutoAssignDS( + targetFilterQueryManagement.createTargetFilterQuery( + entityFactory.targetFilterQuery().create().name(filterName).query("name==z*")).getId(), + distributionSet2.getId()); assertEquals(4L, targetFilterQueryManagement.countAllTargetFilterQuery().longValue()); @@ -231,8 +230,7 @@ public void findFiltersWithDistributionSet() { assertEquals("Returns correct target filter query", tfq.getId(), tfqList.iterator().next().getId()); - tfq2.setAutoAssignDistributionSet(distributionSet); - targetFilterQueryManagement.updateTargetFilterQuery(tfq2); + targetFilterQueryManagement.updateTargetFilterQueryAutoAssignDS(tfq2.getId(), distributionSet.getId()); // check if find works for two tfqList = targetFilterQueryManagement.findTargetFilterQueryByAutoAssignDS(new PageRequest(0, 500), diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementSearchTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementSearchTest.java index 163cb67ddb..d0d708f555 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementSearchTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementSearchTest.java @@ -19,14 +19,9 @@ import java.util.stream.Collectors; import org.eclipse.hawkbit.repository.FilterParams; -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; @@ -54,10 +49,10 @@ public class TargetManagementSearchTest extends AbstractJpaIntegrationTest { + "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 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 TargetTag targTagX = tagManagement.createTargetTag(entityFactory.tag().create().name("TargTag-X")); + final TargetTag targTagY = tagManagement.createTargetTag(entityFactory.tag().create().name("TargTag-Y")); + final TargetTag targTagZ = tagManagement.createTargetTag(entityFactory.tag().create().name("TargTag-Z")); + final TargetTag targTagW = tagManagement.createTargetTag(entityFactory.tag().create().name("TargTag-W")); final DistributionSet setA = testdataFactory.createDistributionSet(""); @@ -68,72 +63,54 @@ public void targetSearchWithVariousFilterCombinations() { final Long lastTargetNull = null; final String targetDsAIdPref = "targ-A"; - List targAs = new ArrayList(); - for (Target t : testdataFactory.generateTargets(100, targetDsAIdPref, targetDsAIdPref.concat(" description"))) { - targAs.add(targetManagement.createTarget(t, TargetUpdateStatus.UNKNOWN, lastTargetQueryNotOverdue, - t.getTargetInfo().getAddress())); - } + List targAs = testdataFactory.createTargets(100, targetDsAIdPref, + targetDsAIdPref.concat(" description"), lastTargetQueryNotOverdue); targAs = targetManagement.toggleTagAssignment(targAs, targTagX).getAssignedEntity(); final String targetDsBIdPref = "targ-B"; - List targBs = new ArrayList(); - for (Target t : testdataFactory.generateTargets(100, targetDsBIdPref, targetDsBIdPref.concat(" description"))) { - targBs.add(targetManagement.createTarget(t, TargetUpdateStatus.UNKNOWN, lastTargetQueryAlwaysOverdue, - t.getTargetInfo().getAddress())); - } + List targBs = testdataFactory.createTargets(100, targetDsBIdPref, + targetDsBIdPref.concat(" description"), lastTargetQueryAlwaysOverdue); + targBs = targetManagement.toggleTagAssignment(targBs, targTagY).getAssignedEntity(); targBs = targetManagement.toggleTagAssignment(targBs, targTagW).getAssignedEntity(); final String targetDsCIdPref = "targ-C"; - List targCs = new ArrayList(); - for (Target t : testdataFactory.generateTargets(100, targetDsCIdPref, targetDsCIdPref.concat(" description"))) { - targCs.add(targetManagement.createTarget(t, TargetUpdateStatus.UNKNOWN, lastTargetQueryAlwaysOverdue, - t.getTargetInfo().getAddress())); - } + List targCs = testdataFactory.createTargets(100, targetDsCIdPref, + targetDsCIdPref.concat(" description"), lastTargetQueryAlwaysOverdue); + targCs = targetManagement.toggleTagAssignment(targCs, targTagZ).getAssignedEntity(); targCs = targetManagement.toggleTagAssignment(targCs, targTagW).getAssignedEntity(); final String targetDsDIdPref = "targ-D"; - List targDs = new ArrayList(); - for (Target t : testdataFactory.generateTargets(100, targetDsDIdPref, targetDsDIdPref.concat(" description"))) { - targDs.add(targetManagement.createTarget(t, TargetUpdateStatus.UNKNOWN, lastTargetNull, - t.getTargetInfo().getAddress())); - } + final List targDs = testdataFactory.createTargets(100, targetDsDIdPref, + targetDsDIdPref.concat(" description"), lastTargetNull); final String assignedC = targCs.iterator().next().getControllerId(); - deploymentManagement.assignDistributionSet(setA.getId(), assignedC); + assignDistributionSet(setA.getId(), assignedC); final String assignedA = targAs.iterator().next().getControllerId(); - deploymentManagement.assignDistributionSet(setA.getId(), assignedA); + assignDistributionSet(setA.getId(), assignedA); final String assignedB = targBs.iterator().next().getControllerId(); - deploymentManagement.assignDistributionSet(setA.getId(), assignedB); + assignDistributionSet(setA.getId(), assignedB); final String installedC = targCs.iterator().next().getControllerId(); - final Long actionId = deploymentManagement.assignDistributionSet(installedSet.getId(), assignedC).getActions() - .get(0); + final Long actionId = assignDistributionSet(installedSet.getId(), assignedC).getActions().get(0); // set one installed DS also - final Action action = deploymentManagement.findActionWithDetails(actionId); - action.setStatus(Status.FINISHED); controllerManagament.addUpdateActionStatus( - new JpaActionStatus((JpaAction) action, Status.FINISHED, System.currentTimeMillis(), "message")); - deploymentManagement.assignDistributionSet(setA.getId(), installedC); - - final List unknown = new ArrayList<>(); - unknown.add(TargetUpdateStatus.UNKNOWN); + entityFactory.actionStatus().create(actionId).status(Status.FINISHED).message("message")); + assignDistributionSet(setA.getId(), installedC); - final List pending = new ArrayList<>(); - pending.add(TargetUpdateStatus.PENDING); - - final List both = new ArrayList<>(); - both.add(TargetUpdateStatus.UNKNOWN); - both.add(TargetUpdateStatus.PENDING); + final List unknown = Lists.newArrayList(TargetUpdateStatus.UNKNOWN); + final List pending = Lists.newArrayList(TargetUpdateStatus.PENDING); + final List both = Lists.newArrayList(TargetUpdateStatus.UNKNOWN, + TargetUpdateStatus.PENDING); // get final updated version of targets - targAs = targetManagement.findTargetByControllerID( - targAs.stream().map(target -> target.getControllerId()).collect(Collectors.toList())); - targBs = targetManagement.findTargetByControllerID( - targBs.stream().map(target -> target.getControllerId()).collect(Collectors.toList())); - targCs = targetManagement.findTargetByControllerID( - targCs.stream().map(target -> target.getControllerId()).collect(Collectors.toList())); + targAs = targetManagement + .findTargetByControllerID(targAs.stream().map(Target::getControllerId).collect(Collectors.toList())); + targBs = targetManagement + .findTargetByControllerID(targBs.stream().map(Target::getControllerId).collect(Collectors.toList())); + targCs = targetManagement + .findTargetByControllerID(targCs.stream().map(Target::getControllerId).collect(Collectors.toList())); // try to find several targets with different filter settings verifyThatRepositoryContains400Targets(); @@ -352,7 +329,8 @@ private void verifyThat3TargetsWithGivenDSAreInPending(final DistributionSet set assertThat(targetManagement .findTargetByFilters(pageReq, pending, null, null, setA.getId(), Boolean.FALSE, new String[0]) - .getContent()).as("has number of elements").hasSize(3).as("that number is also returned by count query") + .getContent()).as("has number of elements").hasSize(3) + .as("that number is also returned by count query") .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(pending, null, null, setA.getId(), Boolean.FALSE, new String[0]))) .as("and contains the following elements").containsAll(expected) @@ -427,8 +405,9 @@ private void verifyThat99TargetsWithNameOrDescriptionAreInGivenStatus(final List assertThat(targetManagement .findTargetByFilters(pageReq, unknown, null, "%targ-A%", null, Boolean.FALSE, new String[0]) .getContent()).as("has number of elements").hasSize(99) - .as("that number is also returned by count query").hasSize(Ints.saturatedCast(targetManagement - .countTargetByFilters(unknown, null, "%targ-A%", null, Boolean.FALSE, new String[0]))) + .as("that number is also returned by count query") + .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(unknown, null, "%targ-A%", + null, Boolean.FALSE, new String[0]))) .as("and contains the following elements").containsAll(expected) .as("and filter query returns the same result") .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) @@ -450,7 +429,8 @@ private void verfyThat0TargetsAreInStatusUnknownAndHaveDSAssigned(final Distribu assertThat(targetManagement .findTargetByFilters(pageReq, unknown, null, null, setA.getId(), Boolean.FALSE, new String[0]) - .getContent()).as("has number of elements").hasSize(0).as("that number is also returned by count query") + .getContent()).as("has number of elements").hasSize(0) + .as("that number is also returned by count query") .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(unknown, null, null, setA.getId(), Boolean.FALSE, new String[0]))) .as("and filter query returns the same result") @@ -727,19 +707,17 @@ private void verifyThatRepositoryContains400Targets() { @Description("Tests the correct order of targets based on selected distribution set. The system expects to have an order based on installed, assigned DS.") public void targetSearchWithVariousFilterCombinationsAndOrderByDistributionSet() { - final List notAssigned = targetManagement - .createTargets(testdataFactory.generateTargets(3, "not", "first description")); - List targAssigned = targetManagement - .createTargets(testdataFactory.generateTargets(3, "assigned", "first description")); - List targInstalled = targetManagement - .createTargets(testdataFactory.generateTargets(3, "installed", "first description")); + final List notAssigned = testdataFactory.createTargets(3, "not", "first description"); + List targAssigned = testdataFactory.createTargets(3, "assigned", "first description"); + List targInstalled = testdataFactory.createTargets(3, "installed", "first description"); final DistributionSet ds = testdataFactory.createDistributionSet("a"); - targAssigned = Lists - .newLinkedList(deploymentManagement.assignDistributionSet(ds, targAssigned).getAssignedEntity()); - targInstalled = deploymentManagement.assignDistributionSet(ds, targInstalled).getAssignedEntity(); - targInstalled = sendUpdateActionStatusToTargets(ds, targInstalled, Status.FINISHED, "installed"); + targAssigned = Lists.newLinkedList(assignDistributionSet(ds, targAssigned).getAssignedEntity()); + targInstalled = assignDistributionSet(ds, targInstalled).getAssignedEntity(); + targInstalled = testdataFactory + .sendUpdateActionStatusToTargets(targInstalled, Status.FINISHED, Collections.singletonList("installed")) + .stream().map(Action::getTarget).collect(Collectors.toList()); final Slice result = targetManagement.findTargetsAllOrderByLinkedDistributionSet(pageReq, ds.getId(), new FilterParams(null, null, null, null, Boolean.FALSE, new String[0])); @@ -770,31 +748,26 @@ public void targetSearchWithOverdueFilterAndOrderByDistributionSet() { final Long[] overdueMix = { lastTargetQueryAlwaysOverdue, lastTargetQueryNotOverdue, lastTargetQueryAlwaysOverdue, lastTargetNull, lastTargetQueryAlwaysOverdue }; - List notAssignedToBeCreated = testdataFactory.generateTargets(overdueMix.length, "not", - "first description"); - List targAssignedToBeCreated = testdataFactory.generateTargets(overdueMix.length, "assigned", - "first description"); - List targInstalledToBeCreated = testdataFactory.generateTargets(overdueMix.length, "installed", - "first description"); - - List notAssigned = new ArrayList<>(); - List targAssigned = new ArrayList<>(); - List targInstalled = new ArrayList<>(); + final List notAssigned = Lists.newArrayListWithExpectedSize(overdueMix.length); + List targAssigned = Lists.newArrayListWithExpectedSize(overdueMix.length); + List targInstalled = Lists.newArrayListWithExpectedSize(overdueMix.length); for (int i = 0; i < overdueMix.length; i++) { - notAssigned.add(targetManagement.createTarget(notAssignedToBeCreated.get(i), TargetUpdateStatus.UNKNOWN, - overdueMix[i], notAssignedToBeCreated.get(i).getTargetInfo().getAddress())); - targAssigned.add(targetManagement.createTarget(targAssignedToBeCreated.get(i), TargetUpdateStatus.UNKNOWN, - overdueMix[i], targAssignedToBeCreated.get(i).getTargetInfo().getAddress())); - targInstalled.add(targetManagement.createTarget(targInstalledToBeCreated.get(i), TargetUpdateStatus.UNKNOWN, - overdueMix[i], targInstalledToBeCreated.get(i).getTargetInfo().getAddress())); + notAssigned.add(targetManagement.createTarget( + entityFactory.target().create().controllerId("not" + i).lastTargetQuery(overdueMix[i]))); + targAssigned.add(targetManagement.createTarget( + entityFactory.target().create().controllerId("assigned" + i).lastTargetQuery(overdueMix[i]))); + targInstalled.add(targetManagement.createTarget( + entityFactory.target().create().controllerId("installed" + i).lastTargetQuery(overdueMix[i]))); } final DistributionSet ds = testdataFactory.createDistributionSet("a"); - targAssigned = deploymentManagement.assignDistributionSet(ds, targAssigned).getAssignedEntity(); - targInstalled = deploymentManagement.assignDistributionSet(ds, targInstalled).getAssignedEntity(); - targInstalled = sendUpdateActionStatusToTargets(ds, targInstalled, Status.FINISHED, "installed"); + targAssigned = assignDistributionSet(ds, targAssigned).getAssignedEntity(); + targInstalled = assignDistributionSet(ds, targInstalled).getAssignedEntity(); + targInstalled = testdataFactory + .sendUpdateActionStatusToTargets(targInstalled, Status.FINISHED, Collections.singletonList("installed")) + .stream().map(action -> action.getTarget()).collect(Collectors.toList()); final Slice result = targetManagement.findTargetsAllOrderByLinkedDistributionSet(pageReq, ds.getId(), new FilterParams(null, null, Boolean.TRUE, null, Boolean.FALSE, new String[0])); @@ -821,10 +794,10 @@ public void targetSearchWithOverdueFilterAndOrderByDistributionSet() { @Description("Verfies that targets with given assigned DS are returned from repository.") public void findTargetByAssignedDistributionSet() { final DistributionSet assignedSet = testdataFactory.createDistributionSet(""); - targetManagement.createTargets(testdataFactory.generateTargets(10, "unassigned")); - List assignedtargets = targetManagement.createTargets(testdataFactory.generateTargets(10, "assigned")); + testdataFactory.createTargets(10, "unassigned", "unassigned"); + List assignedtargets = testdataFactory.createTargets(10, "assigned", "assigned"); - deploymentManagement.assignDistributionSet(assignedSet, assignedtargets); + assignDistributionSet(assignedSet, assignedtargets); // get final updated version of targets assignedtargets = targetManagement.findTargetByControllerID( @@ -841,18 +814,16 @@ public void findTargetByAssignedDistributionSet() { public void findTargetWithoutAssignedDistributionSet() { final DistributionSet assignedSet = testdataFactory.createDistributionSet(""); final TargetFilterQuery tfq = targetFilterQueryManagement - .createTargetFilterQuery(entityFactory.generateTargetFilterQuery("tfq", "name==*")); - List unassignedTargets = targetManagement - .createTargets(testdataFactory.generateTargets(12, "unassigned")); - List assignedTargets = targetManagement.createTargets(testdataFactory.generateTargets(10, "assigned")); + .createTargetFilterQuery(entityFactory.targetFilterQuery().create().name("tfq").query("name==*")); + final List unassignedTargets = testdataFactory.createTargets(12, "unassigned", "unassigned"); + final List assignedTargets = testdataFactory.createTargets(10, "assigned", "assigned"); - deploymentManagement.assignDistributionSet(assignedSet, assignedTargets); + assignDistributionSet(assignedSet, assignedTargets); - List result = targetManagement.findAllTargetsByTargetFilterQueryAndNonDS(pageReq, - assignedSet.getId(), tfq).getContent(); - assertThat(result) - .as("count of targets").hasSize(unassignedTargets.size()) - .as("contains all targets").containsAll(unassignedTargets); + final List result = targetManagement + .findAllTargetsByTargetFilterQueryAndNonDS(pageReq, assignedSet.getId(), tfq).getContent(); + assertThat(result).as("count of targets").hasSize(unassignedTargets.size()).as("contains all targets") + .containsAll(unassignedTargets); } @@ -861,17 +832,13 @@ public void findTargetWithoutAssignedDistributionSet() { public void findTargetByInstalledDistributionSet() { 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")); + testdataFactory.createTargets(10, "unassigned", "unassigned"); + List installedtargets = testdataFactory.createTargets(10, "assigned", "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 JpaActionStatus((JpaAction) action, Status.FINISHED, System.currentTimeMillis(), "message")); - }); - deploymentManagement.assignDistributionSet(assignedSet, installedtargets); + assignDistributionSet(installedSet, installedtargets).getActions().forEach(actionId -> controllerManagament + .addUpdateActionStatus(entityFactory.actionStatus().create(actionId).status(Status.FINISHED))); + assignDistributionSet(assignedSet, installedtargets); // get final updated version of targets installedtargets = targetManagement.findTargetByControllerID( @@ -882,32 +849,4 @@ public void findTargetByInstalledDistributionSet() { .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((JpaTarget) t); - for (final Action action : findByTarget) { - result.add(sendUpdateActionStatusToTarget(status, action, t, msgs)); - } - } - return result; - } - - private Target sendUpdateActionStatusToTarget(final Status status, final Action updActA, final Target t, - final String... msgs) { - updActA.setStatus(status); - - 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); - return targetManagement.findTargetByControllerID(t.getControllerId()); - } - } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementTest.java index 4188ebfc54..a7e244f7e7 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementTest.java @@ -13,23 +13,16 @@ import static com.google.common.collect.Lists.newArrayList; import static java.util.stream.Collectors.toList; import static org.fest.assertions.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; import java.util.stream.Collectors; -import javax.persistence.Query; import javax.validation.ConstraintViolationException; import org.eclipse.hawkbit.im.authentication.SpPermission; @@ -43,11 +36,7 @@ import org.eclipse.hawkbit.repository.event.remote.entity.TargetUpdatedEvent; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; import org.eclipse.hawkbit.repository.exception.TenantNotExistException; -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.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetAssignmentResult; @@ -63,6 +52,7 @@ import org.springframework.data.domain.PageRequest; import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; @@ -76,7 +66,8 @@ public class TargetManagementTest extends AbstractJpaIntegrationTest { @Description("Ensures that retrieving the target security is only permitted with the necessary permissions.") @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1) }) public void getTargetSecurityTokenOnlyWithCorrectPermission() throws Exception { - final Target createdTarget = targetManagement.createTarget(new JpaTarget("targetWithSecurityToken", "token")); + final Target createdTarget = targetManagement.createTarget( + entityFactory.target().create().controllerId("targetWithSecurityToken").securityToken("token")); // retrieve security token only with READ_TARGET_SEC_TOKEN permission final String securityTokenWithReadPermission = securityRule.runAs(WithSpringAuthorityRule @@ -108,7 +99,7 @@ public void getTargetSecurityTokenOnlyWithCorrectPermission() throws Exception { @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) }) public void createTargetForTenantWhichDoesNotExistThrowsTenantNotExistException() { try { - targetManagement.createTarget(new JpaTarget("targetId123")); + targetManagement.createTarget(entityFactory.target().create().controllerId("targetId123")); fail("should not be possible as the tenant does not exist"); } catch (final TenantNotExistException e) { // ok @@ -120,14 +111,14 @@ public void createTargetForTenantWhichDoesNotExistThrowsTenantNotExistException( @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) }) public void createTargetWithNoControllerId() { try { - targetManagement.createTarget(new JpaTarget("")); + targetManagement.createTarget(entityFactory.target().create().controllerId("")); fail("target with empty controller id should not be created"); } catch (final ConstraintViolationException e) { // ok } try { - targetManagement.createTarget(new JpaTarget(null)); + targetManagement.createTarget(entityFactory.target().create().controllerId(null)); fail("target with empty controller id should not be created"); } catch (final ConstraintViolationException e) { // ok @@ -140,14 +131,18 @@ public void createTargetWithNoControllerId() { @Expect(type = TargetTagCreatedEvent.class, count = 1), @Expect(type = TargetUpdatedEvent.class, count = 8) }) public void assignAndUnassignTargetsToTag() { - final List assignTarget = new ArrayList(); - 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()); + final List assignTarget = new ArrayList<>(); + assignTarget.add(targetManagement.createTarget(entityFactory.target().create().controllerId("targetId123")) + .getControllerId()); + assignTarget.add(targetManagement.createTarget(entityFactory.target().create().controllerId("targetId1234")) + .getControllerId()); + assignTarget.add(targetManagement.createTarget(entityFactory.target().create().controllerId("targetId1235")) + .getControllerId()); + assignTarget.add(targetManagement.createTarget(entityFactory.target().create().controllerId("targetId1236")) + .getControllerId()); assignTarget.add("NotExist"); - final TargetTag targetTag = tagManagement.createTargetTag(new JpaTargetTag("Tag1")); + final TargetTag targetTag = tagManagement.createTargetTag(entityFactory.tag().create().name("Tag1")); final List assignedTargets = targetManagement.assignTag(assignTarget, targetTag); assertThat(assignedTargets.size()).as("Assigned targets are wrong").isEqualTo(4); @@ -178,7 +173,7 @@ public void assignAndUnassignTargetsToTag() { @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 12), @Expect(type = TargetDeletedEvent.class, count = 12), @Expect(type = TargetUpdatedEvent.class, count = 6) }) public void deleteAndCreateTargets() { - Target target = targetManagement.createTarget(new JpaTarget("targetId123")); + Target target = targetManagement.createTarget(entityFactory.target().create().controllerId("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); @@ -190,7 +185,7 @@ public void deleteAndCreateTargets() { final List targets = new ArrayList<>(); for (int i = 0; i < 5; i++) { - target = targetManagement.createTarget(new JpaTarget("" + i)); + target = targetManagement.createTarget(entityFactory.target().create().controllerId("" + i)); targets.add(target.getId()); targets.add(createTargetWithAttributes("" + (i * i + 1000)).getId()); } @@ -200,14 +195,13 @@ public void deleteAndCreateTargets() { } private Target createTargetWithAttributes(final String controllerId) { - Target target = new JpaTarget(controllerId); final Map testData = new HashMap<>(); testData.put("test1", "testdata1"); - target = targetManagement.createTarget(target); - target = controllerManagament.updateControllerAttributes(controllerId, testData); + targetManagement.createTarget(entityFactory.target().create().controllerId(controllerId)); + controllerManagament.updateControllerAttributes(controllerId, testData); - target = targetManagement.findTargetByControllerIDWithDetails(controllerId); + final Target target = targetManagement.findTargetByControllerIDWithDetails(controllerId); assertThat(target.getTargetInfo().getControllerAttributes()).as("Controller Attributes are wrong") .isEqualTo(testData); return target; @@ -237,13 +231,11 @@ public void findTargetByControllerIDWithDetails() { final long current = System.currentTimeMillis(); controllerManagament.updateLastTargetQuery("4711", null); - final DistributionSetAssignmentResult result = deploymentManagement.assignDistributionSet(set.getId(), "4711"); + final DistributionSetAssignmentResult result = assignDistributionSet(set.getId(), "4711"); - final JpaAction action = (JpaAction) deploymentManagement.findActionWithDetails(result.getActions().get(0)); - action.setStatus(Status.FINISHED); controllerManagament.addUpdateActionStatus( - new JpaActionStatus(action, Status.FINISHED, System.currentTimeMillis(), "message")); - deploymentManagement.assignDistributionSet(set2.getId(), "4711"); + entityFactory.actionStatus().create(result.getActions().get(0)).status(Status.FINISHED)); + assignDistributionSet(set2.getId(), "4711"); target = targetManagement.findTargetByControllerIDWithDetails("4711"); // read data @@ -273,10 +265,9 @@ public void findTargetByControllerIDWithDetailsReturnsNullForNonexisting() { @Description("Checks if the EntityAlreadyExistsException is thrown if the targets with the same controller ID are created twice.") @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 5) }) public void createMultipleTargetsDuplicate() { - final List targets = testdataFactory.generateTargets(5, "mySimpleTargs", "my simple targets"); - targetManagement.createTargets(targets); + testdataFactory.createTargets(5, "mySimpleTargs", "my simple targets"); try { - targetManagement.createTargets(targets); + testdataFactory.createTargets(5, "mySimpleTargs", "my simple targets"); fail("Targets already exists"); } catch (final EntityAlreadyExistsException e) { } @@ -287,9 +278,9 @@ public void createMultipleTargetsDuplicate() { @Description("Checks if the EntityAlreadyExistsException is thrown if a single target with the same controller ID are created twice.") @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1) }) public void createTargetDuplicate() { - targetManagement.createTarget(new JpaTarget("4711")); + targetManagement.createTarget(entityFactory.target().create().controllerId("4711")); try { - targetManagement.createTarget(new JpaTarget("4711")); + targetManagement.createTarget(entityFactory.target().create().controllerId("4711")); fail("Target already exists"); } catch (final EntityAlreadyExistsException e) { } @@ -351,9 +342,8 @@ private void checkTargetHasNotTags(final Iterable targets, final TargetT public void singleTargetIsInsertedIntoRepo() throws Exception { final String myCtrlID = "myCtrlID"; - final Target target = testdataFactory.generateTarget(myCtrlID, "the description!"); - Target savedTarget = targetManagement.createTarget(target); + Target savedTarget = testdataFactory.createTarget(myCtrlID); assertNotNull("The target should not be null", savedTarget); final Long createdAt = savedTarget.getCreatedAt(); Long modifiedAt = savedTarget.getLastModifiedAt(); @@ -361,11 +351,10 @@ public void singleTargetIsInsertedIntoRepo() throws Exception { assertThat(createdAt).as("CreatedAt compared with modifiedAt").isEqualTo(modifiedAt); assertNotNull("The createdAt attribut of the target should no be null", savedTarget.getCreatedAt()); assertNotNull("The lastModifiedAt attribut of the target should no be null", savedTarget.getLastModifiedAt()); - assertThat(target).as("Target compared with saved target").isEqualTo(savedTarget); - savedTarget.setDescription("changed description"); Thread.sleep(1); - savedTarget = targetManagement.updateTarget(savedTarget); + savedTarget = targetManagement.updateTarget( + entityFactory.target().update(savedTarget.getControllerId()).description("changed description")); assertNotNull("The lastModifiedAt attribute of the target should not be null", savedTarget.getLastModifiedAt()); assertThat(createdAt).as("CreatedAt compared with saved modifiedAt") .isNotEqualTo(savedTarget.getLastModifiedAt()); @@ -391,29 +380,27 @@ public void singleTargetIsInsertedIntoRepo() throws Exception { @Expect(type = TargetDeletedEvent.class, count = 51) }) public void bulkTargetCreationAndDelete() throws Exception { final String myCtrlID = "myCtrlID"; - final List firstList = testdataFactory.generateTargets(100, myCtrlID, "first description"); + List firstList = testdataFactory.createTargets(100, myCtrlID, "first description"); - final Target extra = testdataFactory.generateTarget("myCtrlID-00081XX", "first description"); - - List firstSaved = targetManagement.createTargets(firstList); - - final Target savedExtra = targetManagement.createTarget(extra); + final Target extra = testdataFactory.createTarget("myCtrlID-00081XX"); final Iterable allFound = targetRepository.findAll(); assertThat(Long.valueOf(firstList.size())).as("List size of targets") - .isEqualTo(firstSaved.spliterator().getExactSizeIfKnown()); + .isEqualTo(firstList.spliterator().getExactSizeIfKnown()); assertThat(Long.valueOf(firstList.size() + 1)).as("LastModifiedAt compared with saved lastModifiedAt") .isEqualTo(allFound.spliterator().getExactSizeIfKnown()); // change the objects and save to again to trigger a change on // lastModifiedAt - firstSaved.forEach(t -> t.setName(t.getName().concat("\tchanged"))); - firstSaved = targetManagement.updateTargets(firstSaved); + firstList = firstList.stream() + .map(t -> targetManagement.updateTarget( + entityFactory.target().update(t.getControllerId()).name(t.getName().concat("\tchanged")))) + .collect(Collectors.toList()); // verify that all entries are found _founds: for (final Target foundTarget : allFound) { - for (final Target changedTarget : firstSaved) { + for (final Target changedTarget : firstList) { if (changedTarget.getControllerId().equals(foundTarget.getControllerId())) { assertThat(changedTarget.getDescription()) .as("Description of changed target compared with description saved target") @@ -430,15 +417,15 @@ public void bulkTargetCreationAndDelete() throws Exception { } } - if (!foundTarget.getControllerId().equals(savedExtra.getControllerId())) { + if (!foundTarget.getControllerId().equals(extra.getControllerId())) { fail("The controllerId of the found target is not equal to the controllerId of the saved target"); } } - targetManagement.deleteTargets(savedExtra.getId()); + targetManagement.deleteTargets(extra.getId()); final int numberToDelete = 50; - final Iterable targetsToDelete = limit(firstSaved, numberToDelete); + final Iterable targetsToDelete = limit(firstList, numberToDelete); final Target[] deletedTargets = toArray(targetsToDelete, Target.class); final List targetsIdsToDelete = newArrayList(targetsToDelete.iterator()).stream().map(Target::getId) .collect(toList()); @@ -446,142 +433,28 @@ public void bulkTargetCreationAndDelete() throws Exception { targetManagement.deleteTargets(targetsIdsToDelete); final List targetsLeft = targetManagement.findTargetsAll(new PageRequest(0, 200)).getContent(); - assertThat(firstSaved.spliterator().getExactSizeIfKnown() - numberToDelete).as("Size of splited list") + assertThat(firstList.spliterator().getExactSizeIfKnown() - numberToDelete).as("Size of splited list") .isEqualTo(targetsLeft.spliterator().getExactSizeIfKnown()); assertThat(targetsLeft).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(testdataFactory.generateTargets(100, "myCtrlID", "first description")); - - 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<>(); - attribs2Del.add("x.y.z"); - attribs2Del.add("1.2.3"); - - for (final Target t : ts) { - JpaTargetInfo targetInfo = (JpaTargetInfo) t.getTargetInfo(); - targetInfo.setNew(false); - for (final Entry attrib : attribs.entrySet()) { - final String key = attrib.getKey(); - final String value = String.format("%s-%s", attrib.getValue(), t.getControllerId()); - targetInfo.getControllerAttributes().put(key, value); - } - targetInfo = targetInfoRepository.save(targetInfo); - } - final Query qry = entityManager.createNativeQuery("select * from sp_target_attributes ta"); - final List result = qry.getResultList(); - - assertThat(attribs.size() * ts.spliterator().getExactSizeIfKnown()).as("Amount of all target attributes") - .isEqualTo(result.size()); - - for (final Target myT : ts) { - final Target t = targetManagement.findTargetByControllerIDWithDetails(myT.getControllerId()); - assertThat(attribs.size()).as("Amount of target attributes per target") - .isEqualTo(t.getTargetInfo().getControllerAttributes().size()); - - for (final Entry ca : t.getTargetInfo().getControllerAttributes().entrySet()) { - assertTrue("Attributes list does not contain target attribute key", attribs.containsKey(ca.getKey())); - // has the same value: see string concatenation above - // assertThat(String.format("%s-%s", - // attribs.get(ca.getKey()))).as("Value of string - // concatenation") - // .isEqualTo(ca.getValue()); - - assertEquals("The value of the string concatenation is not equal to the value of the target attributes", - String.format("%s-%s", attribs.get(ca.getKey()), t.getControllerId()), ca.getValue()); - - } - } - - ts = targetManagement.findTargetsAll(new PageRequest(0, 100)).getContent(); - final Iterator tsIt = ts.iterator(); - // all attributs of the target are deleted - final Target[] ts2DelAllAttribs = new Target[] { tsIt.next(), tsIt.next(), tsIt.next() }; - // a few attributs are deleted - final Target[] ts2DelAttribs = new Target[] { tsIt.next(), tsIt.next() }; - - // perform the deletion operations accordingly - for (final Target ta : ts2DelAllAttribs) { - final Target t = targetManagement.findTargetByControllerIDWithDetails(ta.getControllerId()); - - final JpaTargetInfo targetStatus = (JpaTargetInfo) t.getTargetInfo(); - targetStatus.getControllerAttributes().clear(); - targetInfoRepository.save(targetStatus); - } - - for (final Target ta : ts2DelAttribs) { - final Target t = targetManagement.findTargetByControllerIDWithDetails(ta.getControllerId()); - - final JpaTargetInfo targetStatus = (JpaTargetInfo) t.getTargetInfo(); - for (final String attribKey : attribs2Del) { - targetStatus.getControllerAttributes().remove(attribKey); - } - targetInfoRepository.save(targetStatus); - } - - // only the number of the remaining targets and controller attributes - // are checked - final Iterable restTS = targetRepository.findAll(); - - restTarget_: for (final Target targetl : restTS) { - final Target target = targetManagement.findTargetByControllerIDWithDetails(targetl.getControllerId()); - - // verify that all members of the list ts2DelAllAttribs don't have - // any attributes - for (final Target tNoAttribl : ts2DelAllAttribs) { - final Target tNoAttrib = targetManagement.findTargetByControllerID(tNoAttribl.getControllerId()); - - if (tNoAttrib.getControllerId().equals(target.getControllerId())) { - assertThat(target.getTargetInfo().getControllerAttributes()) - .as("Controller attributes should be empty").isEmpty(); - continue restTarget_; - } - } - // verify that that the attribute list of all members of the list - // ts2DelAttribs don't have - // attributes which have been deleted - for (final Target tNoAttribl : ts2DelAttribs) { - final Target tNoAttrib = targetManagement.findTargetByControllerID(tNoAttribl.getControllerId()); - - if (tNoAttrib.getControllerId().equals(target.getControllerId())) { - assertThat(target.getTargetInfo().getControllerAttributes().keySet().toArray()) - .as("Controller attributes are wrong").doesNotContain(attribs2Del.toArray()); - continue restTarget_; - } - } - } - } - @Test @Description("Tests the assigment of tags to the a single target.") @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 2), - @Expect(type = TargetTagCreatedEvent.class, count = 7) }) + @Expect(type = TargetTagCreatedEvent.class, count = 7), + @Expect(type = TargetUpdatedEvent.class, count = 7) }) public void targetTagAssignment() { - final Target t1 = testdataFactory.generateTarget("id-1", "blablub"); + final Target t1 = testdataFactory.createTarget("id-1"); final int noT2Tags = 4; final int noT1Tags = 3; - final List t1Tags = tagManagement - .createTargetTags(testdataFactory.generateTargetTags(noT1Tags, "tag1")); - - t1Tags.forEach(tag -> ((JpaTarget) t1).addTag(tag)); + final List t1Tags = testdataFactory.createTargetTags(noT1Tags, "tag1"); - targetManagement.createTarget(t1); - final Target t2 = testdataFactory.generateTarget("id-2", "blablub"); - final List t2Tags = tagManagement - .createTargetTags(testdataFactory.generateTargetTags(noT2Tags, "tag2")); + t1Tags.forEach(tag -> targetManagement.assignTag(Lists.newArrayList(t1.getControllerId()), tag)); - t2Tags.forEach(tag -> ((JpaTarget) t2).addTag(tag)); - targetManagement.createTarget(t2); + final Target t2 = testdataFactory.createTarget("id-2"); + final List t2Tags = testdataFactory.createTargetTags(noT2Tags, "tag2"); + t2Tags.forEach(tag -> targetManagement.assignTag(Lists.newArrayList(t2.getControllerId()), tag)); final Target t11 = targetManagement.findTargetByControllerID(t1.getControllerId()); assertThat(t11.getTags()).as("Tag size is wrong").hasSize(noT1Tags).containsAll(t1Tags); @@ -600,23 +473,18 @@ public void targetTagAssignment() { @Expect(type = TargetTagCreatedEvent.class, count = 4), @Expect(type = TargetUpdatedEvent.class, count = 80) }) public void targetTagBulkAssignments() { - final List tagATargets = targetManagement - .createTargets(testdataFactory.generateTargets(10, "tagATargets", "first description")); - final List tagBTargets = targetManagement - .createTargets(testdataFactory.generateTargets(10, "tagBTargets", "first description")); - final List tagCTargets = targetManagement - .createTargets(testdataFactory.generateTargets(10, "tagCTargets", "first description")); + final List tagATargets = testdataFactory.createTargets(10, "tagATargets", "first description"); + final List tagBTargets = testdataFactory.createTargets(10, "tagBTargets", "first description"); + final List tagCTargets = testdataFactory.createTargets(10, "tagCTargets", "first description"); - final List tagABTargets = targetManagement - .createTargets(testdataFactory.generateTargets(10, "tagABTargets", "first description")); + final List tagABTargets = testdataFactory.createTargets(10, "tagABTargets", "first description"); - final List tagABCTargets = targetManagement - .createTargets(testdataFactory.generateTargets(10, "tagABCTargets", "first description")); + final List tagABCTargets = testdataFactory.createTargets(10, "tagABCTargets", "first description"); - 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")); + final TargetTag tagA = tagManagement.createTargetTag(entityFactory.tag().create().name("A")); + final TargetTag tagB = tagManagement.createTargetTag(entityFactory.tag().create().name("B")); + final TargetTag tagC = tagManagement.createTargetTag(entityFactory.tag().create().name("C")); + tagManagement.createTargetTag(entityFactory.tag().create().name("X")); // doing different assignments targetManagement.toggleTagAssignment(tagATargets, tagA); @@ -634,9 +502,9 @@ public void targetTagBulkAssignments() { .as("Target count is wrong").isEqualTo(0); // search for targets with tag tagA - final List targetWithTagA = new ArrayList(); - final List targetWithTagB = new ArrayList(); - final List targetWithTagC = new ArrayList(); + final List targetWithTagA = new ArrayList<>(); + final List targetWithTagB = new ArrayList<>(); + final List targetWithTagC = new ArrayList<>(); // storing target lists to enable easy evaluation Iterables.addAll(targetWithTagA, tagATargets); @@ -674,25 +542,18 @@ public void targetTagBulkAssignments() { @Expect(type = TargetCreatedEvent.class, count = 109), @Expect(type = TargetUpdatedEvent.class, count = 227) }) public void targetTagBulkUnassignments() { - 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(testdataFactory.generateTargets(25, "target-id-A", "first description")); - final List targBs = targetManagement - .createTargets(testdataFactory.generateTargets(20, "target-id-B", "first description")); - final List targCs = targetManagement - .createTargets(testdataFactory.generateTargets(15, "target-id-C", "first description")); - - final List targABs = targetManagement - .createTargets(testdataFactory.generateTargets(12, "target-id-AB", "first description")); - final List targACs = targetManagement - .createTargets(testdataFactory.generateTargets(13, "target-id-AC", "first description")); - final List targBCs = targetManagement - .createTargets(testdataFactory.generateTargets(7, "target-id-BC", "first description")); - final List targABCs = targetManagement - .createTargets(testdataFactory.generateTargets(17, "target-id-ABC", "first description")); + final TargetTag targTagA = tagManagement.createTargetTag(entityFactory.tag().create().name("Targ-A-Tag")); + final TargetTag targTagB = tagManagement.createTargetTag(entityFactory.tag().create().name("Targ-B-Tag")); + final TargetTag targTagC = tagManagement.createTargetTag(entityFactory.tag().create().name("Targ-C-Tag")); + + final List targAs = testdataFactory.createTargets(25, "target-id-A", "first description"); + final List targBs = testdataFactory.createTargets(20, "target-id-B", "first description"); + final List targCs = testdataFactory.createTargets(15, "target-id-C", "first description"); + + final List targABs = testdataFactory.createTargets(12, "target-id-AB", "first description"); + final List targACs = testdataFactory.createTargets(13, "target-id-AC", "first description"); + final List targBCs = testdataFactory.createTargets(7, "target-id-BC", "first description"); + final List targABCs = testdataFactory.createTargets(17, "target-id-ABC", "first description"); targetManagement.toggleTagAssignment(targAs, targTagA); targetManagement.toggleTagAssignment(targABs, targTagA); @@ -739,21 +600,20 @@ public void targetTagBulkUnassignments() { @Expect(type = TargetCreatedEvent.class, count = 25), @Expect(type = TargetUpdatedEvent.class, count = 25) }) public void findTargetsByControllerIDsWithTags() { - final TargetTag targTagA = tagManagement.createTargetTag(new JpaTargetTag("Targ-A-Tag")); + final TargetTag targTagA = tagManagement.createTargetTag(entityFactory.tag().create().name("Targ-A-Tag")); - final List targAs = targetManagement - .createTargets(testdataFactory.generateTargets(25, "target-id-A", "first description")); + final List targAs = testdataFactory.createTargets(25, "target-id-A", "first description"); targetManagement.toggleTagAssignment(targAs, targTagA); assertThat(targetManagement.findTargetsByControllerIDsWithTags( - targAs.stream().map(target -> target.getControllerId()).collect(Collectors.toList()))) - .as("Target count is wrong").hasSize(25); + targAs.stream().map(Target::getControllerId).collect(Collectors.toList()))).as("Target count is wrong") + .hasSize(25); // no lazy loading exception and tag correctly assigned assertThat(targetManagement .findTargetsByControllerIDsWithTags( - targAs.stream().map(target -> target.getControllerId()).collect(Collectors.toList())) + targAs.stream().map(Target::getControllerId).collect(Collectors.toList())) .stream().map(target -> target.getTags().contains(targTagA)).collect(Collectors.toList())) .as("Tags not correctly assigned").containsOnly(true); } @@ -762,9 +622,8 @@ public void findTargetsByControllerIDsWithTags() { @Description("Test the optimized quere for retrieving all ID/name pairs of targets.") @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 25) }) public void findAllTargetIdNamePaiss() { - final List targAs = targetManagement - .createTargets(testdataFactory.generateTargets(25, "target-id-A", "first description")); - final String[] createdTargetIds = targAs.stream().map(t -> t.getControllerId()) + final List targAs = testdataFactory.createTargets(25, "target-id-A", "first description"); + final String[] createdTargetIds = targAs.stream().map(Target::getControllerId) .toArray(size -> new String[size]); final List findAllTargetIdNames = targetManagement.findAllTargetIds(); @@ -781,17 +640,15 @@ public void findAllTargetIdNamePaiss() { @Expect(type = TargetUpdatedEvent.class, count = 25) }) public void findTargetsWithNoTag() { - final TargetTag targTagA = tagManagement.createTargetTag(new JpaTargetTag("Targ-A-Tag")); - final List targAs = targetManagement - .createTargets(testdataFactory.generateTargets(25, "target-id-A", "first description")); + final TargetTag targTagA = tagManagement.createTargetTag(entityFactory.tag().create().name("Targ-A-Tag")); + final List targAs = testdataFactory.createTargets(25, "target-id-A", "first description"); targetManagement.toggleTagAssignment(targAs, targTagA); - targetManagement.createTargets(testdataFactory.generateTargets(25, "target-id-B", "first description")); + testdataFactory.createTargets(25, "target-id-B", "first description"); final String[] tagNames = null; final List targetsListWithNoTag = targetManagement - .findTargetByFilters(new PageRequest(0, 500), null, null, null, null, Boolean.TRUE, tagNames) - .getContent(); + .findTargetByFilters(pageReq, null, null, null, null, Boolean.TRUE, tagNames).getContent(); assertThat(50).as("Total targets").isEqualTo(targetManagement.findAllTargetIds().size()); assertThat(25).as("Targets with no tag").isEqualTo(targetsListWithNoTag.size()); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/autoassign/AutoAssignCheckerTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/autoassign/AutoAssignCheckerTest.java index fe0675da11..0495a2c468 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/autoassign/AutoAssignCheckerTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/autoassign/AutoAssignCheckerTest.java @@ -14,8 +14,6 @@ import java.util.stream.Collectors; import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; -import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; -import org.eclipse.hawkbit.repository.jpa.model.JpaTargetFilterQuery; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetFilterQuery; @@ -44,32 +42,34 @@ public class AutoAssignCheckerTest extends AbstractJpaIntegrationTest { @Description("Test auto assignment of a DS to filtered targets") public void checkAutoAssign() { - final DistributionSet setA = testdataFactory.createDistributionSet("dsA"); // will be auto assigned + final DistributionSet setA = testdataFactory.createDistributionSet("dsA"); // will + // be + // auto + // assigned final DistributionSet setB = testdataFactory.createDistributionSet("dsB"); // target filter query that matches all targets - TargetFilterQuery targetFilterQuery = targetFilterQueryManagement - .createTargetFilterQuery(new JpaTargetFilterQuery("filterA", "name==*")); - targetFilterQuery.setAutoAssignDistributionSet(setA); - targetFilterQueryManagement.updateTargetFilterQuery(targetFilterQuery); - + final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement + .createTargetFilterQuery(entityFactory.targetFilterQuery().create().name("filterA").query("name==*")); + targetFilterQueryManagement.updateTargetFilterQueryAutoAssignDS(targetFilterQuery.getId(), setA.getId()); final String targetDsAIdPref = "targ"; - List targets = targetManagement.createTargets( - testdataFactory.generateTargets(100, targetDsAIdPref, targetDsAIdPref.concat(" description"))); - int targetsCount = targets.size(); + final List targets = testdataFactory.createTargets(100, targetDsAIdPref, + targetDsAIdPref.concat(" description")); + final int targetsCount = targets.size(); // assign set A to first 10 targets - deploymentManagement.assignDistributionSet(setA, targets.subList(0, 10)); + assignDistributionSet(setA, targets.subList(0, 10)); verifyThatTargetsHaveDistributionSetAssignment(setA, targets.subList(0, 10), targetsCount); // assign set B to first 5 targets - // they have now 2 DS in their action history and should not get updated with dsA - deploymentManagement.assignDistributionSet(setB, targets.subList(0, 5)); + // they have now 2 DS in their action history and should not get updated + // with dsA + assignDistributionSet(setB, targets.subList(0, 5)); verifyThatTargetsHaveDistributionSetAssignment(setB, targets.subList(0, 5), targetsCount); // assign set B to next 10 targets - deploymentManagement.assignDistributionSet(setB, targets.subList(10, 20)); + assignDistributionSet(setB, targets.subList(10, 20)); verifyThatTargetsHaveDistributionSetAssignment(setB, targets.subList(10, 20), targetsCount); // Count the number of targets that will be assigned with setA @@ -91,9 +91,8 @@ public void checkAutoAssign() { public void checkAutoAssignWithFailures() { // incomplete distribution set that will be assigned - final DistributionSet setF = distributionSetManagement - .createDistributionSet(entityFactory.generateDistributionSet("dsA", "1", "incomplete ds", - testdataFactory.findOrCreateDefaultTestDsType(), null)); + final DistributionSet setF = distributionSetManagement.createDistributionSet(entityFactory.distributionSet() + .create().name("dsA").version("1").type(testdataFactory.findOrCreateDefaultTestDsType())); final DistributionSet setA = testdataFactory.createDistributionSet("dsA"); final DistributionSet setB = testdataFactory.createDistributionSet("dsB"); @@ -102,23 +101,27 @@ public void checkAutoAssignWithFailures() { // target filter query that matches first bunch of targets, that should // fail - targetFilterQueryManagement.createTargetFilterQuery( - new JpaTargetFilterQuery("filterA", "id==" + targetDsFIdPref + "*", (JpaDistributionSet) setF)); + targetFilterQueryManagement.updateTargetFilterQueryAutoAssignDS( + targetFilterQueryManagement.createTargetFilterQuery(entityFactory.targetFilterQuery().create() + .name("filterA").query("id==" + targetDsFIdPref + "*")).getId(), + setF.getId()); // target filter query that matches failed bunch of targets - targetFilterQueryManagement.createTargetFilterQuery( - new JpaTargetFilterQuery("filterB", "id==" + targetDsAIdPref + "*", (JpaDistributionSet) setA)); + targetFilterQueryManagement.updateTargetFilterQueryAutoAssignDS( + targetFilterQueryManagement.createTargetFilterQuery(entityFactory.targetFilterQuery().create() + .name("filterB").query("id==" + targetDsAIdPref + "*")).getId(), + setA.getId()); - List targetsF = targetManagement.createTargets( - testdataFactory.generateTargets(10, targetDsFIdPref, targetDsFIdPref.concat(" description"))); + final List targetsF = testdataFactory.createTargets(10, targetDsFIdPref, + targetDsFIdPref.concat(" description")); - List targetsA = targetManagement.createTargets( - testdataFactory.generateTargets(10, targetDsAIdPref, targetDsAIdPref.concat(" description"))); + final List targetsA = testdataFactory.createTargets(10, targetDsAIdPref, + targetDsAIdPref.concat(" description")); - int targetsCount = targetsA.size() + targetsF.size(); + final int targetsCount = targetsA.size() + targetsF.size(); // assign set B to first 5 targets of fail group - deploymentManagement.assignDistributionSet(setB, targetsF.subList(0, 5)); + assignDistributionSet(setB, targetsF.subList(0, 5)); verifyThatTargetsHaveDistributionSetAssignment(setB, targetsF.subList(0, 5), targetsCount); // Run the check @@ -133,18 +136,21 @@ public void checkAutoAssignWithFailures() { } /** - * @param set the expected distribution set - * @param targets the targets that should have it + * @param set + * the expected distribution set + * @param targets + * the targets that should have it */ @Step - private void verifyThatTargetsHaveDistributionSetAssignment(final DistributionSet set, List targets, int count) { - List targetIds = targets.stream().map(Target::getId).collect(Collectors.toList()); + private void verifyThatTargetsHaveDistributionSetAssignment(final DistributionSet set, final List targets, + final int count) { + final List targetIds = targets.stream().map(Target::getId).collect(Collectors.toList()); - Slice targetsAll = targetManagement.findTargetsAll(new PageRequest(0, 1000)); + final Slice targetsAll = targetManagement.findTargetsAll(new PageRequest(0, 1000)); assertThat(targetsAll).as("Count of targets").hasSize(count); - for (Target target : targetsAll) { - if(targetIds.contains(target.getId())) { + for (final Target target : targetsAll) { + if (targetIds.contains(target.getId())) { assertThat(target.getAssignedDistributionSet()).as("assigned DS").isEqualTo(set); } } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/event/RepositoryEntityEventTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/event/RepositoryEntityEventTest.java index 507347e63b..7628f9a468 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/event/RepositoryEntityEventTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/event/RepositoryEntityEventTest.java @@ -52,7 +52,7 @@ public void beforeTest() { @Test @Description("Verifies that the target created event is published when a target has been created") public void targetCreatedEventIsPublished() throws InterruptedException { - final Target createdTarget = targetManagement.createTarget(entityFactory.generateTarget("12345")); + final Target createdTarget = testdataFactory.createTarget("12345"); final TargetCreatedEvent targetCreatedEvent = eventListener.waitForEvent(TargetCreatedEvent.class, 1, TimeUnit.SECONDS); @@ -63,9 +63,9 @@ public void targetCreatedEventIsPublished() throws InterruptedException { @Test @Description("Verifies that the target update event is published when a target has been updated") public void targetUpdateEventIsPublished() throws InterruptedException { - final Target createdTarget = targetManagement.createTarget(entityFactory.generateTarget("12345")); - createdTarget.setName("updateName"); - targetManagement.updateTarget(createdTarget); + final Target createdTarget = testdataFactory.createTarget("12345"); + targetManagement + .updateTarget(entityFactory.target().update(createdTarget.getControllerId()).name("updateName")); final TargetUpdatedEvent targetUpdatedEvent = eventListener.waitForEvent(TargetUpdatedEvent.class, 1, TimeUnit.SECONDS); @@ -76,7 +76,7 @@ public void targetUpdateEventIsPublished() throws InterruptedException { @Test @Description("Verifies that the target deleted event is published when a target has been deleted") public void targetDeletedEventIsPublished() throws InterruptedException { - final Target createdTarget = targetManagement.createTarget(entityFactory.generateTarget("12345")); + final Target createdTarget = testdataFactory.createTarget("12345"); targetManagement.deleteTargets(createdTarget.getId()); @@ -89,11 +89,7 @@ public void targetDeletedEventIsPublished() throws InterruptedException { @Test @Description("Verifies that the distribution set created event is published when a distribution set has been created") public void distributionSetCreatedEventIsPublished() throws InterruptedException { - final DistributionSet generateDistributionSet = entityFactory.generateDistributionSet(); - generateDistributionSet.setName("dsEventTest"); - generateDistributionSet.setVersion("1"); - final DistributionSet createDistributionSet = distributionSetManagement - .createDistributionSet(generateDistributionSet); + final DistributionSet createDistributionSet = testdataFactory.createDistributionSet(); final DistributionSetCreatedEvent dsCreatedEvent = eventListener.waitForEvent(DistributionSetCreatedEvent.class, 1, TimeUnit.SECONDS); @@ -104,12 +100,7 @@ public void distributionSetCreatedEventIsPublished() throws InterruptedException @Test @Description("Verifies that the distribution set deleted event is published when a distribution set has been deleted") public void distributionSetDeletedEventIsPublished() throws InterruptedException { - - final DistributionSet generateDistributionSet = entityFactory.generateDistributionSet(); - generateDistributionSet.setName("dsEventTest"); - generateDistributionSet.setVersion("1"); - final DistributionSet createDistributionSet = distributionSetManagement - .createDistributionSet(generateDistributionSet); + final DistributionSet createDistributionSet = testdataFactory.createDistributionSet(); distributionSetManagement.deleteDistributionSet(createDistributionSet); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/model/EntityInterceptorListenerTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/model/EntityInterceptorListenerTest.java index 946661e8c4..76fcdf7a63 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/model/EntityInterceptorListenerTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/model/EntityInterceptorListenerTest.java @@ -52,9 +52,7 @@ public void postLoadIsCalledWhenLoadATarget() { final PostLoadEntityListener postLoadEntityListener = new PostLoadEntityListener(); EntityInterceptorHolder.getInstance().getEntityInterceptors().add(postLoadEntityListener); - final Target targetToBeCreated = entityFactory.generateTarget("targetToBeCreated"); - - targetManagement.createTarget(targetToBeCreated); + final Target targetToBeCreated = testdataFactory.createTarget("targetToBeCreated"); final Target loadedTarget = targetManagement.findTargetByControllerID(targetToBeCreated.getControllerId()); assertThat(postLoadEntityListener.getEntity()).isNotNull(); @@ -86,19 +84,17 @@ public void postRemoveIsCalledWhenDeletingATarget() { } private void executePersistAndAssertCallbackResult(final AbstractEntityListener entityInterceptor) { - final Target targetToBeCreated = entityFactory.generateTarget("targetToBeCreated"); - addListenerAndCreateTarget(entityInterceptor, targetToBeCreated); + final Target targetToBeCreated = addListenerAndCreateTarget(entityInterceptor, "targetToBeCreated"); assertThat(entityInterceptor.getEntity()).isNotNull(); assertThat(entityInterceptor.getEntity()).isEqualTo(targetToBeCreated); } private void executeUpdateAndAssertCallbackResult(final AbstractEntityListener entityInterceptor) { - Target updateTarget = addListenerAndCreateTarget(entityInterceptor, - entityFactory.generateTarget("targetToBeCreated")); - updateTarget.setDescription("New"); + Target updateTarget = addListenerAndCreateTarget(entityInterceptor, "targetToBeCreated"); - updateTarget = targetManagement.updateTarget(updateTarget); + updateTarget = targetManagement + .updateTarget(entityFactory.target().update(updateTarget.getControllerId()).name("New")); assertThat(entityInterceptor.getEntity()).isNotNull(); assertThat(entityInterceptor.getEntity()).isEqualTo(updateTarget); @@ -107,7 +103,7 @@ private void executeUpdateAndAssertCallbackResult(final AbstractEntityListener e private void executeDeleteAndAssertCallbackResult(final AbstractEntityListener entityInterceptor) { EntityInterceptorHolder.getInstance().getEntityInterceptors().add(entityInterceptor); final SoftwareModuleType type = softwareManagement - .createSoftwareModuleType(entityFactory.generateSoftwareModuleType("test", "test", "test", 1)); + .createSoftwareModuleType(entityFactory.softwareModuleType().create().name("test").key("test")); softwareManagement.deleteSoftwareModuleType(type); assertThat(entityInterceptor.getEntity()).isNotNull(); @@ -115,12 +111,12 @@ private void executeDeleteAndAssertCallbackResult(final AbstractEntityListener e } private Target addListenerAndCreateTarget(final AbstractEntityListener entityInterceptor, - final Target targetToBeCreated) { + final String targetToBeCreated) { EntityInterceptorHolder.getInstance().getEntityInterceptors().add(entityInterceptor); - return targetManagement.createTarget(targetToBeCreated); + return testdataFactory.createTarget(targetToBeCreated); } - private static abstract class AbstractEntityListener implements EntityInterceptor { + private abstract static class AbstractEntityListener implements EntityInterceptor { private Object entity; @@ -183,4 +179,4 @@ public void postRemove(final Object entity) { setEntity(entity); } } -} \ No newline at end of file +} diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/model/ModelEqualsHashcodeTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/model/ModelEqualsHashcodeTest.java index 9f4cefa5d2..48e49425fa 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/model/ModelEqualsHashcodeTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/model/ModelEqualsHashcodeTest.java @@ -56,20 +56,20 @@ public void differentEntitiesAreNotEqual() { @Description("Verfies that updated entities are not equal.") public void changedEntitiesAreNotEqual() { final SoftwareModuleType type = softwareManagement - .createSoftwareModuleType(new JpaSoftwareModuleType("test", "test", "test", 1)); + .createSoftwareModuleType(entityFactory.softwareModuleType().create().key("test").name("test")); assertThat(type).as("persited entity is not equal to regular object") - .isNotEqualTo(new JpaSoftwareModuleType("test", "test", "test", 1)); + .isNotEqualTo(entityFactory.softwareModuleType().create().key("test").name("test").build()); - type.setDescription("another"); - final SoftwareModuleType updated = softwareManagement.updateSoftwareModuleType(type); + final SoftwareModuleType updated = softwareManagement.updateSoftwareModuleType( + entityFactory.softwareModuleType().update(type.getId()).description("another")); assertThat(type).as("Changed entity is not equal to the previous version").isNotEqualTo(updated); } @Test @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 JpaSoftwareModuleType("test", "test", "test", 1)); + final SoftwareModuleType type = softwareManagement.createSoftwareModuleType( + entityFactory.softwareModuleType().create().key("test").name("test").description("test")); final JpaSoftwareModuleType mock = new JpaSoftwareModuleType("test", "test", "test", 1); mock.setId(type.getId()); @@ -81,23 +81,4 @@ public void managedEntityIsEqualToUnamangedObjectWithSameKey() { .isEqualTo(mock.hashCode()); } - @Test - @Description("Verfies that updated entities do not have the same hashcode.") - public void updatedEntitiesHaveDifferentHashcodes() { - final SoftwareModuleType type = softwareManagement - .createSoftwareModuleType(new JpaSoftwareModuleType("test", "test", "test", 1)); - assertThat(type.hashCode()).as("persited entity does not have same hashcode as regular object") - .isNotEqualTo(new JpaSoftwareModuleType("test", "test", "test", 1).hashCode()); - - final int beforeChange = type.hashCode(); - type.setDescription("another"); - assertThat(type.hashCode()) - .as("Changed entity has no different hashcode than the previous version until updated in repository") - .isEqualTo(beforeChange); - - final SoftwareModuleType updated = softwareManagement.updateSoftwareModuleType(type); - assertThat(type.hashCode()).as("Updated entity has different hashcode than the previous version") - .isNotEqualTo(updated.hashCode()); - } - } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLActionFieldsTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLActionFieldsTest.java index 7afc46d5ab..78c889f5de 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLActionFieldsTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLActionFieldsTest.java @@ -38,9 +38,8 @@ public class RSQLActionFieldsTest extends AbstractJpaIntegrationTest { @Before public void setupBeforeTest() { final DistributionSet dsA = testdataFactory.createDistributionSet("daA"); - target = new JpaTarget("targetId123"); - target.setDescription("targetId123"); - targetManagement.createTarget(target); + target = (JpaTarget) targetManagement + .createTarget(entityFactory.target().create().controllerId("targetId123").description("targetId123")); action = new JpaAction(); action.setActionType(ActionType.SOFT); action.setDistributionSet(dsA); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetFieldTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetFieldTest.java index 4eb15a78d4..4dadbaf54c 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetFieldTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetFieldTest.java @@ -16,8 +16,6 @@ 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.DistributionSetTag; import org.eclipse.hawkbit.repository.test.util.TestdataFactory; @@ -38,22 +36,21 @@ public class RSQLDistributionSetFieldTest extends AbstractJpaIntegrationTest { public void seuptBeforeTest() { DistributionSet ds = testdataFactory.createDistributionSet("DS"); - ds.setDescription("DS"); - ds = distributionSetManagement.updateDistributionSet(ds); - distributionSetManagement - .createDistributionSetMetadata(new JpaDistributionSetMetadata("metaKey", ds, "metaValue")); + ds = distributionSetManagement + .updateDistributionSet(entityFactory.distributionSet().update(ds.getId()).description("DS")); + createDistributionSetMetadata(ds.getId(), entityFactory.generateMetadata("metaKey", "metaValue")); DistributionSet ds2 = testdataFactory.createDistributionSets("NewDS", 3).get(0); - ds2.setDescription("DS%"); - ds2 = distributionSetManagement.updateDistributionSet(ds2); - distributionSetManagement - .createDistributionSetMetadata(new JpaDistributionSetMetadata("metaKey", ds2, "value")); + ds2 = distributionSetManagement + .updateDistributionSet(entityFactory.distributionSet().update(ds2.getId()).description("DS%")); + createDistributionSetMetadata(ds2.getId(), entityFactory.generateMetadata("metaKey", "value")); - final DistributionSetTag targetTag = tagManagement.createDistributionSetTag(new JpaDistributionSetTag("Tag1")); - tagManagement.createDistributionSetTag(new JpaDistributionSetTag("Tag2")); - tagManagement.createDistributionSetTag(new JpaDistributionSetTag("Tag3")); - tagManagement.createDistributionSetTag(new JpaDistributionSetTag("Tag4")); + final DistributionSetTag targetTag = tagManagement + .createDistributionSetTag(entityFactory.tag().create().name("Tag1")); + tagManagement.createDistributionSetTag(entityFactory.tag().create().name("Tag2")); + tagManagement.createDistributionSetTag(entityFactory.tag().create().name("Tag3")); + tagManagement.createDistributionSetTag(entityFactory.tag().create().name("Tag4")); distributionSetManagement.assignTag(Arrays.asList(ds.getId(), ds2.getId()), targetTag); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetMetadataFieldsTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetMetadataFieldsTest.java index 65b6776938..b62a41e681 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetMetadataFieldsTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetMetadataFieldsTest.java @@ -15,9 +15,9 @@ 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.eclipse.hawkbit.repository.model.MetaData; import org.junit.Before; import org.junit.Test; import org.springframework.data.domain.Page; @@ -38,12 +38,12 @@ public void setupBeforeTest() { final DistributionSet distributionSet = testdataFactory.createDistributionSet("DS"); distributionSetId = distributionSet.getId(); - final List metadata = new ArrayList<>(); + final List metadata = new ArrayList<>(5); for (int i = 0; i < 5; i++) { - metadata.add(new JpaDistributionSetMetadata("" + i, distributionSet, "" + i)); + metadata.add(entityFactory.generateMetadata("" + i, "" + i)); } - distributionSetManagement.createDistributionSetMetadata(metadata); + distributionSetManagement.createDistributionSetMetadata(distributionSetId, metadata); } @Test diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLRolloutGroupFields.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLRolloutGroupFields.java index fd48aed94f..99254aca02 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLRolloutGroupFields.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLRolloutGroupFields.java @@ -12,7 +12,6 @@ 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; @@ -37,7 +36,7 @@ public class RSQLRolloutGroupFields extends AbstractJpaIntegrationTest { @Before public void seuptBeforeTest() { final int amountTargets = 20; - targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); + testdataFactory.createTargets(amountTargets, "rollout", "rollout"); final DistributionSet dsA = testdataFactory.createDistributionSet(""); rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*"); rollout = rolloutManagement.findRolloutById(rollout.getId()); @@ -83,11 +82,11 @@ private void assertRSQLQuery(final String rsqlParam, final long expcetedTargets) private Rollout createRollout(final String name, final int amountGroups, final long distributionSetId, final String targetFilterQuery) { - final Rollout rollout = new JpaRollout(); - rollout.setDistributionSet(distributionSetManagement.findDistributionSetById(distributionSetId)); - rollout.setName(name); - rollout.setTargetFilterQuery(targetFilterQuery); - return rolloutManagement.createRollout(rollout, amountGroups, new RolloutGroupConditionBuilder() - .successCondition(RolloutGroupSuccessCondition.THRESHOLD, "100").build()); + return rolloutManagement.createRollout( + entityFactory.rollout().create() + .set(distributionSetManagement.findDistributionSetById(distributionSetId)).name(name) + .targetFilterQuery(targetFilterQuery), + amountGroups, new RolloutGroupConditionBuilder().withDefaults() + .successCondition(RolloutGroupSuccessCondition.THRESHOLD, "100").build()); } } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleFieldTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleFieldTest.java index 25897ccdec..22b7714251 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleFieldTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleFieldTest.java @@ -13,9 +13,8 @@ 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.MetaData; import org.eclipse.hawkbit.repository.model.SoftwareModule; -import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; import org.eclipse.hawkbit.repository.test.util.TestdataFactory; import org.junit.Before; import org.junit.Test; @@ -32,19 +31,21 @@ public class RSQLSoftwareModuleFieldTest extends AbstractJpaIntegrationTest { @Before public void setupBeforeTest() { - 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 ah = softwareManagement.createSoftwareModule(entityFactory.softwareModule().create() + .type(appType).name("agent-hub").version("1.0.1").description("agent-hub")); + softwareManagement.createSoftwareModule(entityFactory.softwareModule().create().type(runtimeType) + .name("oracle-jre").version("1.7.2").description("aa")); + softwareManagement.createSoftwareModule( + entityFactory.softwareModule().create().type(osType).name("poky").version("3.0.2").description("aa")); - final JpaSoftwareModule ah2 = (JpaSoftwareModule) softwareManagement - .createSoftwareModule(new JpaSoftwareModule(appType, "agent-hub2", "1.0.1", "agent-hub2", "")); + final JpaSoftwareModule ah2 = (JpaSoftwareModule) softwareManagement.createSoftwareModule(entityFactory + .softwareModule().create().type(appType).name("agent-hub2").version("1.0.1").description("agent-hub2")); - final SoftwareModuleMetadata softwareModuleMetadata = new JpaSoftwareModuleMetadata("metaKey", ah, "metaValue"); - softwareManagement.createSoftwareModuleMetadata(softwareModuleMetadata); + final MetaData softwareModuleMetadata = entityFactory.generateMetadata("metaKey", "metaValue"); + softwareManagement.createSoftwareModuleMetadata(ah.getId(), softwareModuleMetadata); - final SoftwareModuleMetadata softwareModuleMetadata2 = new JpaSoftwareModuleMetadata("metaKey", ah2, "value"); - softwareManagement.createSoftwareModuleMetadata(softwareModuleMetadata2); + final MetaData softwareModuleMetadata2 = entityFactory.generateMetadata("metaKey", "value"); + softwareManagement.createSoftwareModuleMetadata(ah2.getId(), softwareModuleMetadata2); } @Test diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleMetadataFieldsTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleMetadataFieldsTest.java index e04ee8c9b8..2775aed027 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleMetadataFieldsTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleMetadataFieldsTest.java @@ -15,7 +15,7 @@ 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.MetaData; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; import org.eclipse.hawkbit.repository.test.util.TestdataFactory; @@ -40,12 +40,12 @@ public void setupBeforeTest() { softwareModuleId = softwareModule.getId(); - final List metadata = new ArrayList<>(); + final List metadata = new ArrayList<>(5); for (int i = 0; i < 5; i++) { - metadata.add(new JpaSoftwareModuleMetadata("" + i, softwareModule, "" + i)); + metadata.add(entityFactory.generateMetadata("" + i, "" + i)); } - softwareManagement.createSoftwareModuleMetadata(metadata); + softwareManagement.createSoftwareModuleMetadata(softwareModule.getId(), metadata); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTagFieldsTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTagFieldsTest.java index 3772bb372e..7781283d54 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTagFieldsTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTagFieldsTest.java @@ -11,9 +11,8 @@ import static org.fest.assertions.api.Assertions.assertThat; import org.eclipse.hawkbit.repository.TagFields; +import org.eclipse.hawkbit.repository.builder.TagCreate; 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; @@ -33,11 +32,10 @@ public class RSQLTagFieldsTest extends AbstractJpaIntegrationTest { public void seuptBeforeTest() { for (int i = 0; i < 5; i++) { - final TargetTag targetTag = new JpaTargetTag("" + i, "" + i, i % 2 == 0 ? "red" : "blue"); + final TagCreate targetTag = entityFactory.tag().create().name(Integer.toString(i)) + .description(Integer.toString(i)).colour(i % 2 == 0 ? "red" : "blue"); tagManagement.createTargetTag(targetTag); - final DistributionSetTag distributionSetTag = new JpaDistributionSetTag("" + i, "" + i, - i % 2 == 0 ? "red" : "blue"); - tagManagement.createDistributionSetTag(distributionSetTag); + tagManagement.createDistributionSetTag(targetTag); } } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTargetFieldTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTargetFieldTest.java index cdac516142..a6099c56e4 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTargetFieldTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTargetFieldTest.java @@ -12,18 +12,15 @@ import static org.junit.Assert.fail; import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; 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.test.util.TestdataFactory; import org.junit.Before; import org.junit.Test; @@ -37,40 +34,39 @@ @Features("Component Tests - Repository") @Stories("RSQL filter target") public class RSQLTargetFieldTest extends AbstractJpaIntegrationTest { - private static final long LAST_TARGET_QUERY = 10000; - private static final long LAST_TARGET_QUERY_SMALLER = 1000; + + private Target target; + private Target target2; @Before - public void seuptBeforeTest() { + public void seuptBeforeTest() throws InterruptedException { final DistributionSet ds = testdataFactory.createDistributionSet("AssignedDs"); - final Target target = entityFactory.generateTarget("targetId123"); - target.setDescription("targetId123"); - final TargetInfo targetInfo = target.getTargetInfo(); - targetInfo.getControllerAttributes().put("revision", "1.1"); - ((JpaTargetInfo) target.getTargetInfo()).setUpdateStatus(TargetUpdateStatus.PENDING); - ((JpaTargetInfo) target.getTargetInfo()).setLastTargetQuery(LAST_TARGET_QUERY); - targetManagement.createTarget(target); - - final JpaTarget target2 = new JpaTarget("targetId1234"); - target2.setDescription("targetId1234"); - final TargetInfo targetInfo2 = target2.getTargetInfo(); - targetInfo2.getControllerAttributes().put("revision", "1.2"); - ((JpaTargetInfo) target2.getTargetInfo()).setLastTargetQuery(LAST_TARGET_QUERY_SMALLER); - targetManagement.createTarget(target2); - - targetManagement.createTarget(new JpaTarget("targetId1235")); - targetManagement.createTarget(new JpaTarget("targetId1236")); - - final TargetTag targetTag = tagManagement.createTargetTag(new JpaTargetTag("Tag1")); - tagManagement.createTargetTag(new JpaTargetTag("Tag2")); - tagManagement.createTargetTag(new JpaTargetTag("Tag3")); - tagManagement.createTargetTag(new JpaTargetTag("Tag4")); + final Map attributes = new HashMap<>(); + + target = targetManagement.createTarget(entityFactory.target().create().controllerId("targetId123") + .name("targetName123").description("targetDesc123")); + attributes.put("revision", "1.1"); + target = controllerManagament.updateControllerAttributes(target.getControllerId(), attributes); + + target2 = targetManagement + .createTarget(entityFactory.target().create().controllerId("targetId1234").description("targetId1234")); + attributes.put("revision", "1.2"); + Thread.sleep(1); + target2 = controllerManagament.updateControllerAttributes(target2.getControllerId(), attributes); + + testdataFactory.createTarget("targetId1235"); + testdataFactory.createTarget("targetId1236"); + + final TargetTag targetTag = tagManagement.createTargetTag(entityFactory.tag().create().name("Tag1")); + tagManagement.createTargetTag(entityFactory.tag().create().name("Tag2")); + tagManagement.createTargetTag(entityFactory.tag().create().name("Tag3")); + tagManagement.createTargetTag(entityFactory.tag().create().name("Tag4")); targetManagement.assignTag(Arrays.asList(target.getControllerId(), target2.getControllerId()), targetTag); - deploymentManagement.assignDistributionSet(ds.getId(), target.getControllerId()); + assignDistributionSet(ds.getId(), target.getControllerId()); } @Test @@ -86,21 +82,21 @@ public void testFilterByParameterId() { @Test @Description("Test filter target by name") public void testFilterByParameterName() { - assertRSQLQuery(TargetFields.NAME.name() + "==targetId123", 1); + assertRSQLQuery(TargetFields.NAME.name() + "==targetName123", 1); assertRSQLQuery(TargetFields.NAME.name() + "==target*", 4); assertRSQLQuery(TargetFields.NAME.name() + "==noExist*", 0); - assertRSQLQuery(TargetFields.NAME.name() + "=in=(targetId123,notexist)", 1); - assertRSQLQuery(TargetFields.NAME.name() + "=out=(targetId123,notexist)", 3); + assertRSQLQuery(TargetFields.NAME.name() + "=in=(targetName123,notexist)", 1); + assertRSQLQuery(TargetFields.NAME.name() + "=out=(targetName123,notexist)", 3); } @Test @Description("Test filter target by description") public void testFilterByParameterDescription() { - assertRSQLQuery(TargetFields.DESCRIPTION.name() + "==targetId123", 1); + assertRSQLQuery(TargetFields.DESCRIPTION.name() + "==targetDesc123", 1); assertRSQLQuery(TargetFields.DESCRIPTION.name() + "==target*", 2); assertRSQLQuery(TargetFields.DESCRIPTION.name() + "==noExist*", 0); - assertRSQLQuery(TargetFields.DESCRIPTION.name() + "=in=(targetId123,notexist)", 1); - assertRSQLQuery(TargetFields.DESCRIPTION.name() + "=out=(targetId123,notexist)", 1); + assertRSQLQuery(TargetFields.DESCRIPTION.name() + "=in=(targetDesc123,notexist)", 1); + assertRSQLQuery(TargetFields.DESCRIPTION.name() + "=out=(targetDesc123,notexist)", 1); } @Test @@ -172,13 +168,19 @@ public void testFilterByTag() { @Test @Description("Test filter target by lastTargetQuery") - public void testFilterByLastTargetQuery() { - assertRSQLQuery(TargetFields.LASTCONTROLLERREQUESTAT.name() + "==" + LAST_TARGET_QUERY, 1); - assertRSQLQuery(TargetFields.LASTCONTROLLERREQUESTAT.name() + "!=" + LAST_TARGET_QUERY, 1); - assertRSQLQuery(TargetFields.LASTCONTROLLERREQUESTAT.name() + "=lt=" + LAST_TARGET_QUERY, 1); - assertRSQLQuery(TargetFields.LASTCONTROLLERREQUESTAT.name() + "=lt=" + LAST_TARGET_QUERY_SMALLER, 0); - assertRSQLQuery(TargetFields.LASTCONTROLLERREQUESTAT.name() + "=gt=" + LAST_TARGET_QUERY_SMALLER, 1); - assertRSQLQuery(TargetFields.LASTCONTROLLERREQUESTAT.name() + "=gt=" + LAST_TARGET_QUERY, 0); + public void testFilterByLastTargetQuery() throws InterruptedException { + assertRSQLQuery( + TargetFields.LASTCONTROLLERREQUESTAT.name() + "==" + target.getTargetInfo().getLastTargetQuery(), 1); + assertRSQLQuery( + TargetFields.LASTCONTROLLERREQUESTAT.name() + "!=" + target.getTargetInfo().getLastTargetQuery(), 1); + assertRSQLQuery( + TargetFields.LASTCONTROLLERREQUESTAT.name() + "=lt=" + target.getTargetInfo().getLastTargetQuery(), 0); + assertRSQLQuery( + TargetFields.LASTCONTROLLERREQUESTAT.name() + "=lt=" + target2.getTargetInfo().getLastTargetQuery(), 1); + assertRSQLQuery( + TargetFields.LASTCONTROLLERREQUESTAT.name() + "=gt=" + target.getTargetInfo().getLastTargetQuery(), 1); + assertRSQLQuery( + TargetFields.LASTCONTROLLERREQUESTAT.name() + "=gt=" + target2.getTargetInfo().getLastTargetQuery(), 0); } private void assertRSQLQuery(final String rsqlParam, final long expcetedTargets) { diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLUtilityTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLUtilityTest.java index 691a659c54..90c8d9b33c 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLUtilityTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLUtilityTest.java @@ -9,8 +9,15 @@ package org.eclipse.hawkbit.repository.jpa.rsql; import static org.junit.Assert.fail; -import static org.mockito.Matchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mockStatic; import javax.persistence.criteria.CriteriaBuilder; @@ -38,9 +45,9 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; - import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; + import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/VirtualPropertyResolverTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/VirtualPropertyResolverTest.java index 87b2c90187..349b7e3eab 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/VirtualPropertyResolverTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/VirtualPropertyResolverTest.java @@ -8,10 +8,10 @@ */ package org.eclipse.hawkbit.repository.jpa.rsql; -import static org.junit.Assert.*; -import static org.mockito.Mockito.when; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mockStatic; import java.time.Instant; @@ -22,15 +22,14 @@ import org.eclipse.hawkbit.repository.model.TenantConfigurationValue; import org.eclipse.hawkbit.repository.rsql.VirtualPropertyResolver; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; - import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; + import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/tenancy/MultiTenancyEntityTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/tenancy/MultiTenancyEntityTest.java index 52f3141710..99665f21eb 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/tenancy/MultiTenancyEntityTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/tenancy/MultiTenancyEntityTest.java @@ -11,9 +11,6 @@ import static org.fest.assertions.api.Assertions.assertThat; 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.Target; import org.eclipse.hawkbit.repository.test.util.WithSpringAuthorityRule; @@ -139,16 +136,12 @@ public void deleteTargetFromOtherTenantIsNotPossible() throws Exception { @Description(value = "Ensures that multiple distribution sets with same name and version can be created for different tenants.") public void createMultipleDistributionSetsWithSameNameForDifferentTenants() throws Exception { - // known ds name for overall tenants same - final String knownDistributionSetName = "dsName"; - final String knownDistributionSetVersion = "0.0.0"; - // known tenant names final String tenant = "aTenant"; final String anotherTenant = "anotherTenant"; // create distribution sets - createDistributionSetForTenant(knownDistributionSetName, knownDistributionSetVersion, tenant); - createDistributionSetForTenant(knownDistributionSetName, knownDistributionSetVersion, anotherTenant); + createDistributionSetForTenant(tenant); + createDistributionSetForTenant(anotherTenant); // ensure both tenants see their distribution sets final Page findDistributionSetsForTenant = findDistributionSetForTenant(tenant); @@ -164,7 +157,7 @@ public void createMultipleDistributionSetsWithSameNameForDifferentTenants() thro private Target createTargetForTenant(final String controllerId, final String tenant) throws Exception { return securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant), - () -> targetManagement.createTarget(new JpaTarget(controllerId))); + () -> testdataFactory.createTarget(controllerId)); } private Slice findTargetsForTenant(final String tenant) throws Exception { @@ -179,22 +172,14 @@ private void deleteTargetsForTenant(final String tenant, final Long... targetIds }); } - private DistributionSet createDistributionSetForTenant(final String name, final String version, final String tenant) - throws Exception { - return securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant), () -> { - final JpaDistributionSet ds = new JpaDistributionSet(); - ds.setName(name); - ds.setTenant(tenant); - ds.setVersion(version); - ds.setType(distributionSetManagement - .createDistributionSetType(new JpaDistributionSetType("typetest", "test", "foobar"))); - return distributionSetManagement.createDistributionSet(ds); - }); + private DistributionSet createDistributionSetForTenant(final String tenant) throws Exception { + return securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant), + () -> testdataFactory.createDistributionSet()); } private Page findDistributionSetForTenant(final String tenant) throws Exception { return securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant), - () -> distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, false)); + () -> distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)); } } diff --git a/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/AbstractIntegrationTest.java b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/AbstractIntegrationTest.java index 7c8fb8150c..1b35986610 100644 --- a/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/AbstractIntegrationTest.java +++ b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/AbstractIntegrationTest.java @@ -14,6 +14,9 @@ import java.io.File; import java.io.IOException; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; import org.apache.commons.io.FileUtils; import org.eclipse.hawkbit.ExcludePathAwareShallowETagFilter; @@ -35,8 +38,22 @@ import org.eclipse.hawkbit.repository.TargetFilterQueryManagement; import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; +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.DistributionSetAssignmentResult; +import org.eclipse.hawkbit.repository.model.DistributionSetMetadata; import org.eclipse.hawkbit.repository.model.DistributionSetType; +import org.eclipse.hawkbit.repository.model.MetaData; +import org.eclipse.hawkbit.repository.model.Rollout; +import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupErrorAction; +import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupErrorCondition; +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.SoftwareModuleType; +import org.eclipse.hawkbit.repository.model.Target; +import org.eclipse.hawkbit.repository.model.TargetWithActionType; import org.eclipse.hawkbit.repository.test.matcher.EventVerifier; import org.eclipse.hawkbit.security.DosFilter; import org.eclipse.hawkbit.security.SystemSecurityContext; @@ -72,6 +89,8 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; +import com.google.common.collect.Lists; + @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ActiveProfiles({ "test" }) @@ -212,6 +231,67 @@ public void setEnvironment(final Environment environment) { this.environment = environment; } + protected DistributionSetAssignmentResult assignDistributionSet(final Long dsID, final String controllerId) { + return deploymentManagement.assignDistributionSet(dsID, + Lists.newArrayList(new TargetWithActionType(controllerId, ActionType.FORCED, + org.eclipse.hawkbit.repository.model.RepositoryModelConstants.NO_FORCE_TIME))); + } + + protected DistributionSetAssignmentResult assignDistributionSet(final DistributionSet pset, + final List targets) { + return deploymentManagement.assignDistributionSet(pset.getId(), + targets.stream().map(Target::getTargetWithActionType).collect(Collectors.toList())); + } + + protected DistributionSetAssignmentResult assignDistributionSet(final DistributionSet pset, final Target target) { + return assignDistributionSet(pset, Lists.newArrayList(target)); + } + + protected DistributionSetMetadata createDistributionSetMetadata(final Long dsId, final MetaData md) { + return distributionSetManagement.createDistributionSetMetadata(dsId, Collections.singletonList(md)).get(0); + } + + protected Long getOsModule(final DistributionSet ds) { + return ds.findFirstModuleByType(osType).getId(); + } + + protected Action prepareFinishedUpdate() { + return prepareFinishedUpdate(TestdataFactory.DEFAULT_CONTROLLER_ID, "", false); + } + + protected Action prepareFinishedUpdate(final String controllerId, final String distributionSet, + final boolean isRequiredMigrationStep) { + final DistributionSet ds = testdataFactory.createDistributionSet(distributionSet, isRequiredMigrationStep); + Target savedTarget = testdataFactory.createTarget(controllerId); + savedTarget = assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getAssignedEntity().iterator() + .next(); + Action savedAction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0); + + savedAction = controllerManagament.addUpdateActionStatus( + entityFactory.actionStatus().create(savedAction.getId()).status(Action.Status.RUNNING)); + + return controllerManagament.addUpdateActionStatus( + entityFactory.actionStatus().create(savedAction.getId()).status(Action.Status.FINISHED)); + } + + protected 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 RolloutGroupConditionBuilder().withDefaults() + .successCondition(RolloutGroupSuccessCondition.THRESHOLD, successCondition) + .errorCondition(RolloutGroupErrorCondition.THRESHOLD, errorCondition) + .errorAction(RolloutGroupErrorAction.PAUSE, null).build(); + + final Rollout rollout = rolloutManagement.createRollout(entityFactory.rollout().create().name(rolloutName) + .description(rolloutDescription).targetFilterQuery(filterQuery).set(distributionSet), groupSize, + conditions); + + // Run here, because Scheduler is disabled during tests + rolloutManagement.fillRolloutGroupsWithTargets(rollout.getId()); + + return rolloutManagement.findRolloutById(rollout.getId()); + } + @Before public void before() throws Exception { mvc = createMvcWebAppContext().build(); @@ -219,18 +299,18 @@ public void before() throws Exception { osType = securityRule .runAsPrivileged(() -> testdataFactory.findOrCreateSoftwareModuleType(TestdataFactory.SM_TYPE_OS)); - osType.setDescription(description); - osType = securityRule.runAsPrivileged(() -> softwareManagement.updateSoftwareModuleType(osType)); + osType = securityRule.runAsPrivileged(() -> softwareManagement.updateSoftwareModuleType( + entityFactory.softwareModuleType().update(osType.getId()).description(description))); appType = securityRule.runAsPrivileged( () -> testdataFactory.findOrCreateSoftwareModuleType(TestdataFactory.SM_TYPE_APP, Integer.MAX_VALUE)); - appType.setDescription(description); - appType = securityRule.runAsPrivileged(() -> softwareManagement.updateSoftwareModuleType(appType)); + appType = securityRule.runAsPrivileged(() -> softwareManagement.updateSoftwareModuleType( + entityFactory.softwareModuleType().update(appType.getId()).description(description))); runtimeType = securityRule .runAsPrivileged(() -> testdataFactory.findOrCreateSoftwareModuleType(TestdataFactory.SM_TYPE_RT)); - runtimeType.setDescription(description); - runtimeType = securityRule.runAsPrivileged(() -> softwareManagement.updateSoftwareModuleType(runtimeType)); + runtimeType = securityRule.runAsPrivileged(() -> softwareManagement.updateSoftwareModuleType( + entityFactory.softwareModuleType().update(runtimeType.getId()).description(description))); standardDsType = securityRule.runAsPrivileged(() -> testdataFactory.findOrCreateDefaultTestDsType()); } diff --git a/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/TestdataFactory.java b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/TestdataFactory.java index 22110bb67d..983aed8b2c 100644 --- a/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/TestdataFactory.java +++ b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/TestdataFactory.java @@ -13,11 +13,14 @@ import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.List; -import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import org.apache.commons.io.IOUtils; import org.eclipse.hawkbit.repository.ArtifactManagement; +import org.eclipse.hawkbit.repository.Constants; import org.eclipse.hawkbit.repository.ControllerManagement; import org.eclipse.hawkbit.repository.DeploymentManagement; import org.eclipse.hawkbit.repository.DistributionSetManagement; @@ -25,6 +28,7 @@ import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.TagManagement; import org.eclipse.hawkbit.repository.TargetManagement; +import org.eclipse.hawkbit.repository.builder.TagCreate; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.ActionStatus; @@ -41,7 +45,6 @@ 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; @@ -135,6 +138,51 @@ 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} and + * {@link DistributionSet#isRequiredMigrationStep()} false. + * + * @return {@link DistributionSet} entity. + */ + public DistributionSet createDistributionSet() { + return createDistributionSet("", 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} and + * {@link DistributionSet#isRequiredMigrationStep()} false. + * + * @param modules + * of {@link DistributionSet#getModules()} + * + * @return {@link DistributionSet} entity. + */ + public DistributionSet createDistributionSet(final Collection modules) { + return createDistributionSet("", DEFAULT_VERSION, false, modules); + } + + /** + * 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 modules + * of {@link DistributionSet#getModules()} + * @param prefix + * for {@link SoftwareModule}s and {@link DistributionSet}s name, + * vendor and description. + * + * @return {@link DistributionSet} entity. + */ + public DistributionSet createDistributionSet(final Collection modules, final String prefix) { + return createDistributionSet(prefix, DEFAULT_VERSION, false, modules); + } + /** * Creates {@link DistributionSet} in repository including three * {@link SoftwareModule}s of types {@link #SM_TYPE_OS}, {@link #SM_TYPE_RT} @@ -190,23 +238,51 @@ public DistributionSet createDistributionSet(final String prefix, final Collecti 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 SecureRandom().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 SecureRandom().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 SecureRandom().nextInt(100), LOREM.words(20), - prefix + " vendor Limited Inc, California")); + final SoftwareModule appMod = softwareManagement.createSoftwareModule(entityFactory.softwareModule().create() + .type(findOrCreateSoftwareModuleType(SM_TYPE_APP, Integer.MAX_VALUE)).name(prefix + SM_TYPE_APP) + .version(version + "." + new SecureRandom().nextInt(100)).description(LOREM.words(20)) + .vendor(prefix + " vendor Limited, California")); + final SoftwareModule runtimeMod = softwareManagement.createSoftwareModule( + entityFactory.softwareModule().create().type(findOrCreateSoftwareModuleType(SM_TYPE_RT)) + .name(prefix + "app runtime").version(version + "." + new SecureRandom().nextInt(100)) + .description(LOREM.words(20)).vendor(prefix + " vendor GmbH, Stuttgart, Germany")); + final SoftwareModule osMod = softwareManagement.createSoftwareModule( + entityFactory.softwareModule().create().type(findOrCreateSoftwareModuleType(SM_TYPE_OS)) + .name(prefix + " Firmware").version(version + "." + new SecureRandom().nextInt(100)) + .description(LOREM.words(20)).vendor(prefix + " vendor Limited Inc, California")); + + return distributionSetManagement.createDistributionSet( + entityFactory.distributionSet().create().name(prefix != null && prefix.length() > 0 ? prefix : "DS") + .version(version).description(LOREM.words(10)).type(findOrCreateDefaultTestDsType()) + .modules(Lists.newArrayList(osMod.getId(), runtimeMod.getId(), appMod.getId())) + .requiredMigrationStep(isRequiredMigrationStep)); + } - 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. + * + * @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()} + * @param modules + * for {@link DistributionSet#getModules()} + * + * @return {@link DistributionSet} entity. + */ + public DistributionSet createDistributionSet(final String prefix, final String version, + final boolean isRequiredMigrationStep, final Collection modules) { + + return distributionSetManagement.createDistributionSet( + entityFactory.distributionSet().create().name(prefix != null && prefix.length() > 0 ? prefix : "DS") + .version(version).description(LOREM.words(10)).type(findOrCreateDefaultTestDsType()) + .modules(modules.stream().map(SoftwareModule::getId).collect(Collectors.toList())) + .requiredMigrationStep(isRequiredMigrationStep)); } /** @@ -296,12 +372,8 @@ public List createDistributionSets(final String prefix, final i */ 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); + return distributionSetManagement.createDistributionSet(entityFactory.distributionSet().create().name(name) + .version(version).description(DEFAULT_DESCRIPTION).type(findOrCreateDefaultTestDsType())); } /** @@ -335,15 +407,99 @@ public List createArtifacts(final Long moduleId) { * @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 createSoftwareModule(typeKey, ""); + } + + /** + * Creates {@link SoftwareModule} of type + * {@value Constants#SMT_DEFAULT_APP_KEY} with {@link #DEFAULT_VENDOR} and + * {@link #DEFAULT_VERSION} and random generated + * {@link Target#getDescription()} in the repository. + * + * + * @return persisted {@link SoftwareModule}. + */ + public SoftwareModule createSoftwareModuleApp() { + return createSoftwareModule(Constants.SMT_DEFAULT_APP_KEY, ""); + } + + /** + * Creates {@link SoftwareModule} of type + * {@value Constants#SMT_DEFAULT_APP_KEY} with {@link #DEFAULT_VENDOR} and + * {@link #DEFAULT_VERSION} and random generated + * {@link Target#getDescription()} in the repository. + * + * @param prefix + * added to name and version + * + * + * @return persisted {@link SoftwareModule}. + */ + public SoftwareModule createSoftwareModuleApp(final String prefix) { + return createSoftwareModule(Constants.SMT_DEFAULT_APP_KEY, prefix); + } + + /** + * Creates {@link SoftwareModule} of type + * {@value Constants#SMT_DEFAULT_OS_KEY} with {@link #DEFAULT_VENDOR} and + * {@link #DEFAULT_VERSION} and random generated + * {@link Target#getDescription()} in the repository. + * + * + * @return persisted {@link SoftwareModule}. + */ + public SoftwareModule createSoftwareModuleOs() { + return createSoftwareModule(Constants.SMT_DEFAULT_OS_KEY, ""); + } + + /** + * Creates {@link SoftwareModule} of type + * {@value Constants#SMT_DEFAULT_OS_KEY} with {@link #DEFAULT_VENDOR} and + * {@link #DEFAULT_VERSION} and random generated + * {@link Target#getDescription()} in the repository. + * + * @param prefix + * added to name and version + * + * + * @return persisted {@link SoftwareModule}. + */ + public SoftwareModule createSoftwareModuleOs(final String prefix) { + return createSoftwareModule(Constants.SMT_DEFAULT_OS_KEY, prefix); + } + + /** + * 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} + * @param prefix + * added to name and version + * + * @return persisted {@link SoftwareModule}. + */ + public SoftwareModule createSoftwareModule(final String typeKey, final String prefix) { + return softwareManagement.createSoftwareModule(entityFactory.softwareModule().create() + .type(findOrCreateSoftwareModuleType(typeKey)).name(prefix + typeKey).version(prefix + DEFAULT_VERSION) + .description(LOREM.words(10)).vendor(DEFAULT_VENDOR)); } /** * @return persisted {@link Target} with {@link #DEFAULT_CONTROLLER_ID}. */ public Target createTarget() { - return targetManagement.createTarget(entityFactory.generateTarget(DEFAULT_CONTROLLER_ID)); + return createTarget(DEFAULT_CONTROLLER_ID); + } + + /** + * @param controllerId + * of the target + * @return persisted {@link Target} + */ + public Target createTarget(final String controllerId) { + return targetManagement.createTarget(entityFactory.target().create().controllerId(controllerId)); } /** @@ -353,7 +509,7 @@ public Target createTarget() { * iterative number and {@link DistributionSet#isRequiredMigrationStep()} * false. * - * In addition it updates the ccreated {@link DistributionSet}s and + * In addition it updates the created {@link DistributionSet}s and * {@link SoftwareModule}s to ensure that * {@link BaseEntity#getLastModifiedAt()} and * {@link BaseEntity#getLastModifiedBy()} is filled. @@ -362,18 +518,14 @@ public Target createTarget() { */ public DistributionSet createUpdatedDistributionSet() { DistributionSet set = createDistributionSet(""); - set.setVersion(DEFAULT_VERSION); - set = distributionSetManagement.updateDistributionSet(set); + set = distributionSetManagement.updateDistributionSet( + entityFactory.distributionSet().update(set.getId()).description("Updated " + DEFAULT_DESCRIPTION)); - set.getModules().forEach(module -> { - module.setDescription("Updated " + DEFAULT_DESCRIPTION); - softwareManagement.updateSoftwareModule(module); - }); + set.getModules().forEach(module -> softwareManagement.updateSoftwareModule( + entityFactory.softwareModule().update(module.getId()).description("Updated " + DEFAULT_DESCRIPTION))); // load also lazy stuff - set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()); - - return set; + return distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()); } /** @@ -411,10 +563,8 @@ public DistributionSetType findOrCreateDistributionSetType(final String dsTypeKe return findDistributionSetTypeByname; } - final DistributionSetType type = entityFactory.generateDistributionSetType(dsTypeKey, dsTypeName, - LOREM.words(10)); - - return distributionSetManagement.createDistributionSetType(type); + return distributionSetManagement.createDistributionSetType(entityFactory.distributionSetType().create() + .key(dsTypeKey).name(dsTypeName).description(LOREM.words(10)).colour("black")); } /** @@ -441,12 +591,10 @@ public DistributionSetType findOrCreateDistributionSetType(final String dsTypeKe return findDistributionSetTypeByname; } - final DistributionSetType type = entityFactory.generateDistributionSetType(dsTypeKey, dsTypeName, - LOREM.words(10)); - mandatory.forEach(type::addMandatoryModuleType); - optional.forEach(type::addOptionalModuleType); - - return distributionSetManagement.createDistributionSetType(type); + return distributionSetManagement.createDistributionSetType(entityFactory.distributionSetType().create() + .key(dsTypeKey).name(dsTypeName).description(LOREM.words(10)).colour("black") + .optional(optional.stream().map(SoftwareModuleType::getId).collect(Collectors.toList())) + .mandatory(mandatory.stream().map(SoftwareModuleType::getId).collect(Collectors.toList()))); } /** @@ -479,12 +627,12 @@ public SoftwareModuleType findOrCreateSoftwareModuleType(final String key, final if (findSoftwareModuleTypeByKey != null) { return findSoftwareModuleTypeByKey; } - return softwareManagement.createSoftwareModuleType( - entityFactory.generateSoftwareModuleType(key, key, LOREM.words(10), maxAssignments)); + return softwareManagement.createSoftwareModuleType(entityFactory.softwareModuleType().create().key(key) + .name(key).description(LOREM.words(10)).maxAssignments(maxAssignments)); } /** - * builder method for creating a {@link DistributionSet}. + * Creates a {@link DistributionSet}. * * @param name * {@link DistributionSet#getName()} @@ -497,81 +645,67 @@ public SoftwareModuleType findOrCreateSoftwareModuleType(final String key, final * * @return the created {@link DistributionSet} */ - public DistributionSet generateDistributionSet(final String name, final String version, + public DistributionSet createDistributionSet(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; + return distributionSetManagement.createDistributionSet( + entityFactory.distributionSet().create().name(name).version(version).description(LOREM.words(10)) + .type(type).modules(modules.stream().map(SoftwareModule::getId).collect(Collectors.toList()))); } /** - * builder method for generating a {@link DistributionSet}. + * Generates {@link DistributionSet} object without persisting it. * * @param name * {@link DistributionSet#getName()} + * @param version + * {@link DistributionSet#getVersion()} + * @param type + * {@link DistributionSet#getType()} + * @param modules + * {@link DistributionSet#getModules()} + * @param requiredMigrationStep + * {@link DistributionSet#isRequiredMigrationStep()} * - * @return the generated {@link DistributionSet} + * @return the created {@link DistributionSet} */ - public DistributionSet generateDistributionSet(final String name) { - final DistributionSet distributionSet = entityFactory.generateDistributionSet(name, DEFAULT_VERSION, null, - findOrCreateDefaultTestDsType(), null); - distributionSet.setDescription(LOREM.words(10)); - return distributionSet; + public DistributionSet generateDistributionSet(final String name, final String version, + final DistributionSetType type, final Collection modules, + final boolean requiredMigrationStep) { + return entityFactory.distributionSet().create().name(name).version(version).description(LOREM.words(10)) + .type(type).modules(modules.stream().map(SoftwareModule::getId).collect(Collectors.toList())) + .requiredMigrationStep(requiredMigrationStep).build(); } /** - * Creates {@link DistributionSetTag}s in repository. - * - * @param number - * of {@link DistributionSetTag}s + * Generates {@link DistributionSet} object without persisting it. + * + * @param name + * {@link DistributionSet#getName()} + * @param version + * {@link DistributionSet#getVersion()} + * @param type + * {@link DistributionSet#getType()} + * @param modules + * {@link DistributionSet#getModules()} * - * @return the persisted {@link DistributionSetTag}s + * @return the created {@link DistributionSet} */ - 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); + public DistributionSet generateDistributionSet(final String name, final String version, + final DistributionSetType type, final Collection modules) { + return generateDistributionSet(name, version, type, modules, false); } /** - * builder method for creating a single target object. + * builder method for generating a {@link DistributionSet}. * - * @param ctrlID - * the ID of the target - * @param description - * of the target - * @return the created target object + * @param name + * {@link DistributionSet#getName()} + * + * @return the generated {@link DistributionSet} */ - 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; + public DistributionSet generateDistributionSet(final String name) { + return generateDistributionSet(name, DEFAULT_VERSION, findOrCreateDefaultTestDsType(), Collections.emptyList(), + false); } /** @@ -585,7 +719,12 @@ private Target generateTarget(final String ctrlID, final String description, fin * @return {@link List} of {@link Target} entities */ public List createTargets(final int number) { - return targetManagement.createTargets(generateTargets(0, number, DEFAULT_CONTROLLER_ID)); + final List targets = Lists.newArrayListWithExpectedSize(number); + for (int i = 0; i < number; i++) { + targets.add(createTarget(DEFAULT_CONTROLLER_ID + i)); + } + + return targets; } /** @@ -601,9 +740,9 @@ public List createTargets(final int number) { * @return list of {@link Target} objects */ private List generateTargets(final int start, final int numberOfTargets, final String controllerIdPrefix) { - final List targets = new ArrayList<>(); + final List targets = Lists.newArrayListWithExpectedSize(numberOfTargets); for (int i = start; i < start + numberOfTargets; i++) { - targets.add(entityFactory.generateTarget(controllerIdPrefix + i)); + targets.add(entityFactory.target().create().controllerId(controllerIdPrefix + i).build()); } return targets; @@ -624,6 +763,19 @@ public List generateTargets(final int numberOfTargets, final String cont return generateTargets(0, numberOfTargets, controllerIdPrefix); } + /** + * builds a set of {@link Target} fixtures from the given parameters. + * + * @param numberOfTargets + * number of targets to create + * @param prefix + * prefix used for the controller ID and description + * @return set of {@link Target} + */ + public List createTargets(final int numberOfTargets, final String prefix) { + return createTargets(numberOfTargets, prefix, prefix); + } + /** * builds a set of {@link Target} fixtures from the given parameters. * @@ -635,100 +787,100 @@ public List generateTargets(final int numberOfTargets, final String cont * prefix used for the description * @return set of {@link Target} */ - public List generateTargets(final int numberOfTargets, final String controllerIdPrefix, + public List createTargets(final int numberOfTargets, final String controllerIdPrefix, final String descriptionPrefix) { - return generateTargets(numberOfTargets, controllerIdPrefix, descriptionPrefix, null); + + return targetManagement.createTargets(IntStream.range(0, numberOfTargets) + .mapToObj(i -> entityFactory.target().create() + .controllerId(String.format("%s-%05d", controllerIdPrefix, i)) + .description(descriptionPrefix + i)) + .collect(Collectors.toList())); } /** - * method creates set of targets by by generating the controller ID and the - * description like: prefix + no of target. + * builds a set of {@link Target} fixtures from the given parameters. * - * @param noOfTgts - * number of targets which should be created + * @param numberOfTargets + * number of targets to create * @param controllerIdPrefix - * prefix of the controllerID which is concatenated with the - * number of the target. Randomly generated if null. + * prefix used for the controller ID * @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); + * prefix used for the description + * @param lastTargetQuery + * last time the target polled + * @return set of {@link Target} + */ + public List createTargets(final int numberOfTargets, final String controllerIdPrefix, + final String descriptionPrefix, final Long lastTargetQuery) { - } - return list; + return targetManagement.createTargets(IntStream.range(0, numberOfTargets) + .mapToObj(i -> entityFactory.target().create().controllerId(controllerIdPrefix + i) + .description(descriptionPrefix + i).lastTargetQuery(lastTargetQuery)) + .collect(Collectors.toList())); } /** - * Generates {@link TargetTag}s. - * + * Create a set of {@link TargetTag}s. + * * @param number - * of {@link TargetTag}s to generate. - * - * @return generated {@link TargetTag}s. + * 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 number) { - final List result = new ArrayList<>(); + public List createTargetTags(final int number, final String tagPrefix) { + final List result = Lists.newArrayListWithExpectedSize(number); for (int i = 0; i < number; i++) { - result.add(entityFactory.generateTargetTag("tag" + i, "tagdesc" + i, String.valueOf(i))); + result.add(entityFactory.tag().create().name(tagPrefix + i).description(tagPrefix + i) + .colour(String.valueOf(i))); } - return result; + return tagManagement.createTargetTags(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 + * Creates {@link DistributionSetTag}s in repository. + * + * @param number + * of {@link DistributionSetTag}s + * + * @return the persisted {@link DistributionSetTag}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); + public List createDistributionSetTags(final int number) { + final List result = Lists.newArrayListWithExpectedSize(number); - final TargetTag targetTag = entityFactory.generateTargetTag(tagName); - list.add(targetTag); + for (int i = 0; i < number; i++) { + result.add( + entityFactory.tag().create().name("tag" + i).description("tagdesc" + i).colour(String.valueOf(i))); } - return list; + + return tagManagement.createDistributionSetTags(result); } - private Action sendUpdateActionStatusToTarget(final Status status, final Action updActA, final String... msgs) { - updActA.setStatus(status); + private Action sendUpdateActionStatusToTarget(final Status status, final Action updActA, + final Collection msgs) { - 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( + entityFactory.actionStatus().create(updActA.getId()).status(status).messages(msgs)); + } - 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 message + * to add + * + * @return updated {@link Action}. + */ + public List sendUpdateActionStatusToTargets(final Collection targets, final Status status, + final String message) { + return sendUpdateActionStatusToTargets(targets, status, Lists.newArrayList(message)); } /** @@ -745,7 +897,7 @@ private Action sendUpdateActionStatusToTarget(final Status status, final Action * @return updated {@link Action}. */ public List sendUpdateActionStatusToTargets(final Collection targets, final Status status, - final String... msgs) { + final Collection msgs) { final List result = new ArrayList<>(); for (final Target target : targets) { final List findByTarget = deploymentManagement.findActionsByTarget(target); diff --git a/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/exception/ResponseExceptionHandler.java b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/exception/ResponseExceptionHandler.java index 41313d6ff8..feab1f3882 100644 --- a/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/exception/ResponseExceptionHandler.java +++ b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/exception/ResponseExceptionHandler.java @@ -69,6 +69,7 @@ public class ResponseExceptionHandler { ERROR_TO_HTTP_STATUS.put(SpServerError.SP_CONFIGURATION_VALUE_INVALID, HttpStatus.BAD_REQUEST); ERROR_TO_HTTP_STATUS.put(SpServerError.SP_CONFIGURATION_KEY_INVALID, HttpStatus.BAD_REQUEST); ERROR_TO_HTTP_STATUS.put(SpServerError.SP_REPO_INVALID_TARGET_ADDRESS, HttpStatus.BAD_REQUEST); + ERROR_TO_HTTP_STATUS.put(SpServerError.SP_REPO_CONSTRAINT_VIOLATION, HttpStatus.BAD_REQUEST); } private static HttpStatus getStatusOrDefault(final SpServerError error) { diff --git a/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/MockMvcResultPrinter.java b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/MockMvcResultPrinter.java index b1de56f612..0abf37d0d9 100644 --- a/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/MockMvcResultPrinter.java +++ b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/MockMvcResultPrinter.java @@ -43,7 +43,9 @@ public void printHeading(final String heading) { } @Override - public void printValue(final String label, Object value) { + public void printValue(final String label, final Object v) { + Object value = v; + if (value != null && value.getClass().isArray()) { value = CollectionUtils.arrayToList(value); } 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 9f40d18113..e4fa321c80 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 @@ -73,7 +73,7 @@ public ArtifactBeanQuery(final QueryDefinition definition, final Map(SoftwareModuleTypeBeanQuery.class))); + typeComboBox.setContainerDataSource( + HawkbitCommonUtil.createLazyQueryContainer(new BeanQueryFactory<>(SoftwareModuleTypeBeanQuery.class))); typeComboBox.setItemCaptionPropertyId(SPUILabelDefinitions.VAR_NAME); } @@ -246,12 +246,8 @@ private boolean isDuplicate() { * updates a softwareModule */ private void updateSwModule() { - final String newDesc = HawkbitCommonUtil.trimAndNullIfEmpty(descTextArea.getValue()); - final String newVendor = HawkbitCommonUtil.trimAndNullIfEmpty(vendorTextField.getValue()); - SoftwareModule newSWModule = softwareManagement.findSoftwareModuleById(baseSwModuleId); - newSWModule.setVendor(newVendor); - newSWModule.setDescription(newDesc); - newSWModule = softwareManagement.updateSoftwareModule(newSWModule); + final SoftwareModule newSWModule = softwareManagement.updateSoftwareModule(entityFactory.softwareModule() + .update(baseSwModuleId).description(descTextArea.getValue()).vendor(vendorTextField.getValue())); if (newSWModule != null) { uiNotifcation.displaySuccess(i18n.get("message.save.success", new Object[] { newSWModule.getName() + ":" + newSWModule.getVersion() })); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleDetails.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleDetails.java index 2b0a74b13c..6dd0b89837 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleDetails.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleDetails.java @@ -10,8 +10,8 @@ import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.SoftwareManagement; +import org.eclipse.hawkbit.repository.model.MetaData; import org.eclipse.hawkbit.repository.model.SoftwareModule; -import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent; import org.eclipse.hawkbit.ui.artifacts.state.ArtifactUploadState; import org.eclipse.hawkbit.ui.common.detailslayout.AbstractNamedVersionedEntityTableDetailsLayout; @@ -76,14 +76,13 @@ protected void init() { @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final MetadataEvent event) { UI.getCurrent().access(() -> { - final SoftwareModuleMetadata softwareModuleMetadata = event.getSoftwareModuleMetadata(); - if (softwareModuleMetadata != null - && isSoftwareModuleSelected(softwareModuleMetadata.getSoftwareModule())) { + final MetaData softwareModuleMetadata = event.getMetaData(); + if (softwareModuleMetadata != null && isSoftwareModuleSelected(event.getModule())) { if (event.getMetadataUIEvent() == MetadataEvent.MetadataUIEvent.CREATE_SOFTWARE_MODULE_METADATA) { - swmMetadataTable.createMetadata(event.getSoftwareModuleMetadata().getKey()); + swmMetadataTable.createMetadata(event.getMetaData().getKey()); } else if (event .getMetadataUIEvent() == MetadataEvent.MetadataUIEvent.DELETE_SOFTWARE_MODULE_METADATA) { - swmMetadataTable.deleteMetadata(event.getSoftwareModuleMetadata().getKey()); + swmMetadataTable.deleteMetadata(event.getMetaData().getKey()); } } }); 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 6c5b3a24e4..f45b785b5c 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 @@ -11,7 +11,6 @@ import java.util.ArrayList; import java.util.List; -import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleTypeEvent; @@ -49,15 +48,12 @@ @ViewScope public class CreateUpdateSoftwareTypeLayout extends CreateUpdateTypeLayout { - private static final long serialVersionUID = -5169398523815919367L; + private static final long serialVersionUID = 1L; private static final Logger LOG = LoggerFactory.getLogger(CreateUpdateSoftwareTypeLayout.class); @Autowired private transient SoftwareManagement swTypeManagementService; - @Autowired - private transient EntityFactory entityFactory; - private String singleAssignStr; private String multiAssignStr; private Label singleAssign; @@ -242,12 +238,9 @@ private void createNewSWModuleType() { } if (null != typeNameValue && null != typeKeyValue) { - SoftwareModuleType newSWType = entityFactory.generateSoftwareModuleType(typeKeyValue, typeNameValue, - typeDescValue, assignNumber); - newSWType.setColour(colorPicked); - newSWType.setDescription(typeDescValue); - newSWType.setColour(colorPicked); - newSWType = swTypeManagementService.createSoftwareModuleType(newSWType); + final SoftwareModuleType newSWType = swTypeManagementService.createSoftwareModuleType( + entityFactory.softwareModuleType().create().key(typeKeyValue).name(typeNameValue) + .description(typeDescValue).colour(colorPicked).maxAssignments(assignNumber)); uiNotification.displaySuccess(i18n.get("message.save.success", new Object[] { newSWType.getName() })); eventBus.publish(this, new SoftwareModuleTypeEvent(SoftwareModuleTypeEnum.ADD_SOFTWARE_MODULE_TYPE, newSWType)); @@ -257,20 +250,12 @@ private void createNewSWModuleType() { } private void updateSWModuleType(final SoftwareModuleType existingType) { - - final String typeNameValue = HawkbitCommonUtil.trimAndNullIfEmpty(tagName.getValue()); - final String typeDescValue = HawkbitCommonUtil.trimAndNullIfEmpty(tagDesc.getValue()); - if (null != typeNameValue) { - existingType.setName(typeNameValue); - existingType.setDescription(typeDescValue); - existingType.setColour(ColorPickerHelper.getColorPickedString(getColorPickerLayout().getSelPreview())); - swTypeManagementService.updateSoftwareModuleType(existingType); - uiNotification.displaySuccess(i18n.get("message.update.success", new Object[] { existingType.getName() })); - eventBus.publish(this, - new SoftwareModuleTypeEvent(SoftwareModuleTypeEnum.UPDATE_SOFTWARE_MODULE_TYPE, existingType)); - } else { - uiNotification.displayValidationError(i18n.get("message.tag.update.mandatory")); - } + swTypeManagementService.updateSoftwareModuleType( + entityFactory.softwareModuleType().update(existingType.getId()).description(tagDesc.getValue()) + .colour(ColorPickerHelper.getColorPickedString(getColorPickerLayout().getSelPreview()))); + uiNotification.displaySuccess(i18n.get("message.update.success", new Object[] { existingType.getName() })); + eventBus.publish(this, + new SoftwareModuleTypeEvent(SoftwareModuleTypeEnum.UPDATE_SOFTWARE_MODULE_TYPE, existingType)); } @Override @@ -291,8 +276,8 @@ public Color getColor() { @Override protected void populateTagNameCombo() { - tagNameComboBox.setContainerDataSource(HawkbitCommonUtil.createLazyQueryContainer( - new BeanQueryFactory(SoftwareModuleTypeBeanQuery.class))); + tagNameComboBox.setContainerDataSource( + HawkbitCommonUtil.createLazyQueryContainer(new BeanQueryFactory<>(SoftwareModuleTypeBeanQuery.class))); tagNameComboBox.setItemCaptionPropertyId(SPUILabelDefinitions.VAR_NAME); } 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 ded26b2545..54590dd9e4 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 @@ -8,7 +8,6 @@ */ package org.eclipse.hawkbit.ui.common; -import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -40,7 +39,7 @@ public class DistributionSetTypeBeanQuery extends AbstractBeanQuery firstPageDistSetType = null; + private transient Page firstPageDistSetType; private transient DistributionSetManagement distributionSetManagement; private transient EntityFactory entityFactory; @@ -59,9 +58,7 @@ public DistributionSetTypeBeanQuery(final QueryDefinition definition, final Map< @Override protected DistributionSetType constructBean() { - final DistributionSetType result = getEntityFactory().generateDistributionSetType("", "", ""); - result.setColour(""); - return result; + return null; } @Override @@ -93,7 +90,6 @@ private EntityFactory getEntityFactory() { @Override protected List loadBeans(final int startIndex, final int count) { Page typeBeans; - final List distSetTypeList = new ArrayList<>(); if (startIndex == 0 && firstPageDistSetType != null) { typeBeans = firstPageDistSetType; } else { @@ -101,8 +97,7 @@ protected List loadBeans(final int startIndex, final int co .findDistributionSetTypesAll(new OffsetBasedPageRequest(startIndex, count, sort)); } - distSetTypeList.addAll(typeBeans.getContent()); - return distSetTypeList; + return typeBeans.getContent(); } @Override 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 8705f7aa91..d5e07c1644 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 @@ -49,7 +49,7 @@ public SoftwareModuleTypeBeanQuery(final QueryDefinition definition, final Map alreadyAssignedSwModules) { final SoftwareModule unAssignedSw = getSoftwareModule(event.getButton().getId(), alreadyAssignedSwModules); if (distributionSetManagement.isDistributionSetInUse(distributionSet)) { - uiNotification.displayValidationError(i18n.get("message.error.notification.ds.target.assigned",distributionSet.getName(), distributionSet.getVersion())); + uiNotification.displayValidationError(i18n.get("message.error.notification.ds.target.assigned", + distributionSet.getName(), distributionSet.getVersion())); } else { - final DistributionSet newDistributionSet = distributionSetManagement.unassignSoftwareModule(distributionSet, - unAssignedSw); + final DistributionSet newDistributionSet = distributionSetManagement + .unassignSoftwareModule(distributionSet.getId(), unAssignedSw.getId()); manageDistUIState.setLastSelectedEntity(DistributionSetIdName.generate(newDistributionSet)); eventBus.publish(this, new DistributionTableEvent(BaseEntityEventType.SELECTED_ENTITY, newDistributionSet)); eventBus.publish(this, DistributionsUIEvent.ORDER_BY_DISTRIBUTION); @@ -257,7 +258,7 @@ protected SoftwareModule getSoftwareModule(final String softwareModule, return null; } - private Label createMandatoryLabel(final boolean mandatory) { + private static Label createMandatoryLabel(final boolean mandatory) { final Label mandatoryLable = mandatory ? HawkbitCommonUtil.getFormatedLabel(" * ") : HawkbitCommonUtil.getFormatedLabel(" "); if (mandatory) { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/SoftwareModuleMetadatadetailslayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/SoftwareModuleMetadatadetailslayout.java index 0886a77f26..5ad02876de 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/SoftwareModuleMetadatadetailslayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/SoftwareModuleMetadatadetailslayout.java @@ -41,19 +41,19 @@ @ViewScope public class SoftwareModuleMetadatadetailslayout extends Table { - private static final long serialVersionUID = 2913758299611838818L; + private static final long serialVersionUID = 2913758299611838818L; - private static final String METADATA_KEY = "Key"; + private static final String METADATA_KEY = "Key"; - private SpPermissionChecker permissionChecker; + private SpPermissionChecker permissionChecker; private transient SoftwareManagement softwareManagement; - private SwMetadataPopupLayout swMetadataPopupLayout; + private SwMetadataPopupLayout swMetadataPopupLayout; - private I18N i18n; + private I18N i18n; - private Long selectedSWModuleId; + private Long selectedSWModuleId; private transient EntityFactory entityFactory; @@ -83,102 +83,101 @@ public void init(final I18N i18n, final SpPermissionChecker permissionChecker, addCustomGeneratedColumns(); } - /** - * Populate software module metadata table. - * - * @param swModule - */ - public void populateSMMetadata(final SoftwareModule swModule) { - removeAllItems(); - if (null == swModule) { - return; - } - selectedSWModuleId = swModule.getId(); - final List swMetadataList = softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(selectedSWModuleId); - if (null != swMetadataList && !swMetadataList.isEmpty()) { - swMetadataList.forEach(swMetadata -> setSWMetadataProperties(swMetadata)); - } - } - - /** - * Create metadata. - * - * @param metadataKeyName - */ - public void createMetadata(final String metadataKeyName) { - final IndexedContainer metadataContainer = (IndexedContainer) getContainerDataSource(); - final Item item = metadataContainer.addItem(metadataKeyName); - item.getItemProperty(METADATA_KEY).setValue(metadataKeyName); - - } - - /** - * Delete metadata. - * - * @param metadataKeyName - */ - public void deleteMetadata(final String metadataKeyName) { - final IndexedContainer metadataContainer = (IndexedContainer) getContainerDataSource(); - metadataContainer.removeItem(metadataKeyName); - } - - private void createSWMMetadataTable() { - addStyleName(ValoTheme.TABLE_NO_HORIZONTAL_LINES); - addStyleName(ValoTheme.TABLE_NO_STRIPES); - addStyleName(SPUIStyleDefinitions.SW_MODULE_TABLE); - setSelectable(false); - setImmediate(true); - setContainerDataSource(getSwModuleMetadataContainer()); - setColumnHeaderMode(ColumnHeaderMode.EXPLICIT); - addSMMetadataTableHeader(); - setSizeFull(); - //same as height of other tabs in details tabsheet - setHeight(116,Unit.PIXELS); - } - - private IndexedContainer getSwModuleMetadataContainer() { - final IndexedContainer container = new IndexedContainer(); - container.addContainerProperty(METADATA_KEY, String.class, ""); - setColumnAlignment(METADATA_KEY, Align.LEFT); - return container; - } - - private void addSMMetadataTableHeader() { - setColumnHeader(METADATA_KEY, i18n.get("header.key")); - } - - - private void setSWMetadataProperties(final SoftwareModuleMetadata swMetadata) { - final Item item = getContainerDataSource().addItem(swMetadata.getKey()); - item.getItemProperty(METADATA_KEY).setValue(swMetadata.getKey()); - } - - private void addCustomGeneratedColumns() { - addGeneratedColumn(METADATA_KEY, (source, itemId, columnId) -> customMetadataDetailButton((String) itemId)); - } - - private Button customMetadataDetailButton(final String metadataKey) { - final Button viewLink = SPUIComponentProvider.getButton(getDetailLinkId(metadataKey), metadataKey, "View" - + metadataKey + " Metadata details", null, false, null, SPUIButtonStyleSmallNoBorder.class); - viewLink.setData(metadataKey); - if (permissionChecker.hasUpdateDistributionPermission()) { - viewLink.addStyleName(ValoTheme.BUTTON_TINY + " " + ValoTheme.BUTTON_LINK + " " + "on-focus-no-border link" - + " " + "text-style"); - viewLink.addClickListener(event -> showMetadataDetails(selectedSWModuleId, metadataKey)); - } - return viewLink; - } - - private static String getDetailLinkId(final String name) { - return new StringBuilder(UIComponentIdProvider.SW_METADATA_DETAIL_LINK).append('.').append(name).toString(); - } - - private void showMetadataDetails(final Long selectedSWModuleId, final String metadataKey) { - final SoftwareModule swmodule = softwareManagement.findSoftwareModuleById(selectedSWModuleId); - /* display the window */ - UI.getCurrent().addWindow( - swMetadataPopupLayout.getWindow(swmodule, - entityFactory.generateSoftwareModuleMetadata(swmodule, metadataKey, ""))); - } + /** + * Populate software module metadata table. + * + * @param swModule + */ + public void populateSMMetadata(final SoftwareModule swModule) { + removeAllItems(); + if (null == swModule) { + return; + } + selectedSWModuleId = swModule.getId(); + final List swMetadataList = softwareManagement + .findSoftwareModuleMetadataBySoftwareModuleId(selectedSWModuleId); + if (null != swMetadataList && !swMetadataList.isEmpty()) { + swMetadataList.forEach(this::setSWMetadataProperties); + } + } + + /** + * Create metadata. + * + * @param metadataKeyName + */ + public void createMetadata(final String metadataKeyName) { + final IndexedContainer metadataContainer = (IndexedContainer) getContainerDataSource(); + final Item item = metadataContainer.addItem(metadataKeyName); + item.getItemProperty(METADATA_KEY).setValue(metadataKeyName); + + } + + /** + * Delete metadata. + * + * @param metadataKeyName + */ + public void deleteMetadata(final String metadataKeyName) { + final IndexedContainer metadataContainer = (IndexedContainer) getContainerDataSource(); + metadataContainer.removeItem(metadataKeyName); + } + + private void createSWMMetadataTable() { + addStyleName(ValoTheme.TABLE_NO_HORIZONTAL_LINES); + addStyleName(ValoTheme.TABLE_NO_STRIPES); + addStyleName(SPUIStyleDefinitions.SW_MODULE_TABLE); + setSelectable(false); + setImmediate(true); + setContainerDataSource(getSwModuleMetadataContainer()); + setColumnHeaderMode(ColumnHeaderMode.EXPLICIT); + addSMMetadataTableHeader(); + setSizeFull(); + // same as height of other tabs in details tabsheet + setHeight(116, Unit.PIXELS); + } + + private IndexedContainer getSwModuleMetadataContainer() { + final IndexedContainer container = new IndexedContainer(); + container.addContainerProperty(METADATA_KEY, String.class, ""); + setColumnAlignment(METADATA_KEY, Align.LEFT); + return container; + } + + private void addSMMetadataTableHeader() { + setColumnHeader(METADATA_KEY, i18n.get("header.key")); + } + + private void setSWMetadataProperties(final SoftwareModuleMetadata swMetadata) { + final Item item = getContainerDataSource().addItem(swMetadata.getKey()); + item.getItemProperty(METADATA_KEY).setValue(swMetadata.getKey()); + } + + private void addCustomGeneratedColumns() { + addGeneratedColumn(METADATA_KEY, (source, itemId, columnId) -> customMetadataDetailButton((String) itemId)); + } + + private Button customMetadataDetailButton(final String metadataKey) { + final Button viewLink = SPUIComponentProvider.getButton(getDetailLinkId(metadataKey), metadataKey, + "View" + metadataKey + " Metadata details", null, false, null, SPUIButtonStyleSmallNoBorder.class); + viewLink.setData(metadataKey); + if (permissionChecker.hasUpdateDistributionPermission()) { + viewLink.addStyleName(ValoTheme.BUTTON_TINY + " " + ValoTheme.BUTTON_LINK + " " + "on-focus-no-border link" + + " " + "text-style"); + viewLink.addClickListener(event -> showMetadataDetails(selectedSWModuleId, metadataKey)); + } + return viewLink; + } + + private static String getDetailLinkId(final String name) { + return new StringBuilder(UIComponentIdProvider.SW_METADATA_DETAIL_LINK).append('.').append(name).toString(); + } + + private void showMetadataDetails(final Long selectedSWModuleId, final String metadataKey) { + final SoftwareModule swmodule = softwareManagement.findSoftwareModuleById(selectedSWModuleId); + /* display the window */ + UI.getCurrent() + .addWindow(swMetadataPopupLayout.getWindow(swmodule, entityFactory.generateMetadata(metadataKey, ""))); + } } 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 53014b6b7c..dbeda7f17f 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 @@ -10,10 +10,11 @@ import java.util.List; import java.util.Set; +import java.util.stream.Collectors; import org.eclipse.hawkbit.repository.DistributionSetManagement; -import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.SoftwareManagement; +import org.eclipse.hawkbit.repository.builder.DistributionSetTypeUpdate; import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.eclipse.hawkbit.ui.colorpicker.ColorPickerConstants; @@ -60,7 +61,7 @@ @ViewScope public class CreateUpdateDistSetTypeLayout extends CreateUpdateTypeLayout { - private static final long serialVersionUID = -5169398523815877767L; + private static final long serialVersionUID = 1L; private static final String DIST_TYPE_NAME = "name"; private static final String DIST_TYPE_DESCRIPTION = "description"; private static final String DIST_TYPE_MANDATORY = "mandatory"; @@ -72,9 +73,6 @@ public class CreateUpdateDistSetTypeLayout extends CreateUpdateTypeLayout itemIds = (List) selectedTable.getItemIds(); if (null != typeNameValue && null != typeKeyValue && null != itemIds && !itemIds.isEmpty()) { - 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(); - final CheckBox mandatoryCheckBox = (CheckBox) item.getItemProperty(DIST_TYPE_MANDATORY).getValue(); - final Boolean isMandatory = mandatoryCheckBox.getValue(); - final SoftwareModuleType swModuleType = softwareManagement.findSoftwareModuleTypeByName(distTypeName); - checkMandatoryAndAddMandatoryModuleType(newDistType, isMandatory, swModuleType); - } - newDistType.setDescription(typeDescValue); - newDistType.setColour(colorPicked); - newDistType = distributionSetManagement.createDistributionSetType(newDistType); + + final List mandatory = itemIds.stream() + .filter(itemId -> isMandatoryModuleType(selectedTable.getItem(itemId))) + .collect(Collectors.toList()); + + final List optional = itemIds.stream() + .filter(itemId -> isOptionalModuleType(selectedTable.getItem(itemId))).collect(Collectors.toList()); + + final DistributionSetType newDistType = distributionSetManagement.createDistributionSetType( + entityFactory.distributionSetType().create().key(typeKeyValue).name(typeNameValue) + .description(typeDescValue).colour(colorPicked).mandatory(mandatory).optional(optional)); uiNotification.displaySuccess(i18n.get("message.save.success", new Object[] { newDistType.getName() })); eventBus.publish(this, new DistributionSetTypeEvent(DistributionSetTypeEnum.ADD_DIST_SET_TYPE, newDistType)); @@ -382,6 +378,15 @@ private void createNewDistributionSetType() { } } + private static boolean isMandatoryModuleType(final Item item) { + final CheckBox mandatoryCheckBox = (CheckBox) item.getItemProperty(DIST_TYPE_MANDATORY).getValue(); + return mandatoryCheckBox.getValue(); + } + + private static boolean isOptionalModuleType(final Item item) { + return !isMandatoryModuleType(item); + } + /** * update distributionSet Type. */ @@ -389,63 +394,25 @@ private void createNewDistributionSetType() { private void updateDistributionSetType(final DistributionSetType existingType) { final List itemIds = (List) selectedTable.getItemIds(); - final String typeNameValue = HawkbitCommonUtil.trimAndNullIfEmpty(tagName.getValue()); - final String typeKeyValue = HawkbitCommonUtil.trimAndNullIfEmpty(typeKey.getValue()); - final String typeDescValue = HawkbitCommonUtil.trimAndNullIfEmpty(tagDesc.getValue()); - /* remove all SW Module Types before update SW Module Types */ - final DistributionSetType updateDistSetType = removeSWModuleTypesFromDistSetType(existingType.getName()); - - if (null != typeNameValue) { - updateDistSetType.setName(typeNameValue); - updateDistSetType.setKey(typeKeyValue); - updateDistSetType.setDescription(typeDescValue); - - 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(); - final Boolean isMandatory = mandatoryCheckBox.getValue(); - final String distTypeName = (String) item.getItemProperty(DIST_TYPE_NAME).getValue(); - final SoftwareModuleType swModuleType = softwareManagement - .findSoftwareModuleTypeByName(distTypeName); - checkMandatoryAndAddMandatoryModuleType(updateDistSetType, isMandatory, swModuleType); - } - } - updateDistSetType.setColour(ColorPickerHelper.getColorPickedString(getColorPickerLayout().getSelPreview())); - distributionSetManagement.updateDistributionSetType(updateDistSetType); - uiNotification - .displaySuccess(i18n.get("message.update.success", new Object[] { updateDistSetType.getName() })); - eventBus.publish(this, - new DistributionSetTypeEvent(DistributionSetTypeEnum.UPDATE_DIST_SET_TYPE, updateDistSetType)); - } else { - uiNotification.displayValidationError(i18n.get("message.type.update.mandatory ")); - } - } - private static void checkMandatoryAndAddMandatoryModuleType(final DistributionSetType updateDistSetType, - final Boolean isMandatory, final SoftwareModuleType swModuleType) { - if (isMandatory) { - updateDistSetType.addMandatoryModuleType(swModuleType); - } else { - updateDistSetType.addOptionalModuleType(swModuleType); + final DistributionSetTypeUpdate update = entityFactory.distributionSetType().update(existingType.getId()) + .description(tagDesc.getValue()) + .colour(ColorPickerHelper.getColorPickedString(getColorPickerLayout().getSelPreview())); + if (distributionSetManagement.countDistributionSetsByType(existingType) <= 0 && null != itemIds + && !itemIds.isEmpty()) { + + update.mandatory(itemIds.stream().filter(itemId -> isMandatoryModuleType(selectedTable.getItem(itemId))) + .collect(Collectors.toList())) + .optional(itemIds.stream().filter(itemId -> isOptionalModuleType(selectedTable.getItem(itemId))) + .collect(Collectors.toList())); } - } - private DistributionSetType removeSWModuleTypesFromDistSetType(final String selectedDistSetType) { + final DistributionSetType updateDistSetType = distributionSetManagement.updateDistributionSetType(update); + + uiNotification.displaySuccess(i18n.get("message.update.success", new Object[] { updateDistSetType.getName() })); + eventBus.publish(this, + new DistributionSetTypeEvent(DistributionSetTypeEnum.UPDATE_DIST_SET_TYPE, updateDistSetType)); - final DistributionSetType distSetType = fetchDistributionSetType(selectedDistSetType); - if (!distSetType.getMandatoryModuleTypes().isEmpty()) { - for (final SoftwareModuleType smType : distSetType.getMandatoryModuleTypes()) { - distSetType.removeModuleType(smType.getId()); - } - } - if (!distSetType.getOptionalModuleTypes().isEmpty()) { - for (final SoftwareModuleType smType : distSetType.getOptionalModuleTypes()) { - distSetType.removeModuleType(smType.getId()); - } - } - return distSetType; } /** @@ -500,8 +467,8 @@ public void populateTagNameCombo() { */ private static LazyQueryContainer getDistSetTypeLazyQueryContainer() { - final LazyQueryContainer disttypeContainer = HawkbitCommonUtil.createLazyQueryContainer( - new BeanQueryFactory(DistributionSetTypeBeanQuery.class)); + final LazyQueryContainer disttypeContainer = HawkbitCommonUtil + .createLazyQueryContainer(new BeanQueryFactory<>(DistributionSetTypeBeanQuery.class)); disttypeContainer.addContainerProperty(SPUILabelDefinitions.VAR_NAME, String.class, "", true, true); return disttypeContainer; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DsMetadataPopupLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DsMetadataPopupLayout.java index 8c363837cf..b7b6a65db3 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DsMetadataPopupLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DsMetadataPopupLayout.java @@ -8,6 +8,7 @@ */ package org.eclipse.hawkbit.ui.distributions.dstable; +import java.util.Collections; import java.util.List; import org.eclipse.hawkbit.repository.DistributionSetManagement; @@ -15,9 +16,11 @@ import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetMetadata; +import org.eclipse.hawkbit.repository.model.MetaData; import org.eclipse.hawkbit.ui.common.AbstractMetadataPopupLayout; import org.springframework.beans.factory.annotation.Autowired; +import com.google.common.collect.Lists; import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.ViewScope; @@ -26,7 +29,7 @@ */ @SpringComponent @ViewScope -public class DsMetadataPopupLayout extends AbstractMetadataPopupLayout { +public class DsMetadataPopupLayout extends AbstractMetadataPopupLayout { private static final long serialVersionUID = -7778944849012048106L; @@ -41,7 +44,7 @@ public class DsMetadataPopupLayout extends AbstractMetadataPopupLayout getMetadataList() { - return getSelectedEntity().getMetadata(); + protected List getMetadataList() { + return Collections.unmodifiableList(getSelectedEntity().getMetadata()); } /** @@ -79,7 +82,7 @@ protected List getMetadataList() { @Override protected void deleteMetadata(final DistributionSet entity, final String key, final String value) { - distributionSetManagement.deleteDistributionSetMetadata(entity, key); + distributionSetManagement.deleteDistributionSetMetadata(entity.getId(), key); } @Override diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/event/MetadataEvent.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/event/MetadataEvent.java index 2436de9e55..492f2d5ceb 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/event/MetadataEvent.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/event/MetadataEvent.java @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.ui.distributions.event; -import org.eclipse.hawkbit.repository.model.DistributionSetMetadata; -import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; +import org.eclipse.hawkbit.repository.model.MetaData; +import org.eclipse.hawkbit.repository.model.SoftwareModule; /** * @@ -24,30 +24,26 @@ public enum MetadataUIEvent { private final MetadataUIEvent metadataUIEvent; - private DistributionSetMetadata distributionSetMetadata; + private final MetaData metadata; - private SoftwareModuleMetadata softwareModuleMetadata; + private final SoftwareModule module; - public MetadataEvent(final MetadataUIEvent metadataUIEvent, final DistributionSetMetadata distributionSetMetadata) { + public MetadataEvent(final MetadataUIEvent metadataUIEvent, final MetaData metadata, final SoftwareModule module) { this.metadataUIEvent = metadataUIEvent; - this.distributionSetMetadata = distributionSetMetadata; - } - - public MetadataEvent(final MetadataUIEvent metadataUIEvent, final SoftwareModuleMetadata softwareModuleMetadata) { - this.metadataUIEvent = metadataUIEvent; - this.softwareModuleMetadata = softwareModuleMetadata; + this.metadata = metadata; + this.module = module; } public MetadataUIEvent getMetadataUIEvent() { return metadataUIEvent; } - public DistributionSetMetadata getDistributionSetMetadata() { - return distributionSetMetadata; + public MetaData getMetaData() { + return metadata; } - public SoftwareModuleMetadata getSoftwareModuleMetadata() { - return softwareModuleMetadata; + public SoftwareModule getModule() { + return module; } } 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 1871eac960..e56a91db25 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 @@ -17,8 +17,6 @@ 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.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleIdName; import org.eclipse.hawkbit.ui.common.DistributionSetIdName; import org.eclipse.hawkbit.ui.common.confirmwindow.layout.AbstractConfirmationWindowLayout; @@ -576,18 +574,12 @@ private IndexedContainer getSWAssignmentsTableContainer() { private void saveAllAssignments(final ConfirmationTab tab) { manageDistUIState.getAssignedList().forEach((distIdName, softIdNameSet) -> { - - final DistributionSet ds = dsManagement.findDistributionSetByIdWithDetails(distIdName.getId()); - final List softIds = softIdNameSet.stream().map(softIdName -> softIdName.getId()) .collect(Collectors.toList()); - - final List softwareModules = softwareManagement.findSoftwareModulesById(softIds); - - softwareModules.forEach(ds::addModule); - dsManagement.updateDistributionSet(ds); + dsManagement.assignSoftwareModules(distIdName.getId(), softIds); }); + int count = 0; for (final Entry> entry : manageDistUIState .getAssignedList().entrySet()) { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwMetadataPopupLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwMetadataPopupLayout.java index b98f72bb7f..cee06b822a 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwMetadataPopupLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwMetadataPopupLayout.java @@ -8,11 +8,13 @@ */ package org.eclipse.hawkbit.ui.distributions.smtable; +import java.util.Collections; import java.util.List; import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.SpPermissionChecker; +import org.eclipse.hawkbit.repository.model.MetaData; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; import org.eclipse.hawkbit.ui.common.AbstractMetadataPopupLayout; @@ -28,7 +30,7 @@ */ @SpringComponent @ViewScope -public class SwMetadataPopupLayout extends AbstractMetadataPopupLayout { +public class SwMetadataPopupLayout extends AbstractMetadataPopupLayout { private static final long serialVersionUID = -1252090014161012563L; @@ -51,10 +53,10 @@ protected void checkForDuplicate(final SoftwareModule entity, final String value */ @Override protected SoftwareModuleMetadata createMetadata(final SoftwareModule entity, final String key, final String value) { - final SoftwareModuleMetadata swMetadata = softwareManagement - .createSoftwareModuleMetadata(entityFactory.generateSoftwareModuleMetadata(entity, key, value)); + final SoftwareModuleMetadata swMetadata = softwareManagement.createSoftwareModuleMetadata(entity.getId(), + entityFactory.generateMetadata(key, value)); setSelectedEntity(swMetadata.getSoftwareModule()); - eventBus.publish(this, new MetadataEvent(MetadataUIEvent.CREATE_SOFTWARE_MODULE_METADATA, swMetadata)); + eventBus.publish(this, new MetadataEvent(MetadataUIEvent.CREATE_SOFTWARE_MODULE_METADATA, swMetadata, entity)); return swMetadata; } @@ -63,15 +65,16 @@ protected SoftwareModuleMetadata createMetadata(final SoftwareModule entity, fin */ @Override protected SoftwareModuleMetadata updateMetadata(final SoftwareModule entity, final String key, final String value) { - final SoftwareModuleMetadata swMetadata = softwareManagement - .updateSoftwareModuleMetadata(entityFactory.generateSoftwareModuleMetadata(entity, key, value)); + final SoftwareModuleMetadata swMetadata = softwareManagement.updateSoftwareModuleMetadata(entity.getId(), + entityFactory.generateMetadata(key, value)); setSelectedEntity(swMetadata.getSoftwareModule()); return swMetadata; } @Override - protected List getMetadataList() { - return softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(getSelectedEntity().getId()); + protected List getMetadataList() { + return Collections.unmodifiableList( + softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(getSelectedEntity().getId())); } /** @@ -79,9 +82,9 @@ protected List getMetadataList() { */ @Override protected void deleteMetadata(final SoftwareModule entity, final String key, final String value) { - final SoftwareModuleMetadata swMetadata = entityFactory.generateSoftwareModuleMetadata(entity, key, value); softwareManagement.deleteSoftwareModuleMetadata(entity.getId(), key); - eventBus.publish(this, new MetadataEvent(MetadataUIEvent.DELETE_SOFTWARE_MODULE_METADATA, swMetadata)); + eventBus.publish(this, new MetadataEvent(MetadataUIEvent.DELETE_SOFTWARE_MODULE_METADATA, + entityFactory.generateMetadata(key, value), entity)); } @Override diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleDetails.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleDetails.java index 046de5e5e1..221d57a6a7 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleDetails.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleDetails.java @@ -10,8 +10,8 @@ import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.SoftwareManagement; +import org.eclipse.hawkbit.repository.model.MetaData; import org.eclipse.hawkbit.repository.model.SoftwareModule; -import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent; import org.eclipse.hawkbit.ui.artifacts.smtable.SoftwareModuleAddUpdateWindow; import org.eclipse.hawkbit.ui.common.detailslayout.AbstractNamedVersionedEntityTableDetailsLayout; @@ -82,14 +82,13 @@ protected void init() { @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final MetadataEvent event) { UI.getCurrent().access(() -> { - final SoftwareModuleMetadata softwareModuleMetadata = event.getSoftwareModuleMetadata(); - if (softwareModuleMetadata != null - && isSoftwareModuleSelected(softwareModuleMetadata.getSoftwareModule())) { + final MetaData softwareModuleMetadata = event.getMetaData(); + if (softwareModuleMetadata != null && isSoftwareModuleSelected(event.getModule())) { if (event.getMetadataUIEvent() == MetadataEvent.MetadataUIEvent.CREATE_SOFTWARE_MODULE_METADATA) { - swmMetadataTable.createMetadata(event.getSoftwareModuleMetadata().getKey()); + swmMetadataTable.createMetadata(event.getMetaData().getKey()); } else if (event .getMetadataUIEvent() == MetadataEvent.MetadataUIEvent.DELETE_SOFTWARE_MODULE_METADATA) { - swmMetadataTable.deleteMetadata(event.getSoftwareModuleMetadata().getKey()); + swmMetadataTable.deleteMetadata(event.getMetaData().getKey()); } } }); 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 97a85a1c8b..97a1ff046e 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 @@ -91,8 +91,6 @@ public class CreateOrUpdateFilterHeader extends VerticalLayout implements Button @Autowired private AutoCompleteTextFieldComponent queryTextField; - private HorizontalLayout breadcrumbLayout; - private Button breadcrumbButton; private Label breadcrumbName; @@ -238,6 +236,7 @@ private void createListeners() { }; queryTextField.addTextChangeListener((valid, query) -> enableDisableSaveButton(!valid, query)); + } private void onFilterNameChange(final TextChangeEvent event) { @@ -260,7 +259,7 @@ private void buildLayout() { titleFilterIconsLayout.addComponents(headerCaption, captionLayout); titleFilterIconsLayout.setSpacing(true); - breadcrumbLayout = new HorizontalLayout(); + final HorizontalLayout breadcrumbLayout = new HorizontalLayout(); breadcrumbLayout.addComponent(breadcrumbButton); breadcrumbLayout.addComponent(new Label(">")); breadcrumbName = new LabelBuilder().buildCaptionLabel(); @@ -319,10 +318,7 @@ private void enableDisableSaveButton(final boolean validationFailed, final Strin } private static boolean isNameAndQueryEmpty(final String name, final String query) { - if (Strings.isNullOrEmpty(name) && Strings.isNullOrEmpty(query)) { - return true; - } - return false; + return Strings.isNullOrEmpty(name) && Strings.isNullOrEmpty(query); } private SPUIButton createSearchResetIcon() { @@ -383,10 +379,8 @@ && manadatoryFieldsPresent()) { } private void createTargetFilterQuery() { - final TargetFilterQuery targetFilterQuery = entityFactory.generateTargetFilterQuery(); - targetFilterQuery.setName(nameTextField.getValue()); - targetFilterQuery.setQuery(queryTextField.getValue()); - targetFilterQueryManagement.createTargetFilterQuery(targetFilterQuery); + final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement.createTargetFilterQuery(entityFactory + .targetFilterQuery().create().name(nameTextField.getValue()).query(queryTextField.getValue())); notification.displaySuccess( i18n.get("message.create.filter.success", new Object[] { targetFilterQuery.getName() })); eventBus.publish(this, CustomFilterUIEvent.CREATE_TARGET_FILTER_QUERY); @@ -398,10 +392,9 @@ private void updateCustomFilter() { return; } final TargetFilterQuery targetFilterQuery = tfQuery.get(); - targetFilterQuery.setName(nameTextField.getValue()); - targetFilterQuery.setQuery(queryTextField.getValue()); final TargetFilterQuery updatedTargetFilter = targetFilterQueryManagement - .updateTargetFilterQuery(targetFilterQuery); + .updateTargetFilterQuery(entityFactory.targetFilterQuery().update(targetFilterQuery.getId()) + .name(nameTextField.getValue()).query(queryTextField.getValue())); filterManagementUIState.setTfQuery(updatedTargetFilter); oldFilterName = nameTextField.getValue(); oldFilterQuery = queryTextField.getValue(); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/DistributionSetSelectWindow.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/DistributionSetSelectWindow.java index de5977a446..9ba409938d 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/DistributionSetSelectWindow.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/DistributionSetSelectWindow.java @@ -182,8 +182,7 @@ private void updateTargetFilterQueryDS(final Long targetFilterQueryId, final Lon if (dsId != null) { confirmWithConsequencesDialog(tfq, dsId); } else { - tfq.setAutoAssignDistributionSet(null); - targetFilterQueryManagement.updateTargetFilterQuery(tfq); + targetFilterQueryManagement.updateTargetFilterQueryAutoAssignDS(targetFilterQueryId, null); eventBus.publish(this, CustomFilterUIEvent.UPDATED_TARGET_FILTER_QUERY); } @@ -195,8 +194,7 @@ private void confirmWithConsequencesDialog(final TargetFilterQuery tfq, final Lo @Override public void onConfirmResult(final boolean accepted) { if (accepted) { - tfq.setAutoAssignDistributionSet(distributionSetManagement.findDistributionSetById(dsId)); - targetFilterQueryManagement.updateTargetFilterQuery(tfq); + targetFilterQueryManagement.updateTargetFilterQueryAutoAssignDS(tfq.getId(), dsId); eventBus.publish(this, CustomFilterUIEvent.UPDATED_TARGET_FILTER_QUERY); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/layouts/AbstractCreateUpdateTagLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/layouts/AbstractCreateUpdateTagLayout.java index 205d233539..b43a029f6d 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/layouts/AbstractCreateUpdateTagLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/layouts/AbstractCreateUpdateTagLayout.java @@ -10,8 +10,10 @@ import javax.annotation.PreDestroy; +import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.TagManagement; +import org.eclipse.hawkbit.repository.builder.TagUpdate; import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.repository.model.NamedEntity; import org.eclipse.hawkbit.repository.model.Tag; @@ -77,6 +79,9 @@ public abstract class AbstractCreateUpdateTagLayout exten @Autowired protected transient TagManagement tagManagement; + @Autowired + protected transient EntityFactory entityFactory; + @Autowired protected transient EventBus.SessionEventBus eventBus; @@ -550,22 +555,16 @@ protected void createNewTag() { * update tag. */ protected void updateExistingTag(final Tag targetObj) { - final String nameUpdateValue = HawkbitCommonUtil.trimAndNullIfEmpty(tagName.getValue()); - final String descUpdateValue = HawkbitCommonUtil.trimAndNullIfEmpty(tagDesc.getValue()); - - if (null != nameUpdateValue) { - targetObj.setName(nameUpdateValue); - targetObj.setDescription(null != descUpdateValue ? descUpdateValue : null); - targetObj.setColour(ColorPickerHelper.getColorPickedString(colorPickerLayout.getSelPreview())); - if (targetObj instanceof TargetTag) { - tagManagement.updateTargetTag((TargetTag) targetObj); - } else if (targetObj instanceof DistributionSetTag) { - tagManagement.updateDistributionSetTag((DistributionSetTag) targetObj); - } - uiNotification.displaySuccess(i18n.get("message.update.success", new Object[] { targetObj.getName() })); - } else { - uiNotification.displayValidationError(i18n.get("message.tag.update.mandatory")); + final TagUpdate update = entityFactory.tag().update(targetObj.getId()).name(tagName.getValue()) + .description(tagDesc.getValue()) + .colour(ColorPickerHelper.getColorPickedString(colorPickerLayout.getSelPreview())); + if (targetObj instanceof TargetTag) { + tagManagement.updateTargetTag(update); + } else if (targetObj instanceof DistributionSetTag) { + tagManagement.updateDistributionSetTag(update); } + uiNotification.displaySuccess(i18n.get("message.update.success", new Object[] { targetObj.getName() })); + } protected void displaySuccess(final String tagName) { 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 7676e4c904..b3b767bc85 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 @@ -9,8 +9,6 @@ package org.eclipse.hawkbit.ui.management.dstable; import java.util.Collections; -import java.util.HashSet; -import java.util.Set; import javax.annotation.PostConstruct; @@ -46,6 +44,7 @@ import org.vaadin.addons.lazyquerycontainer.LazyQueryDefinition; import org.vaadin.spring.events.EventBus; +import com.google.common.collect.Sets; import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.ViewScope; import com.vaadin.ui.CheckBox; @@ -88,9 +87,8 @@ public class DistributionAddUpdateWindowLayout extends CustomComponent { private TextArea descTextArea; private CheckBox reqMigStepCheckbox; private ComboBox distsetTypeNameComboBox; - private boolean editDistribution = Boolean.FALSE; + private boolean editDistribution; private Long editDistId; - private CommonDialogWindow window; private FormLayout formLayout; @@ -182,7 +180,7 @@ private LazyQueryContainer getDistSetTypeLazyQueryContainer() { dtQF.setQueryConfiguration(Collections.emptyMap()); final LazyQueryContainer disttypeContainer = new LazyQueryContainer( - new LazyQueryDefinition(true, SPUIDefinitions.DIST_TYPE_SIZE, SPUILabelDefinitions.VAR_NAME), dtQF); + new LazyQueryDefinition(true, SPUIDefinitions.DIST_TYPE_SIZE, SPUILabelDefinitions.VAR_ID), dtQF); disttypeContainer.addContainerProperty(SPUILabelDefinitions.VAR_NAME, String.class, "", true, true); @@ -202,17 +200,14 @@ private void updateDistribution() { if (isDuplicate()) { return; } - final String name = HawkbitCommonUtil.trimAndNullIfEmpty(distNameTextField.getValue()); - final String version = HawkbitCommonUtil.trimAndNullIfEmpty(distVersionTextField.getValue()); - final String distSetTypeName = HawkbitCommonUtil - .trimAndNullIfEmpty((String) distsetTypeNameComboBox.getValue()); - final DistributionSet currentDS = distributionSetManagement.findDistributionSetByIdWithDetails(editDistId); - final String desc = HawkbitCommonUtil.trimAndNullIfEmpty(descTextArea.getValue()); final boolean isMigStepReq = reqMigStepCheckbox.getValue(); + final Long distSetTypeId = (Long) distsetTypeNameComboBox.getValue(); - /* identify the changes */ - setDistributionValues(currentDS, name, version, distSetTypeName, desc, isMigStepReq); - distributionSetManagement.updateDistributionSet(currentDS); + final DistributionSet currentDS = distributionSetManagement + .updateDistributionSet(entityFactory.distributionSet().update(editDistId) + .name(distNameTextField.getValue()).description(descTextArea.getValue()) + .version(distVersionTextField.getValue()).requiredMigrationStep(isMigStepReq) + .type(distributionSetManagement.findDistributionSetTypeById(distSetTypeId))); notificationMessage.displaySuccess(i18n.get("message.new.dist.save.success", new Object[] { currentDS.getName(), currentDS.getVersion() })); // update table row+details layout @@ -228,46 +223,21 @@ private void addNewDistribution() { final String name = HawkbitCommonUtil.trimAndNullIfEmpty(distNameTextField.getValue()); final String version = HawkbitCommonUtil.trimAndNullIfEmpty(distVersionTextField.getValue()); - final String distSetTypeName = HawkbitCommonUtil - .trimAndNullIfEmpty((String) distsetTypeNameComboBox.getValue()); - + final Long distSetTypeId = (Long) distsetTypeNameComboBox.getValue(); final String desc = HawkbitCommonUtil.trimAndNullIfEmpty(descTextArea.getValue()); final boolean isMigStepReq = reqMigStepCheckbox.getValue(); - DistributionSet newDist = entityFactory.generateDistributionSet(); - setDistributionValues(newDist, name, version, distSetTypeName, desc, isMigStepReq); - newDist = distributionSetManagement.createDistributionSet(newDist); + final DistributionSet newDist = distributionSetManagement + .createDistributionSet(entityFactory.distributionSet().create().name(name).version(version) + .description(desc).type(distributionSetManagement.findDistributionSetTypeById(distSetTypeId)) + .requiredMigrationStep(isMigStepReq)); notificationMessage.displaySuccess( i18n.get("message.new.dist.save.success", new Object[] { newDist.getName(), newDist.getVersion() })); - final Set s = new HashSet<>(); - s.add(new DistributionSetIdName(newDist.getId(), newDist.getName(), newDist.getVersion())); final DistributionSetTable distributionSetTable = SpringContextHelper.getBean(DistributionSetTable.class); - distributionSetTable.setValue(s); - } - - /** - * Set Values for Distribution set. - * - * @param distributionSet - * as reference - * @param name - * as string - * @param version - * as string - * @param desc - * as string - * @param isMigStepReq - * as string - */ - private void setDistributionValues(final DistributionSet distributionSet, final String name, final String version, - final String distSetTypeName, final String desc, final boolean isMigStepReq) { - distributionSet.setName(name); - distributionSet.setVersion(version); - distributionSet.setType(distributionSetManagement.findDistributionSetTypeByName(distSetTypeName)); - distributionSet.setDescription(desc != null ? desc : ""); - distributionSet.setRequiredMigrationStep(isMigStepReq); + distributionSetTable.setValue( + Sets.newHashSet(new DistributionSetIdName(newDist.getId(), newDist.getName(), newDist.getVersion()))); } private boolean isDuplicate() { @@ -324,9 +294,10 @@ private void populateValuesOfDistribution(final Long editDistId) { distNameTextField.setValue(distSet.getName()); distVersionTextField.setValue(distSet.getVersion()); if (distSet.getType().isDeleted()) { - distsetTypeNameComboBox.addItem(distSet.getType().getName()); + distsetTypeNameComboBox.addItem(distSet.getType().getId()); } - distsetTypeNameComboBox.setValue(distSet.getType().getName()); + distsetTypeNameComboBox.setValue(distSet.getType().getId()); + reqMigStepCheckbox.setValue(distSet.isRequiredMigrationStep()); if (distSet.getDescription() != null) { descTextArea.setValue(distSet.getDescription()); @@ -344,11 +315,9 @@ public CommonDialogWindow getWindow(final Long editDistId) { resetComponents(); populateDistSetTypeNameCombo(); populateValuesOfDistribution(editDistId); - window = new WindowBuilder(SPUIDefinitions.CREATE_UPDATE_WINDOW).caption(i18n.get("caption.add.new.dist")) + return new WindowBuilder(SPUIDefinitions.CREATE_UPDATE_WINDOW).caption(i18n.get("caption.add.new.dist")) .content(this).layout(formLayout).i18n(i18n).saveDialogCloseListener(new SaveOnCloseDialogListener()) .buildCommonDialogWindow(); - - return window; } /** @@ -357,7 +326,7 @@ public CommonDialogWindow getWindow(final Long editDistId) { private void populateDistSetTypeNameCombo() { distsetTypeNameComboBox.setContainerDataSource(getDistSetTypeLazyQueryContainer()); distsetTypeNameComboBox.setItemCaptionPropertyId(SPUILabelDefinitions.VAR_NAME); - distsetTypeNameComboBox.setValue(getDefaultDistributionSetType().getName()); + distsetTypeNameComboBox.setValue(getDefaultDistributionSetType().getId()); } } 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 7d35ff132a..aa2103ae58 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 @@ -12,7 +12,6 @@ import java.util.List; -import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.ui.colorpicker.ColorPickerConstants; import org.eclipse.hawkbit.ui.colorpicker.ColorPickerHelper; @@ -22,7 +21,6 @@ import org.eclipse.hawkbit.ui.push.DistributionSetTagUpdatedEventContainer; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; -import org.springframework.beans.factory.annotation.Autowired; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -39,9 +37,6 @@ public class CreateUpdateDistributionTagLayoutWindow extends AbstractCreateUpdat private static final long serialVersionUID = 444276149954167545L; - @Autowired - private transient EntityFactory entityFactory; - private static final String TARGET_TAG_NAME_DYNAMIC_STYLE = "new-target-tag-name"; private static final String MSG_TEXTFIELD_NAME = "textfield.name"; @@ -103,13 +98,14 @@ protected DistributionSetTag findEntityByName() { protected void createNewTag() { super.createNewTag(); if (isNotEmpty(getTagNameValue())) { - DistributionSetTag newDistTag = entityFactory.generateDistributionSetTag(tagNameValue, tagDescValue, - ColorPickerConstants.START_COLOR.getCSS()); + String colour = ColorPickerConstants.START_COLOR.getCSS(); if (isNotEmpty(getColorPicked())) { - newDistTag.setColour(getColorPicked()); + colour = getColorPicked(); } - newDistTag = tagManagement.createDistributionSetTag(newDistTag); + + final DistributionSetTag newDistTag = tagManagement.createDistributionSetTag( + entityFactory.tag().create().name(tagNameValue).description(tagDescValue).colour(colour)); displaySuccess(newDistTag.getName()); resetDistTagValues(); } else { 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 46acf6b48d..00e7014505 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,7 +11,7 @@ import java.util.Collections; import org.eclipse.hawkbit.repository.EntityFactory; -import org.eclipse.hawkbit.repository.model.DistributionSetTag; +import org.eclipse.hawkbit.repository.model.Tag; import org.eclipse.hawkbit.ui.common.filterlayout.AbstractFilterButtonClickBehaviour; import org.eclipse.hawkbit.ui.common.filterlayout.AbstractFilterButtons; import org.eclipse.hawkbit.ui.management.event.DistributionTagDropEvent; @@ -46,7 +46,9 @@ @ViewScope public class DistributionTagButtons extends AbstractFilterButtons { - private static final long serialVersionUID = -8151483237450892057L; + private static final String NO_TAG = "NO TAG"; + + private static final long serialVersionUID = 1L; @Autowired private DistributionTagDropEvent spDistTagDropEvent; @@ -60,7 +62,7 @@ public class DistributionTagButtons extends AbstractFilterButtons { @Override public void init(final AbstractFilterButtonClickBehaviour filterButtonClickBehaviour) { super.init(filterButtonClickBehaviour); - addNewTag(entityFactory.generateDistributionSetTag("NO TAG")); + addNewTag(entityFactory.tag().create().name(NO_TAG).build()); } @EventBusListenerMethod(scope = EventScope.SESSION) @@ -102,8 +104,7 @@ protected String getButtonsTableId() { protected LazyQueryContainer createButtonsLazyQueryContainer() { final BeanQueryFactory tagQF = new BeanQueryFactory<>(DistributionTagBeanQuery.class); tagQF.setQueryConfiguration(Collections.emptyMap()); - return HawkbitCommonUtil.createDSLazyQueryContainer( - new BeanQueryFactory(DistributionTagBeanQuery.class)); + return HawkbitCommonUtil.createDSLazyQueryContainer(new BeanQueryFactory<>(DistributionTagBeanQuery.class)); } @@ -141,11 +142,11 @@ protected String getButttonWrapperIdPrefix() { private void refreshTagTable() { ((LazyQueryContainer) getContainerDataSource()).refresh(); removeGeneratedColumn(FILTER_BUTTON_COLUMN); - addNewTag(entityFactory.generateDistributionSetTag("NO TAG")); + addNewTag(entityFactory.tag().create().name(NO_TAG).build()); addColumn(); } - private void addNewTag(final DistributionSetTag daTag) { + private void addNewTag(final Tag daTag) { final LazyQueryContainer targetTagContainer = (LazyQueryContainer) getContainerDataSource(); final Object addItem = targetTagContainer.addItem(); final Item item = targetTagContainer.getItem(addItem); 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 63f46cb125..96bf52a3f7 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 @@ -217,12 +217,9 @@ protected Component getUnsavedActionsWindowContent() { @Override protected boolean hasUnsavedActions() { - if (!managementUIState.getDeletedDistributionList().isEmpty() + return !managementUIState.getDeletedDistributionList().isEmpty() || !managementUIState.getDeletedTargetList().isEmpty() - || !managementUIState.getAssignedList().isEmpty()) { - return true; - } - return false; + || !managementUIState.getAssignedList().isEmpty(); } @Override 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 11a786c725..4f8b8cfc3b 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 @@ -169,9 +169,9 @@ private void saveAllAssignments(final ConfirmationTab tab) { for (final Map.Entry> mapEntry : saveAssignedList.entrySet()) { tempIdList = saveAssignedList.get(mapEntry.getKey()); - final String[] ids = tempIdList.stream().map(t -> t.getControllerId()).toArray(size -> new String[size]); final DistributionSetAssignmentResult distributionSetAssignmentResult = deploymentManagement - .assignDistributionSet(mapEntry.getKey(), actionType, forcedTimeStamp, ids); + .assignDistributionSet(mapEntry.getKey(), actionType, forcedTimeStamp, + tempIdList.stream().map(t -> t.getControllerId()).collect(Collectors.toList())); if (distributionSetAssignmentResult.getAssigned() > 0) { successAssignmentCount += distributionSetAssignmentResult.getAssigned(); 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 3a28bdc3f0..c6721b6e48 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 @@ -327,7 +327,7 @@ private String saveAllAssignments() { return i18n.get("message.bulk.upload.assignment.failed"); } deploymentManagement.assignDistributionSet(targetBulkUpload.getDsNameAndVersion().getId(), actionType, - forcedTimeStamp, targetsList.toArray(new String[targetsList.size()])); + forcedTimeStamp, targetsList); return null; } @@ -398,9 +398,8 @@ private void addNewTarget(final String controllerId, final String name) { final String newDesc = HawkbitCommonUtil.trimAndNullIfEmpty(descTextArea.getValue()); /* create new target entity */ - final Target newTarget = entityFactory.generateTarget(newControllerId); - setTargetValues(newTarget, newName, newDesc); - targetManagement.createTarget(newTarget); + targetManagement.createTarget(entityFactory.target().create().controllerId(newControllerId) + .name(newName).description(newDesc)); managementUIState.getTargetTableFilters().getBulkUpload().getTargetsCreated().add(newControllerId); successfullTargetCount++; } @@ -408,16 +407,6 @@ private void addNewTarget(final String controllerId, final String name) { } } - private static void setTargetValues(final Target target, final String name, final String description) { - if (null == name) { - target.setName(target.getControllerId()); - } else { - target.setName(name); - } - target.setName(name == null ? target.getControllerId() : name); - target.setDescription(description); - } - private boolean mandatoryCheck(final String newControlllerId) { if (newControlllerId == null) { failedTargetCount++; 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 7a52c48cd1..478b7e17f1 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 @@ -132,32 +132,23 @@ private void buildLayout() { * Update the Target if modified. */ public void updateTarget() { - - final String newName = HawkbitCommonUtil.trimAndNullIfEmpty(nameTextField.getValue()); - final String newDesc = HawkbitCommonUtil.trimAndNullIfEmpty(descTextArea.getValue()); - /* get latest entity */ - final Target latestTarget = targetManagement.findTargetByControllerIDWithDetails(controllerId); - /* update new name & desc */ - setTargetValues(latestTarget, newName, newDesc); /* save updated entity */ - targetManagement.updateTarget(latestTarget); + final Target target = targetManagement.updateTarget(entityFactory.target().update(controllerId) + .name(nameTextField.getValue()).description(descTextArea.getValue())); /* display success msg */ - uINotification.displaySuccess(i18n.get("message.update.success", new Object[] { latestTarget.getName() })); + uINotification.displaySuccess(i18n.get("message.update.success", new Object[] { target.getName() })); // publishing through event bus - eventBus.publish(this, new TargetTableEvent(BaseEntityEventType.UPDATED_ENTITY, latestTarget)); + eventBus.publish(this, new TargetTableEvent(BaseEntityEventType.UPDATED_ENTITY, target)); } private void addNewTarget() { - final String newControlllerId = HawkbitCommonUtil.trimAndNullIfEmpty(controllerIDTextField.getValue()); + final String newControllerId = HawkbitCommonUtil.trimAndNullIfEmpty(controllerIDTextField.getValue()); final String newName = HawkbitCommonUtil.trimAndNullIfEmpty(nameTextField.getValue()); final String newDesc = HawkbitCommonUtil.trimAndNullIfEmpty(descTextArea.getValue()); - /* create new target entity */ - Target newTarget = entityFactory.generateTarget(newControlllerId); - /* set values to the new target entity */ - setTargetValues(newTarget, newName, newDesc); /* save new target */ - newTarget = targetManagement.createTarget(newTarget); + final Target newTarget = targetManagement.createTarget( + entityFactory.target().create().controllerId(newControllerId).name(newName).description(newDesc)); final TargetTable targetTable = SpringContextHelper.getBean(TargetTable.class); final Set s = new HashSet<>(); s.add(newTarget.getTargetIdName()); @@ -203,11 +194,6 @@ public void resetComponents() { editTarget = Boolean.FALSE; } - private void setTargetValues(final Target target, final String name, final String description) { - target.setName(name == null ? target.getControllerId() : name); - target.setDescription(description); - } - private boolean isDuplicate() { final String newControlllerId = controllerIDTextField.getValue(); final Target existingTarget = targetManagement.findTargetByControllerID(newControlllerId.trim()); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/CreateUpdateTargetTagLayoutWindow.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/CreateUpdateTargetTagLayoutWindow.java index 1aad784e14..ddbf4562c4 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/CreateUpdateTargetTagLayoutWindow.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/CreateUpdateTargetTagLayoutWindow.java @@ -12,7 +12,6 @@ import java.util.List; -import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.model.TargetTag; import org.eclipse.hawkbit.ui.colorpicker.ColorPickerConstants; import org.eclipse.hawkbit.ui.colorpicker.ColorPickerHelper; @@ -20,7 +19,6 @@ import org.eclipse.hawkbit.ui.push.TargetTagCreatedEventContainer; import org.eclipse.hawkbit.ui.push.TargetTagDeletedEventContainer; import org.eclipse.hawkbit.ui.push.TargetTagUpdatedEventContainer; -import org.springframework.beans.factory.annotation.Autowired; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -37,9 +35,6 @@ public class CreateUpdateTargetTagLayoutWindow extends AbstractCreateUpdateTagLa private static final long serialVersionUID = 2446682350481560235L; - @Autowired - private transient EntityFactory entityFactory; - @EventBusListenerMethod(scope = EventScope.SESSION) // Exception squid:S1172 - event not needed @SuppressWarnings({ "squid:S1172" }) @@ -121,15 +116,13 @@ protected TargetTag findEntityByName() { protected void createNewTag() { super.createNewTag(); if (isNotEmpty(getTagNameValue())) { - TargetTag newTargetTag = entityFactory.generateTargetTag(getTagNameValue()); - if (isNotEmpty(getTagDescValue())) { - newTargetTag.setDescription(getTagDescValue()); - } - newTargetTag.setColour(ColorPickerConstants.START_COLOR.getCSS()); + String colour = ColorPickerConstants.START_COLOR.getCSS(); if (isNotEmpty(getColorPicked())) { - newTargetTag.setColour(getColorPicked()); + colour = getColorPicked(); } - newTargetTag = tagManagement.createTargetTag(newTargetTag); + + final TargetTag newTargetTag = tagManagement.createTargetTag( + entityFactory.tag().create().name(getTagNameValue()).description(getTagDescValue()).colour(colour)); displaySuccess(newTargetTag.getName()); } else { displayValidationError(i18n.get(MESSAGE_ERROR_MISSING_TAGNAME)); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/FilterByStatusLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/FilterByStatusLayout.java index cd6625c93f..09d82d3603 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/FilterByStatusLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/FilterByStatusLayout.java @@ -168,9 +168,9 @@ private void getTargetFilterStatuses() { registered = SPUIComponentProvider.getButton(UIComponentIdProvider.REGISTERED_STATUS_ICON, TargetUpdateStatus.REGISTERED.toString(), i18n.get("tooltip.status.registered"), SPUIButtonDefinitions.SP_BUTTON_STATUS_STYLE, false, FontAwesome.SQUARE, SPUIButtonStyleSmall.class); - overdue = SPUIComponentProvider.getButton(UIComponentIdProvider.OVERDUE_STATUS_ICON, - OVERDUE_CAPTION, i18n.get("tooltip.status.overdue"), - SPUIButtonDefinitions.SP_BUTTON_STATUS_STYLE, false, FontAwesome.SQUARE, SPUIButtonStyleSmall.class); + overdue = SPUIComponentProvider.getButton(UIComponentIdProvider.OVERDUE_STATUS_ICON, OVERDUE_CAPTION, + i18n.get("tooltip.status.overdue"), SPUIButtonDefinitions.SP_BUTTON_STATUS_STYLE, false, + FontAwesome.SQUARE, SPUIButtonStyleSmall.class); applyStatusBtnStyle(); unknown.setData("filterStatusOne"); inSync.setData("filterStatusTwo"); @@ -320,24 +320,15 @@ private void removeClickedStyle() { * @return */ private boolean isStatusFilterApplied() { - if (isPendingOrUnknownBtnClicked() || isErrorOrRegisteredBtnClicked() || inSyncBtnClicked) { - return true; - } - return false; + return isPendingOrUnknownBtnClicked() || isErrorOrRegisteredBtnClicked() || inSyncBtnClicked; } private boolean isPendingOrUnknownBtnClicked() { - if (unknownBtnClicked || pendingBtnClicked) { - return true; - } - return false; + return unknownBtnClicked || pendingBtnClicked; } private boolean isErrorOrRegisteredBtnClicked() { - if (errorBtnClicked || registeredBtnClicked) { - return true; - } - return false; + return errorBtnClicked || registeredBtnClicked; } @PreDestroy diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/TargetFilterQueryButtons.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/TargetFilterQueryButtons.java index 81a874df5d..f74a29fdc9 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/TargetFilterQueryButtons.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/TargetFilterQueryButtons.java @@ -38,17 +38,11 @@ import com.vaadin.ui.themes.ValoTheme; /** - * Target filter query{#link {@link TargetFilterQuery} buttons layout . - * - * - * + * Target filter query{#link {@link TargetFilterQuery} buttons layout. */ @SpringComponent @ViewScope public class TargetFilterQueryButtons extends Table { - /** - * - */ private static final long serialVersionUID = 9188095103191937850L; protected static final String FILTER_BUTTON_COLUMN = "filterButton"; @@ -115,10 +109,6 @@ protected void addColumn() { addGeneratedColumn(FILTER_BUTTON_COLUMN, (source, itemId, columnId) -> addGeneratedCell(itemId)); } - /** - * @param itemId - * @return - */ private Button addGeneratedCell(final Object itemId) { final Item item = getItem(itemId); final Long id = (Long) item.getItemProperty(SPUILabelDefinitions.VAR_ID).getValue(); @@ -131,16 +121,9 @@ private Button addGeneratedCell(final Object itemId) { return typeButton; } - /** - * @param id - * @return - */ private boolean isClickedByDefault(final Long id) { - if (managementUIState.getTargetTableFilters().getTargetFilterQuery().isPresent() - && (managementUIState.getTargetTableFilters().getTargetFilterQuery().get().getId().equals(id))) { - return true; - } - return false; + return managementUIState.getTargetTableFilters().getTargetFilterQuery().map(q -> q.getId().equals(id)) + .orElse(false); } private Button createFilterButton(final Long id, final String name, final Object itemId) { 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 37ba5af736..ba9b2f8b8f 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 @@ -15,8 +15,8 @@ import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.TargetManagement; +import org.eclipse.hawkbit.repository.model.Tag; 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.ui.common.filterlayout.AbstractFilterButtons; import org.eclipse.hawkbit.ui.common.table.AbstractTable; @@ -59,8 +59,9 @@ @SpringComponent @ViewScope public class TargetTagFilterButtons extends AbstractFilterButtons { + private static final String NO_TAG = "NO TAG"; - private static final long serialVersionUID = 5049554600376508073L; + private static final long serialVersionUID = 1L; @Autowired private ManagementUIState managementUIState; @@ -95,7 +96,7 @@ public class TargetTagFilterButtons extends AbstractFilterButtons { public void init(final TargetTagFilterButtonClick filterButtonClickBehaviour) { this.filterButtonClickBehaviour = filterButtonClickBehaviour; super.init(filterButtonClickBehaviour); - addNewTargetTag(entityFactory.generateTargetTag("NO TAG")); + addNewTargetTag(entityFactory.tag().create().name(NO_TAG).build()); } @EventBusListenerMethod(scope = EventScope.SESSION) @@ -120,8 +121,7 @@ protected String getButtonsTableId() { @Override protected LazyQueryContainer createButtonsLazyQueryContainer() { - return HawkbitCommonUtil - .createDSLazyQueryContainer(new BeanQueryFactory(TargetTagBeanQuery.class)); + return HawkbitCommonUtil.createDSLazyQueryContainer(new BeanQueryFactory<>(TargetTagBeanQuery.class)); } @@ -307,7 +307,7 @@ void onEventTargetDeletedEvent(final TargetTagDeletedEventContainer eventContain private void refreshContainer() { removeGeneratedColumn(FILTER_BUTTON_COLUMN); ((LazyQueryContainer) getContainerDataSource()).refresh(); - addNewTargetTag(entityFactory.generateTargetTag("NO TAG")); + addNewTargetTag(entityFactory.tag().create().name(NO_TAG).build()); addColumn(); } @@ -320,7 +320,7 @@ void onEvent(final ManagementUIEvent event) { } @SuppressWarnings("unchecked") - private void addNewTargetTag(final TargetTag newTargetTag) { + private void addNewTargetTag(final Tag newTargetTag) { final LazyQueryContainer targetTagContainer = (LazyQueryContainer) getContainerDataSource(); final Object addItem = targetTagContainer.addItem(); final Item item = targetTagContainer.getItem(addItem); 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 461a300315..0706feea99 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 @@ -12,14 +12,12 @@ 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.ActionType; 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.RolloutGroupErrorAction; import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupErrorCondition; @@ -92,9 +90,6 @@ public class AddUpdateRolloutWindowLayout extends GridLayout { @Autowired private transient RolloutManagement rolloutManagement; - @Autowired - private transient DistributionSetManagement distributionSetManagement; - @Autowired private transient TargetManagement targetManagement; @@ -191,11 +186,10 @@ public CommonDialogWindow getWindow(final Long rolloutId) { public CommonDialogWindow getWindow() { resetComponents(); - final CommonDialogWindow commonDialogWindow = new WindowBuilder(SPUIDefinitions.CREATE_UPDATE_WINDOW) - .caption(i18n.get("caption.configure.rollout")).content(this).layout(this).i18n(i18n) + return new WindowBuilder(SPUIDefinitions.CREATE_UPDATE_WINDOW).caption(i18n.get("caption.configure.rollout")) + .content(this).layout(this).i18n(i18n) .helpLink(uiProperties.getLinks().getDocumentation().getRolloutView()) .saveDialogCloseListener(new SaveOnDialogCloseListener()).buildCommonDialogWindow(); - return commonDialogWindow; } /** @@ -424,21 +418,9 @@ private void editRollout() { if (rolloutForEdit == null) { return; } - rolloutForEdit.setName(rolloutName.getValue()); - rolloutForEdit.setDescription(description.getValue()); - final DistributionSetIdName distributionSetIdName = (DistributionSetIdName) distributionSet.getValue(); - rolloutForEdit - .setDistributionSet(distributionSetManagement.findDistributionSetById(distributionSetIdName.getId())); - rolloutForEdit.setActionType(getActionType()); - rolloutForEdit.setForcedTime(getForcedTimeStamp()); - final int amountGroup = Integer.parseInt(noOfGroups.getValue()); - final int errorThresoldPercent = getErrorThresoldPercentage(amountGroup); - for (final RolloutGroup rolloutGroup : rolloutForEdit.getRolloutGroups()) { - rolloutGroup.setErrorConditionExp(triggerThreshold.getValue()); - rolloutGroup.setSuccessConditionExp(String.valueOf(errorThresoldPercent)); - } - final Rollout updatedRollout = rolloutManagement.updateRollout(rolloutForEdit); + final Rollout updatedRollout = rolloutManagement.updateRollout(entityFactory.rollout() + .update(rolloutForEdit.getId()).name(rolloutName.getValue()).description(description.getValue())); uiNotification.displaySuccess(i18n.get("message.update.success", new Object[] { updatedRollout.getName() })); eventBus.publish(this, RolloutEvent.UPDATE_ROLLOUT); } @@ -471,28 +453,22 @@ private void createRollout() { } private Rollout saveRollout() { - Rollout rolloutToCreate = entityFactory.generateRollout(); + final int amountGroup = Integer.parseInt(noOfGroups.getValue()); - final String targetFilter = getTargetFilterQuery(); final int errorThresoldPercent = getErrorThresoldPercentage(amountGroup); - final RolloutGroupConditions conditions = new RolloutGroupConditionBuilder() + final RolloutGroupConditions conditions = new RolloutGroupConditionBuilder().withDefaults() .successAction(RolloutGroupSuccessAction.NEXTGROUP, null) .successCondition(RolloutGroupSuccessCondition.THRESHOLD, triggerThreshold.getValue()) .errorCondition(RolloutGroupErrorCondition.THRESHOLD, String.valueOf(errorThresoldPercent)) .errorAction(RolloutGroupErrorAction.PAUSE, null).build(); final DistributionSetIdName distributionSetIdName = (DistributionSetIdName) distributionSet.getValue(); - rolloutToCreate.setName(rolloutName.getValue()); - rolloutToCreate.setDescription(description.getValue()); - rolloutToCreate.setTargetFilterQuery(targetFilter); - rolloutToCreate - .setDistributionSet(distributionSetManagement.findDistributionSetById(distributionSetIdName.getId())); - rolloutToCreate.setActionType(getActionType()); - rolloutToCreate.setForcedTime(getForcedTimeStamp()); - rolloutToCreate = rolloutManagement.createRollout(rolloutToCreate, amountGroup, conditions); - return rolloutToCreate; + return rolloutManagement.createRollout(entityFactory.rollout().create().name(rolloutName.getValue()) + .description(description.getValue()).set(distributionSetIdName.getId()) + .targetFilterQuery(getTargetFilterQuery()).actionType(getActionType()).forcedTime(getForcedTimeStamp()), + amountGroup, conditions); } private String getTargetFilterQuery() { @@ -676,11 +652,7 @@ private void populateData(final Long rolloutId) { final List rolloutGroups = rolloutForEdit.getRolloutGroups(); setThresholdValues(rolloutGroups); setActionType(rolloutForEdit); - if (rolloutForEdit.getStatus() != RolloutStatus.READY) { - disableRequiredFieldsOnEdit(); - } - - noOfGroups.setEnabled(false); + disableRequiredFieldsOnEdit(); targetFilterQuery.setValue(rolloutForEdit.getTargetFilterQuery()); removeComponent(1, 2); targetFilterQueryCombo.removeValidator(nullValidator); @@ -695,6 +667,7 @@ private void populateData(final Long rolloutId) { } private void disableRequiredFieldsOnEdit() { + noOfGroups.setEnabled(false); distributionSet.setEnabled(false); errorThreshold.setEnabled(false); triggerThreshold.setEnabled(false); @@ -747,7 +720,7 @@ enum SAVESTARTOPTIONS { String value; - private SAVESTARTOPTIONS(final String val) { + SAVESTARTOPTIONS(final String val) { this.value = val; } @@ -764,7 +737,7 @@ enum ERRORTHRESOLDOPTIONS { String value; - private ERRORTHRESOLDOPTIONS(final String val) { + ERRORTHRESOLDOPTIONS(final String val) { this.value = val; } 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 721020eac9..0e870a6e56 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 @@ -14,8 +14,17 @@ import static org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil.HTML_UL_CLOSE_TAG; import static org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil.HTML_UL_OPEN_TAG; import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.ACTION; +import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_CREATED_DATE; +import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_CREATED_USER; +import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_DESC; import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_DIST_NAME_VERSION; +import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_ID; +import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_MODIFIED_BY; +import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_MODIFIED_DATE; +import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_NAME; +import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS; import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_STATUS; +import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_TOTAL_TARGETS; import static org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS; import java.util.ArrayList; @@ -46,7 +55,6 @@ import org.eclipse.hawkbit.ui.rollout.state.RolloutUIState; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; 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.UIComponentIdProvider; import org.eclipse.hawkbit.ui.utils.UINotification; @@ -150,15 +158,14 @@ private void handleEvent(final RolloutChangeEvent rolloutChangeEvent) { refreshGrid(); return; } - item.getItemProperty(SPUILabelDefinitions.VAR_STATUS).setValue(rollout.getStatus()); - item.getItemProperty(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS).setValue(totalTargetCountStatus); - final Long groupCount = (Long) item.getItemProperty(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS).getValue(); + item.getItemProperty(VAR_STATUS).setValue(rollout.getStatus()); + item.getItemProperty(VAR_TOTAL_TARGETS_COUNT_STATUS).setValue(totalTargetCountStatus); + final Long groupCount = (Long) item.getItemProperty(VAR_NUMBER_OF_GROUPS).getValue(); final int groupsCreated = rollout.getRolloutGroupsCreated(); if (groupsCreated != 0) { - item.getItemProperty(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS).setValue(Long.valueOf(groupsCreated)); + item.getItemProperty(VAR_NUMBER_OF_GROUPS).setValue(Long.valueOf(groupsCreated)); } else if (rollout.getRolloutGroups() != null && groupCount != rollout.getRolloutGroups().size()) { - item.getItemProperty(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS) - .setValue(Long.valueOf(rollout.getRolloutGroups().size())); + item.getItemProperty(VAR_NUMBER_OF_GROUPS).setValue(Long.valueOf(rollout.getRolloutGroups().size())); } item.getItemProperty(ROLLOUT_RENDERER_DATA) .setValue(new RolloutRendererData(rollout.getName(), rollout.getStatus().toString())); @@ -167,38 +174,29 @@ private void handleEvent(final RolloutChangeEvent rolloutChangeEvent) { @Override protected Container createContainer() { final BeanQueryFactory rolloutQf = new BeanQueryFactory<>(RolloutBeanQuery.class); - return new LazyQueryContainer( - new LazyQueryDefinition(true, SPUIDefinitions.PAGE_SIZE, SPUILabelDefinitions.VAR_ID), rolloutQf); + return new LazyQueryContainer(new LazyQueryDefinition(true, SPUIDefinitions.PAGE_SIZE, VAR_ID), rolloutQf); } @Override protected void addContainerProperties() { final LazyQueryContainer rolloutGridContainer = (LazyQueryContainer) getContainerDataSource(); - rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_NAME, String.class, "", false, false); + rolloutGridContainer.addContainerProperty(VAR_NAME, String.class, "", false, false); rolloutGridContainer.addContainerProperty(DS_TYPE, String.class, null, false, false); rolloutGridContainer.addContainerProperty(SW_MODULES, Set.class, null, false, false); rolloutGridContainer.addContainerProperty(ROLLOUT_RENDERER_DATA, RolloutRendererData.class, null, false, false); - rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_DESC, String.class, null, false, false); + rolloutGridContainer.addContainerProperty(VAR_DESC, String.class, null, false, false); rolloutGridContainer.addContainerProperty(IS_REQUIRED_MIGRATION_STEP, boolean.class, null, false, false); - rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_STATUS, RolloutStatus.class, null, false, - false); - rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_DIST_NAME_VERSION, String.class, null, false, - false); - rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_CREATED_DATE, String.class, null, false, - false); - - rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_MODIFIED_DATE, String.class, null, false, - false); - rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_CREATED_USER, String.class, null, false, - false); - rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_MODIFIED_BY, String.class, null, false, - false); - rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS, Long.class, 0, false, - false); - rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_TOTAL_TARGETS, String.class, "0", false, - false); - rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS, - TotalTargetCountStatus.class, null, false, false); + rolloutGridContainer.addContainerProperty(VAR_STATUS, RolloutStatus.class, null, false, false); + rolloutGridContainer.addContainerProperty(VAR_DIST_NAME_VERSION, String.class, null, false, false); + rolloutGridContainer.addContainerProperty(VAR_CREATED_DATE, String.class, null, false, false); + + rolloutGridContainer.addContainerProperty(VAR_MODIFIED_DATE, String.class, null, false, false); + rolloutGridContainer.addContainerProperty(VAR_CREATED_USER, String.class, null, false, false); + rolloutGridContainer.addContainerProperty(VAR_MODIFIED_BY, String.class, null, false, false); + rolloutGridContainer.addContainerProperty(VAR_NUMBER_OF_GROUPS, Long.class, 0, false, false); + rolloutGridContainer.addContainerProperty(VAR_TOTAL_TARGETS, String.class, "0", false, false); + rolloutGridContainer.addContainerProperty(VAR_TOTAL_TARGETS_COUNT_STATUS, TotalTargetCountStatus.class, null, + false, false); rolloutGridContainer.addContainerProperty(RUN_OPTION, String.class, FontAwesome.PLAY.getHtml(), false, false); @@ -217,17 +215,17 @@ protected void setColumnExpandRatio() { getColumn(ROLLOUT_RENDERER_DATA).setMinimumWidth(40); getColumn(ROLLOUT_RENDERER_DATA).setMaximumWidth(150); - getColumn(SPUILabelDefinitions.VAR_DIST_NAME_VERSION).setMinimumWidth(40); - getColumn(SPUILabelDefinitions.VAR_DIST_NAME_VERSION).setMaximumWidth(150); + getColumn(VAR_DIST_NAME_VERSION).setMinimumWidth(40); + getColumn(VAR_DIST_NAME_VERSION).setMaximumWidth(150); - getColumn(SPUILabelDefinitions.VAR_STATUS).setMinimumWidth(75); - getColumn(SPUILabelDefinitions.VAR_STATUS).setMaximumWidth(75); + getColumn(VAR_STATUS).setMinimumWidth(75); + getColumn(VAR_STATUS).setMaximumWidth(75); - getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS).setMinimumWidth(40); - getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS).setMaximumWidth(100); + getColumn(VAR_TOTAL_TARGETS).setMinimumWidth(40); + getColumn(VAR_TOTAL_TARGETS).setMaximumWidth(100); - getColumn(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS).setMinimumWidth(40); - getColumn(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS).setMaximumWidth(100); + getColumn(VAR_NUMBER_OF_GROUPS).setMinimumWidth(40); + getColumn(VAR_NUMBER_OF_GROUPS).setMaximumWidth(100); getColumn(RUN_OPTION).setMinimumWidth(25); getColumn(RUN_OPTION).setMaximumWidth(25); @@ -240,7 +238,7 @@ protected void setColumnExpandRatio() { getColumn(UPDATE_OPTION).setMaximumWidth(25); } - getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS).setMinimumWidth(280); + getColumn(VAR_TOTAL_TARGETS_COUNT_STATUS).setMinimumWidth(280); setFrozenColumnCount(getColumns().size()); } @@ -251,17 +249,16 @@ protected void setColumnHeaderNames() { getColumn(DS_TYPE).setHeaderCaption(i18n.get("header.type")); getColumn(SW_MODULES).setHeaderCaption(i18n.get("header.swmodules")); getColumn(IS_REQUIRED_MIGRATION_STEP).setHeaderCaption(i18n.get("header.migrations.step")); - getColumn(SPUILabelDefinitions.VAR_DIST_NAME_VERSION).setHeaderCaption(i18n.get("header.distributionset")); - getColumn(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS).setHeaderCaption(i18n.get("header.numberofgroups")); - getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS).setHeaderCaption(i18n.get("header.total.targets")); - getColumn(SPUILabelDefinitions.VAR_CREATED_DATE).setHeaderCaption(i18n.get("header.createdDate")); - getColumn(SPUILabelDefinitions.VAR_CREATED_USER).setHeaderCaption(i18n.get("header.createdBy")); - getColumn(SPUILabelDefinitions.VAR_MODIFIED_DATE).setHeaderCaption(i18n.get("header.modifiedDate")); - getColumn(SPUILabelDefinitions.VAR_MODIFIED_BY).setHeaderCaption(i18n.get("header.modifiedBy")); - getColumn(SPUILabelDefinitions.VAR_DESC).setHeaderCaption(i18n.get("header.description")); - getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS) - .setHeaderCaption(i18n.get("header.detail.status")); - getColumn(SPUILabelDefinitions.VAR_STATUS).setHeaderCaption(i18n.get("header.status")); + getColumn(VAR_DIST_NAME_VERSION).setHeaderCaption(i18n.get("header.distributionset")); + getColumn(VAR_NUMBER_OF_GROUPS).setHeaderCaption(i18n.get("header.numberofgroups")); + getColumn(VAR_TOTAL_TARGETS).setHeaderCaption(i18n.get("header.total.targets")); + getColumn(VAR_CREATED_DATE).setHeaderCaption(i18n.get("header.createdDate")); + getColumn(VAR_CREATED_USER).setHeaderCaption(i18n.get("header.createdBy")); + getColumn(VAR_MODIFIED_DATE).setHeaderCaption(i18n.get("header.modifiedDate")); + getColumn(VAR_MODIFIED_BY).setHeaderCaption(i18n.get("header.modifiedBy")); + getColumn(VAR_DESC).setHeaderCaption(i18n.get("header.description")); + getColumn(VAR_TOTAL_TARGETS_COUNT_STATUS).setHeaderCaption(i18n.get("header.detail.status")); + getColumn(VAR_STATUS).setHeaderCaption(i18n.get("header.status")); getColumn(RUN_OPTION).setHeaderCaption(i18n.get("header.action.run")); getColumn(PAUSE_OPTION).setHeaderCaption(i18n.get("header.action.pause")); @@ -283,14 +280,14 @@ protected String getGridId() { protected void setColumnProperties() { final List columnList = new ArrayList<>(); columnList.add(ROLLOUT_RENDERER_DATA); - columnList.add(SPUILabelDefinitions.VAR_DIST_NAME_VERSION); + columnList.add(VAR_DIST_NAME_VERSION); columnList.add(DS_TYPE); columnList.add(SW_MODULES); columnList.add(IS_REQUIRED_MIGRATION_STEP); - columnList.add(SPUILabelDefinitions.VAR_STATUS); - columnList.add(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS); - columnList.add(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS); - columnList.add(SPUILabelDefinitions.VAR_TOTAL_TARGETS); + columnList.add(VAR_STATUS); + columnList.add(VAR_TOTAL_TARGETS_COUNT_STATUS); + columnList.add(VAR_NUMBER_OF_GROUPS); + columnList.add(VAR_TOTAL_TARGETS); columnList.add(RUN_OPTION); columnList.add(PAUSE_OPTION); @@ -299,11 +296,11 @@ protected void setColumnProperties() { columnList.add(UPDATE_OPTION); } - columnList.add(SPUILabelDefinitions.VAR_CREATED_DATE); - columnList.add(SPUILabelDefinitions.VAR_CREATED_USER); - columnList.add(SPUILabelDefinitions.VAR_MODIFIED_DATE); - columnList.add(SPUILabelDefinitions.VAR_MODIFIED_BY); - columnList.add(SPUILabelDefinitions.VAR_DESC); + columnList.add(VAR_CREATED_DATE); + columnList.add(VAR_CREATED_USER); + columnList.add(VAR_MODIFIED_DATE); + columnList.add(VAR_MODIFIED_BY); + columnList.add(VAR_DESC); setColumnOrder(columnList.toArray()); alignColumns(); } @@ -311,12 +308,12 @@ protected void setColumnProperties() { @Override protected void setHiddenColumns() { final List columnsToBeHidden = new ArrayList<>(); - columnsToBeHidden.add(SPUILabelDefinitions.VAR_NAME); - columnsToBeHidden.add(SPUILabelDefinitions.VAR_CREATED_DATE); - columnsToBeHidden.add(SPUILabelDefinitions.VAR_CREATED_USER); - columnsToBeHidden.add(SPUILabelDefinitions.VAR_MODIFIED_DATE); - columnsToBeHidden.add(SPUILabelDefinitions.VAR_MODIFIED_BY); - columnsToBeHidden.add(SPUILabelDefinitions.VAR_DESC); + columnsToBeHidden.add(VAR_NAME); + columnsToBeHidden.add(VAR_CREATED_DATE); + columnsToBeHidden.add(VAR_CREATED_USER); + columnsToBeHidden.add(VAR_MODIFIED_DATE); + columnsToBeHidden.add(VAR_MODIFIED_BY); + columnsToBeHidden.add(VAR_DESC); columnsToBeHidden.add(IS_REQUIRED_MIGRATION_STEP); columnsToBeHidden.add(DS_TYPE); columnsToBeHidden.add(SW_MODULES); @@ -332,13 +329,12 @@ protected CellDescriptionGenerator getDescriptionGenerator() { @Override protected void addColumnRenderes() { - getColumn(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS).setRenderer(new HtmlRenderer(), - new TotalTargetGroupsConverter()); - getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS).setRenderer(new HtmlRenderer(), + getColumn(VAR_NUMBER_OF_GROUPS).setRenderer(new HtmlRenderer(), new TotalTargetGroupsConverter()); + getColumn(VAR_TOTAL_TARGETS_COUNT_STATUS).setRenderer(new HtmlRenderer(), new TotalTargetCountStatusConverter()); createRolloutStatusToFontMap(); - getColumn(SPUILabelDefinitions.VAR_STATUS).setRenderer(new HtmlLabelRenderer(), new RolloutStatusConverter()); + getColumn(VAR_STATUS).setRenderer(new HtmlLabelRenderer(), new RolloutStatusConverter()); final RolloutRenderer customObjectRenderer = new RolloutRenderer(RolloutRendererData.class); customObjectRenderer.addClickListener(this::onClickOfRolloutName); @@ -382,10 +378,10 @@ private void alignColumns() { private void onClickOfRolloutName(final RendererClickEvent event) { rolloutUIState.setRolloutId((long) event.getItemId()); final String rolloutName = (String) getContainerDataSource().getItem(event.getItemId()) - .getItemProperty(SPUILabelDefinitions.VAR_NAME).getValue(); + .getItemProperty(VAR_NAME).getValue(); rolloutUIState.setRolloutName(rolloutName); final String ds = (String) getContainerDataSource().getItem(event.getItemId()) - .getItemProperty(SPUILabelDefinitions.VAR_DIST_NAME_VERSION).getValue(); + .getItemProperty(VAR_DIST_NAME_VERSION).getValue(); rolloutUIState.setRolloutDistributionSet(ds); eventBus.publish(this, RolloutEvent.SHOW_ROLLOUT_GROUPS); } @@ -393,14 +389,13 @@ private void onClickOfRolloutName(final RendererClickEvent event) { private void pauseRollout(final Long rolloutId) { final Item row = getContainerDataSource().getItem(rolloutId); - final RolloutStatus rolloutStatus = (RolloutStatus) row.getItemProperty(SPUILabelDefinitions.VAR_STATUS) - .getValue(); + final RolloutStatus rolloutStatus = (RolloutStatus) row.getItemProperty(VAR_STATUS).getValue(); if (!RolloutStatus.RUNNING.equals(rolloutStatus)) { return; } - final String rolloutName = (String) row.getItemProperty(SPUILabelDefinitions.VAR_NAME).getValue(); + final String rolloutName = (String) row.getItemProperty(VAR_NAME).getValue(); rolloutManagement.pauseRollout(rolloutManagement.findRolloutById(rolloutId)); uiNotification.displaySuccess(i18n.get("message.rollout.paused", rolloutName)); @@ -409,9 +404,8 @@ private void pauseRollout(final Long rolloutId) { private void startOrResumeRollout(final Long rolloutId) { final Item row = getContainerDataSource().getItem(rolloutId); - final RolloutStatus rolloutStatus = (RolloutStatus) row.getItemProperty(SPUILabelDefinitions.VAR_STATUS) - .getValue(); - final String rolloutName = (String) row.getItemProperty(SPUILabelDefinitions.VAR_NAME).getValue(); + final RolloutStatus rolloutStatus = (RolloutStatus) row.getItemProperty(VAR_STATUS).getValue(); + final String rolloutName = (String) row.getItemProperty(VAR_NAME).getValue(); if (RolloutStatus.READY.equals(rolloutStatus)) { rolloutManagement.startRollout(rolloutManagement.findRolloutByName(rolloutName)); @@ -470,7 +464,7 @@ private static String getDSDetails(final Item rolloutItem) { stringBuilder.append(HTML_UL_OPEN_TAG); stringBuilder.append(HTML_LI_OPEN_TAG); stringBuilder.append(" DistributionSet Description : ") - .append((String) rolloutItem.getItemProperty(SPUILabelDefinitions.VAR_DESC).getValue()); + .append((String) rolloutItem.getItemProperty(VAR_DESC).getValue()); stringBuilder.append(HTML_LI_CLOSE_TAG); stringBuilder.append(HTML_LI_OPEN_TAG); stringBuilder.append(" DistributionSet Type : ") @@ -521,7 +515,7 @@ public RollouStatusCellStyleGenerator(final Container.Indexed containerDataSourc @Override public String getStyle(final CellReference cellReference) { - if (SPUILabelDefinitions.VAR_STATUS.equals(cellReference.getPropertyId())) { + if (VAR_STATUS.equals(cellReference.getPropertyId())) { return "centeralign"; } return convertRolloutStatusToString(cellReference); @@ -557,7 +551,7 @@ private String getStatus(final CellReference cellReference, final RolloutStatus. private RolloutStatus getRolloutStatus(final Object itemId) { final Item row = containerDataSource.getItem(itemId); - return (RolloutStatus) row.getItemProperty(SPUILabelDefinitions.VAR_STATUS).getValue(); + return (RolloutStatus) row.getItemProperty(VAR_STATUS).getValue(); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DefaultDistributionSetTypeLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DefaultDistributionSetTypeLayout.java index 2751d1fe79..8cbdaef65f 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DefaultDistributionSetTypeLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/DefaultDistributionSetTypeLayout.java @@ -126,10 +126,7 @@ private DistributionSetType getCurrentDistributionSetType() { @Override public void save() { if (!currentDefaultDisSetType.equals(selectedDefaultDisSetType) && selectedDefaultDisSetType != null) { - final DistributionSetType defaultDistributionSetType = distributionSetManagement - .findDistributionSetTypeById(selectedDefaultDisSetType); - tenantMetaData.setDefaultDsType(defaultDistributionSetType); - tenantMetaData = systemManagement.updateTenantMetadata(tenantMetaData); + tenantMetaData = systemManagement.updateTenantMetadata(selectedDefaultDisSetType); currentDefaultDisSetType = selectedDefaultDisSetType; } changeIcon.setVisible(false); 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 dfcf67dce0..7465c8f510 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 @@ -366,14 +366,9 @@ public static String getFormattedNameVersion(final String name, final String ver 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 = entityFactory.generateSoftwareModule(); - newSWModule.setType(bstype); - newSWModule.setName(bsname); - newSWModule.setVersion(bsversion); - newSWModule.setVendor(bsvendor); - newSWModule.setDescription(description); - newSWModule = swMgmtService.createSoftwareModule(newSWModule); - return newSWModule; + + return swMgmtService.createSoftwareModule(entityFactory.softwareModule().create().type(bstype).name(bsname) + .version(bsversion).description(description).vendor(bsvendor)); } /** diff --git a/pom.xml b/pom.xml index 1a02407e64..ce76bf30d7 100644 --- a/pom.xml +++ b/pom.xml @@ -109,7 +109,7 @@ 4.1.2.RELEASE 4.3.3.RELEASE 4.3.2.RELEASE - Hopper-SR4 + Hopper-SR5 3.2.2 diff --git a/sonarCircleCi.sh b/sonarCircleCi.sh index 9a00961c8f..d605ef2d4a 100644 --- a/sonarCircleCi.sh +++ b/sonarCircleCi.sh @@ -1,3 +1,4 @@ +#!/bin/sh # # Copyright (c) 2015 Bosch Software Innovations GmbH and others. #