Make entities immutable and create proper update methods that state by signature what can be updated. (#342)

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>
This commit is contained in:
Kai Zimmermann
2016-11-17 20:07:23 +01:00
committed by GitHub
parent b6834e9ee2
commit ca63106d5c
314 changed files with 7699 additions and 6914 deletions

View File

@@ -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 .. cd ..
mvn dependency:list -DexcludeGroupIds=org.eclipse.hawkbit -Dsort=true -DoutputFile=dependencies.txt 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 find . -name dependencies.txt|while read i; do cat $i;done|grep '.*:.*:compile'|sort|uniq > 3rd-dependencies/compile.txt

View File

@@ -335,7 +335,7 @@ public class SecurityManagedConfiguration {
private VaadinSecurityContext vaadinSecurityContext; private VaadinSecurityContext vaadinSecurityContext;
@Autowired @Autowired
private org.springframework.boot.autoconfigure.security.SecurityProperties springSecurityProperties; private SecurityProperties springSecurityProperties;
/** /**
* post construct for setting the authentication success handler for the * post construct for setting the authentication success handler for the

View File

@@ -144,20 +144,16 @@ public class DdiArtifactStoreController implements DdiDlArtifactStoreControllerR
.getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(), artifact.getSoftwareModule()); .getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(), artifact.getSoftwareModule());
final String range = request.getHeader("Range"); final String range = request.getHeader("Range");
final ActionStatus actionStatus = entityFactory.generateActionStatus(); String message;
actionStatus.setAction(action);
actionStatus.setOccurredAt(System.currentTimeMillis());
actionStatus.setStatus(Status.DOWNLOAD);
if (range != null) { if (range != null) {
actionStatus.addMessage(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads range " + range message = RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads range " + range + " of: "
+ " of: " + request.getRequestURI()); + request.getRequestURI();
} else { } else {
actionStatus.addMessage( message = RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads: " + request.getRequestURI();
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));
} }
} }

View File

@@ -10,6 +10,7 @@ package org.eclipse.hawkbit.ddi.rest.resource;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@@ -34,6 +35,7 @@ import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.RepositoryConstants; import org.eclipse.hawkbit.repository.RepositoryConstants;
import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.SystemManagement; 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.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.Action.Status;
@@ -179,20 +181,16 @@ public class DdiRootController implements DdiRootControllerRestApi {
.getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(), module); .getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(), module);
final String range = request.getHeader("Range"); final String range = request.getHeader("Range");
final ActionStatus statusMessage = entityFactory.generateActionStatus(); String message;
statusMessage.setAction(action);
statusMessage.setOccurredAt(System.currentTimeMillis());
statusMessage.setStatus(Status.DOWNLOAD);
if (range != null) { if (range != null) {
statusMessage.addMessage(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads range " + range message = RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads range " + range + " of: "
+ " of: " + request.getRequestURI()); + request.getRequestURI();
} else { } else {
statusMessage.addMessage( message = RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads " + request.getRequestURI();
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) { private static boolean checkModule(final String fileName, final SoftwareModule module) {
@@ -293,73 +291,69 @@ public class DdiRootController implements DdiRootControllerRestApi {
return new ResponseEntity<>(HttpStatus.GONE); return new ResponseEntity<>(HttpStatus.GONE);
} }
controllerManagement controllerManagement.addUpdateActionStatus(generateUpdateStatus(feedback, controllerId, feedback.getId()));
.addUpdateActionStatus(generateUpdateStatus(feedback, controllerId, feedback.getId(), action));
return new ResponseEntity<>(HttpStatus.OK); return new ResponseEntity<>(HttpStatus.OK);
} }
private ActionStatus generateUpdateStatus(final DdiActionFeedback feedback, final String controllerId, private ActionStatusCreate generateUpdateStatus(final DdiActionFeedback feedback, final String controllerId,
final Long actionid, final Action action) { final Long actionid) {
final ActionStatus actionStatus = entityFactory.generateActionStatus();
actionStatus.setAction(action);
actionStatus.setOccurredAt(System.currentTimeMillis());
final List<String> messages = new ArrayList<>();
Status status;
switch (feedback.getStatus().getExecution()) { switch (feedback.getStatus().getExecution()) {
case CANCELED: case CANCELED:
LOG.debug("Controller confirmed cancel (actionid: {}, controllerId: {}) as we got {} report.", actionid, LOG.debug("Controller confirmed cancel (actionid: {}, controllerId: {}) as we got {} report.", actionid,
controllerId, feedback.getStatus().getExecution()); controllerId, feedback.getStatus().getExecution());
actionStatus.setStatus(Status.CANCELED); status = Status.CANCELED;
actionStatus.addMessage(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target confirmed cancelation."); messages.add(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target confirmed cancelation.");
break; break;
case REJECTED: case REJECTED:
LOG.info("Controller reported internal error (actionid: {}, controllerId: {}) as we got {} report.", LOG.info("Controller reported internal error (actionid: {}, controllerId: {}) as we got {} report.",
actionid, controllerId, feedback.getStatus().getExecution()); actionid, controllerId, feedback.getStatus().getExecution());
actionStatus.setStatus(Status.WARNING); status = Status.WARNING;
actionStatus.addMessage(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target REJECTED update."); messages.add(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target REJECTED update.");
break; break;
case CLOSED: case CLOSED:
handleClosedUpdateStatus(feedback, controllerId, actionid, actionStatus); status = handleClosedCase(feedback, controllerId, actionid, messages);
break; break;
default: default:
handleDefaultUpdateStatus(feedback, controllerId, actionid, actionStatus); status = handleDefaultCase(feedback, controllerId, actionid, messages);
break; break;
} }
action.setStatus(actionStatus.getStatus()); if (feedback.getStatus().getDetails() != null) {
messages.addAll(feedback.getStatus().getDetails());
if (feedback.getStatus().getDetails() != null && !feedback.getStatus().getDetails().isEmpty()) {
final List<String> details = feedback.getStatus().getDetails();
for (final String detailMsg : details) {
actionStatus.addMessage(detailMsg);
}
} }
return actionStatus; return entityFactory.actionStatus().create(actionid).status(status).messages(messages);
} }
private static void handleDefaultUpdateStatus(final DdiActionFeedback feedback, final String controllerId, private Status handleDefaultCase(final DdiActionFeedback feedback, final String controllerId, final Long actionid,
final Long actionid, final ActionStatus actionStatus) { final List<String> messages) {
Status status;
LOG.debug("Controller reported intermediate status (actionid: {}, controllerId: {}) as we got {} report.", LOG.debug("Controller reported intermediate status (actionid: {}, controllerId: {}) as we got {} report.",
actionid, controllerId, feedback.getStatus().getExecution()); actionid, controllerId, feedback.getStatus().getExecution());
actionStatus.setStatus(Status.RUNNING); status = Status.RUNNING;
actionStatus.addMessage( messages.add(
RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target reported " + feedback.getStatus().getExecution()); RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target reported " + feedback.getStatus().getExecution());
return status;
} }
private static void handleClosedUpdateStatus(final DdiActionFeedback feedback, final String controllerId, private Status handleClosedCase(final DdiActionFeedback feedback, final String controllerId, final Long actionid,
final Long actionid, final ActionStatus actionStatus) { final List<String> messages) {
Status status;
LOG.debug("Controller reported closed (actionid: {}, controllerId: {}) as we got {} report.", actionid, LOG.debug("Controller reported closed (actionid: {}, controllerId: {}) as we got {} report.", actionid,
controllerId, feedback.getStatus().getExecution()); controllerId, feedback.getStatus().getExecution());
if (feedback.getStatus().getResult().getFinished() == FinalResult.FAILURE) { if (feedback.getStatus().getResult().getFinished() == FinalResult.FAILURE) {
actionStatus.setStatus(Status.ERROR); status = Status.ERROR;
actionStatus.addMessage(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target reported CLOSED with ERROR!"); messages.add(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target reported CLOSED with ERROR!");
} else { } else {
actionStatus.setStatus(Status.FINISHED); status = Status.FINISHED;
actionStatus.addMessage(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target reported CLOSED with OK!"); messages.add(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target reported CLOSED with OK!");
} }
return status;
} }
@Override @Override
@@ -426,57 +420,64 @@ public class DdiRootController implements DdiRootControllerRestApi {
return new ResponseEntity<>(HttpStatus.NOT_FOUND); return new ResponseEntity<>(HttpStatus.NOT_FOUND);
} }
controllerManagement.addCancelActionStatus( controllerManagement
generateActionCancelStatus(feedback, target, feedback.getId(), action, entityFactory)); .addCancelActionStatus(generateActionCancelStatus(feedback, target, feedback.getId(), entityFactory));
return new ResponseEntity<>(HttpStatus.OK); return new ResponseEntity<>(HttpStatus.OK);
} }
private static ActionStatus generateActionCancelStatus(final DdiActionFeedback feedback, final Target target, private static ActionStatusCreate generateActionCancelStatus(final DdiActionFeedback feedback, final Target target,
final Long actionid, final Action action, final EntityFactory entityFactory) { final Long actionid, final EntityFactory entityFactory) {
final ActionStatus actionStatus = entityFactory.generateActionStatus();
actionStatus.setAction(action);
actionStatus.setOccurredAt(System.currentTimeMillis());
final List<String> messages = new ArrayList<>();
Status status;
switch (feedback.getStatus().getExecution()) { switch (feedback.getStatus().getExecution()) {
case CANCELED: case CANCELED:
LOG.error( status = handleCaseCancelCanceled(feedback, target, actionid, messages);
"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);
break; break;
case REJECTED: case REJECTED:
LOG.info("Controller rejected the cancelation request (too late) (actionid: {}, controllerId: {}).", LOG.info("Target rejected the cancelation request (actionid: {}, controllerId: {}).", actionid,
actionid, target.getControllerId()); target.getControllerId());
actionStatus.setStatus(Status.WARNING); status = Status.WARNING;
messages.add(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target rejected the cancelation request.");
break; break;
case CLOSED: case CLOSED:
handleClosedCancelStatus(feedback, actionStatus); status = handleCancelClosedCase(feedback, messages);
break; break;
default: default:
actionStatus.setStatus(Status.RUNNING); status = Status.RUNNING;
break; break;
} }
action.setStatus(actionStatus.getStatus()); if (feedback.getStatus().getDetails() != null) {
messages.addAll(feedback.getStatus().getDetails());
if (feedback.getStatus().getDetails() != null && !feedback.getStatus().getDetails().isEmpty()) {
final List<String> details = feedback.getStatus().getDetails();
for (final String detailMsg : details) {
actionStatus.addMessage(detailMsg);
}
} }
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<String> messages) {
Status status;
if (feedback.getStatus().getResult().getFinished() == FinalResult.FAILURE) { 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 { } 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<String> 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) { private Action findActionWithExceptionIfNotFound(final Long actionId) {

View File

@@ -22,7 +22,6 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@@ -37,6 +36,7 @@ import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.test.util.TestdataFactory;
import org.eclipse.hawkbit.repository.test.util.WithUser; import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest; import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest;
import org.junit.Before; import org.junit.Before;
@@ -50,6 +50,7 @@ import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.MvcResult;
import com.google.common.base.Charsets; import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.google.common.net.HttpHeaders; import com.google.common.net.HttpHeaders;
import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Description;
@@ -80,14 +81,12 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTest {
@Description("Tests non allowed requests on the artifact ressource, e.g. invalid URI, wrong if-match, wrong command.") @Description("Tests non allowed requests on the artifact ressource, e.g. invalid URI, wrong if-match, wrong command.")
public void invalidRequestsOnArtifactResource() throws Exception { public void invalidRequestsOnArtifactResource() throws Exception {
// create target // create target
Target target = entityFactory.generateTarget("4712"); final Target target = testdataFactory.createTarget();
target = targetManagement.createTarget(target); final List<Target> targets = Lists.newArrayList(target);
final List<Target> targets = new ArrayList<>();
targets.add(target);
// create ds // create ds
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
deploymentManagement.assignDistributionSet(ds, targets); assignDistributionSet(ds, targets);
// create artifact // create artifact
final byte random[] = RandomUtils.nextBytes(5 * 1024); final byte random[] = RandomUtils.nextBytes(5 * 1024);
@@ -96,9 +95,9 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTest {
// no artifact available // no artifact available
mvc.perform(get("/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/123455", 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", 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 // SM does not exist
mvc.perform(get("/controller/v1/{targetid}/softwaremodules/1234567890/artifacts/{filename}", mvc.perform(get("/controller/v1/{targetid}/softwaremodules/1234567890/artifacts/{filename}",
@@ -108,70 +107,69 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTest {
// test now consistent data to test allowed methods // test now consistent data to test allowed methods
mvc.perform(get("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}", mvc.perform(get("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}",
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename())
artifact.getFilename()).header(HttpHeaders.IF_MATCH, artifact.getSha1Hash())) .header(HttpHeaders.IF_MATCH, artifact.getSha1Hash()))
.andExpect(status().isOk()); .andExpect(status().isOk());
mvc.perform(get("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}.MD5SUM", mvc.perform(get("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}.MD5SUM",
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename()))
artifact.getFilename())).andExpect(status().isOk()); .andExpect(status().isOk());
// test failed If-match // test failed If-match
mvc.perform(get("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}", mvc.perform(get("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}",
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename())
artifact.getFilename()).header("If-Match", "fsjkhgjfdhg")).andExpect(status().isPreconditionFailed()); .header("If-Match", "fsjkhgjfdhg"))
.andExpect(status().isPreconditionFailed());
// test invalid range // test invalid range
mvc.perform(get("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}", mvc.perform(get("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}",
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename())
artifact.getFilename()).header("Range", "bytes=1-10,hdsfjksdh")) .header("Range", "bytes=1-10,hdsfjksdh"))
.andExpect(header().string("Content-Range", "bytes */" + 5 * 1024)) .andExpect(header().string("Content-Range", "bytes */" + 5 * 1024))
.andExpect(status().isRequestedRangeNotSatisfiable()); .andExpect(status().isRequestedRangeNotSatisfiable());
mvc.perform(get("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}", mvc.perform(get("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}",
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename())
artifact.getFilename()).header("Range", "bytes=100-10")) .header("Range", "bytes=100-10"))
.andExpect(header().string("Content-Range", "bytes */" + 5 * 1024)) .andExpect(header().string("Content-Range", "bytes */" + 5 * 1024))
.andExpect(status().isRequestedRangeNotSatisfiable()); .andExpect(status().isRequestedRangeNotSatisfiable());
// not allowed methods // not allowed methods
mvc.perform(put("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}", mvc.perform(put("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}",
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename()))
artifact.getFilename())).andExpect(status().isMethodNotAllowed()); .andExpect(status().isMethodNotAllowed());
mvc.perform(delete("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}", mvc.perform(delete("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}",
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename()))
artifact.getFilename())).andExpect(status().isMethodNotAllowed()); .andExpect(status().isMethodNotAllowed());
mvc.perform(post("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}", mvc.perform(post("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}",
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename()))
artifact.getFilename())).andExpect(status().isMethodNotAllowed()); .andExpect(status().isMethodNotAllowed());
mvc.perform(put("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}.MD5SUM", mvc.perform(put("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}.MD5SUM",
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename()))
artifact.getFilename())).andExpect(status().isMethodNotAllowed()); .andExpect(status().isMethodNotAllowed());
mvc.perform(delete("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}.MD5SUM", mvc.perform(delete("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}.MD5SUM",
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename()))
artifact.getFilename())).andExpect(status().isMethodNotAllowed()); .andExpect(status().isMethodNotAllowed());
mvc.perform(post("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}.MD5SUM", mvc.perform(post("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}.MD5SUM",
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(), tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename()))
artifact.getFilename())).andExpect(status().isMethodNotAllowed()); .andExpect(status().isMethodNotAllowed());
} }
@Test @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.") @Description("Tests non allowed requests on the artifact ressource, e.g. invalid URI, wrong if-match, wrong command.")
public void invalidRequestsOnArtifactResourceByName() throws Exception { public void invalidRequestsOnArtifactResourceByName() throws Exception {
// create target // create target
Target target = entityFactory.generateTarget("4712"); final Target target = testdataFactory.createTarget();
target = targetManagement.createTarget(target); final List<Target> targets = Lists.newArrayList(target);
final List<Target> targets = new ArrayList<>();
targets.add(target);
// create ds // create ds
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
deploymentManagement.assignDistributionSet(ds, targets); assignDistributionSet(ds, targets);
// create artifact // create artifact
final byte random[] = RandomUtils.nextBytes(5 * 1024); final byte random[] = RandomUtils.nextBytes(5 * 1024);
@@ -185,8 +183,8 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTest {
.andExpect(status().isNotFound()); .andExpect(status().isNotFound());
// test now consistent data to test allowed methods // test now consistent data to test allowed methods
final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), getOsModule(ds),
ds.findFirstModuleByType(osType).getId(), "file1", false); "file1", false);
mvc.perform( mvc.perform(
get("/{tenant}/controller/artifacts/v1/filename/{filename}", tenantAware.getCurrentTenant(), "file1") get("/{tenant}/controller/artifacts/v1/filename/{filename}", tenantAware.getCurrentTenant(), "file1")
@@ -248,10 +246,8 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTest {
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
// create target // create target
Target target = entityFactory.generateTarget("4712"); final Target target = testdataFactory.createTarget();
target = targetManagement.createTarget(target); final List<Target> targets = Lists.newArrayList(target);
final List<Target> targets = new ArrayList<Target>();
targets.add(target);
// create ds // create ds
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
@@ -263,16 +259,15 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTest {
// download fails as artifact is not yet assigned // download fails as artifact is not yet assigned
mvc.perform(get("/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/{filename}", mvc.perform(get("/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/{filename}",
target.getControllerId(), ds.findFirstModuleByType(osType).getId(), artifact.getFilename())) target.getControllerId(), getOsModule(ds), artifact.getFilename())).andExpect(status().isNotFound());
.andExpect(status().isNotFound());
// now assign and download successful // now assign and download successful
deploymentManagement.assignDistributionSet(ds, targets); assignDistributionSet(ds, targets);
final MvcResult result = mvc final MvcResult result = mvc
.perform( .perform(
get("/{tenant}/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/{filename}", get("/{tenant}/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/{filename}",
tenantAware.getCurrentTenant(), target.getControllerId(), tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds),
ds.findFirstModuleByType(osType).getId(), artifact.getFilename())) artifact.getFilename()))
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM)) .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM))
.andExpect(header().string("Accept-Ranges", "bytes")) .andExpect(header().string("Accept-Ranges", "bytes"))
.andExpect(header().string("Last-Modified", dateFormat.format(new Date(artifact.getCreatedAt())))) .andExpect(header().string("Last-Modified", dateFormat.format(new Date(artifact.getCreatedAt()))))
@@ -291,23 +286,22 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTest {
@Description("Tests valid MD5SUm file downloads through the artifact resource by identifying the artifact by ID.") @Description("Tests valid MD5SUm file downloads through the artifact resource by identifying the artifact by ID.")
public void downloadMd5sumThroughControllerApi() throws Exception { public void downloadMd5sumThroughControllerApi() throws Exception {
// create target // create target
Target target = entityFactory.generateTarget("4712"); final Target target = testdataFactory.createTarget();
target = targetManagement.createTarget(target);
// create ds // create ds
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
// create artifact // create artifact
final byte random[] = RandomUtils.nextBytes(5 * 1024); final byte random[] = RandomUtils.nextBytes(5 * 1024);
final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), getOsModule(ds),
ds.findFirstModuleByType(osType).getId(), "file1", false); "file1", false);
// download // download
final MvcResult result = mvc final MvcResult result = mvc
.perform( .perform(
get("/{tenant}/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/{filename}.MD5SUM", get("/{tenant}/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/{filename}.MD5SUM",
tenantAware.getCurrentTenant(), target.getControllerId(), tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds),
ds.findFirstModuleByType(osType).getId(), artifact.getFilename())) artifact.getFilename()))
.andExpect(status().isOk()).andExpect(header().string("Content-Disposition", .andExpect(status().isOk()).andExpect(header().string("Content-Disposition",
"attachment;filename=" + artifact.getFilename() + ".MD5SUM")) "attachment;filename=" + artifact.getFilename() + ".MD5SUM"))
.andReturn(); .andReturn();
@@ -327,21 +321,18 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTest {
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
// create target // create target
Target target = entityFactory.generateTarget("4712"); final Target target = testdataFactory.createTarget();
target = targetManagement.createTarget(target); final List<Target> targets = Lists.newArrayList(target);
final List<Target> targets = new ArrayList<>();
targets.add(target);
// create ds // create ds
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
// create artifact // create artifact
final byte random[] = RandomUtils.nextBytes(ARTIFACT_SIZE); final byte random[] = RandomUtils.nextBytes(ARTIFACT_SIZE);
artifactManagement.createArtifact(new ByteArrayInputStream(random), ds.findFirstModuleByType(osType).getId(), artifactManagement.createArtifact(new ByteArrayInputStream(random), getOsModule(ds), "file1.tar.bz2", false);
"file1.tar.bz2", false);
// download fails as artifact is not yet assigned to target // 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")) mvc.perform(get("/controller/artifacts/v1/filename/{filename}", "file1.tar.bz2"))
.andExpect(status().isNotFound()); .andExpect(status().isNotFound());
@@ -350,7 +341,7 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTest {
} }
@Test @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.") @Description("Ensures that an authenticated and named controller is permitted to download.")
public void downloadArtifactByNameByNamedController() throws Exception { public void downloadArtifactByNameByNamedController() throws Exception {
downLoadProgress = 1; downLoadProgress = 1;
@@ -359,25 +350,23 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTest {
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
// create target // create target
Target target = entityFactory.generateTarget("4712"); final Target target = testdataFactory.createTarget();
target = targetManagement.createTarget(target); final List<Target> targets = Lists.newArrayList(target);
final List<Target> targets = new ArrayList<>();
targets.add(target);
// create ds // create ds
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
// create artifact // create artifact
final byte random[] = RandomUtils.nextBytes(ARTIFACT_SIZE); final byte random[] = RandomUtils.nextBytes(ARTIFACT_SIZE);
final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), getOsModule(ds),
ds.findFirstModuleByType(osType).getId(), "file1", false); "file1", false);
// download fails as artifact is not yet assigned to target // download fails as artifact is not yet assigned to target
mvc.perform(get("/{tenant}/controller/artifacts/v1/filename/{filename}", tenantAware.getCurrentTenant(), mvc.perform(get("/{tenant}/controller/artifacts/v1/filename/{filename}", tenantAware.getCurrentTenant(),
"file1.tar.bz2")).andExpect(status().isNotFound()); "file1.tar.bz2")).andExpect(status().isNotFound());
// now assign and download successful // now assign and download successful
deploymentManagement.assignDistributionSet(ds, targets); assignDistributionSet(ds, targets);
final MvcResult result = mvc final MvcResult result = mvc
.perform(get("/{tenant}/controller/artifacts/v1/filename/{filename}", tenantAware.getCurrentTenant(), .perform(get("/{tenant}/controller/artifacts/v1/filename/{filename}", tenantAware.getCurrentTenant(),
"file1")) "file1"))
@@ -405,14 +394,12 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTest {
} }
@Test @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.") @Description("Test various HTTP range requests for artifact download, e.g. chunk download or download resume.")
public void rangeDownloadArtifactByName() throws Exception { public void rangeDownloadArtifactByName() throws Exception {
// create target // create target
Target target = entityFactory.generateTarget("4712"); final Target target = testdataFactory.createTarget();
target = targetManagement.createTarget(target); final List<Target> targets = Lists.newArrayList(target);
final List<Target> targets = new ArrayList<>();
targets.add(target);
// create ds // create ds
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
@@ -421,13 +408,13 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTest {
// create artifact // create artifact
final byte random[] = RandomUtils.nextBytes(resultLength); final byte random[] = RandomUtils.nextBytes(resultLength);
final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), getOsModule(ds),
ds.findFirstModuleByType(osType).getId(), "file1", false); "file1", false);
assertThat(random.length).isEqualTo(resultLength); assertThat(random.length).isEqualTo(resultLength);
// now assign and download successful // now assign and download successful
deploymentManagement.assignDistributionSet(ds, targets); assignDistributionSet(ds, targets);
final int range = 100 * 1024; final int range = 100 * 1024;
@@ -515,18 +502,16 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTest {
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
// create target // create target
Target target = entityFactory.generateTarget("4712"); final Target target = testdataFactory.createTarget();
target = targetManagement.createTarget(target); final List<Target> targets = Lists.newArrayList(target);
final List<Target> targets = new ArrayList<>();
targets.add(target);
// create ds // create ds
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
// create artifact // create artifact
final byte random[] = RandomUtils.nextBytes(5 * 1024); final byte random[] = RandomUtils.nextBytes(5 * 1024);
final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), getOsModule(ds),
ds.findFirstModuleByType(osType).getId(), "file1.tar.bz2", false); "file1.tar.bz2", false);
// download fails as artifact is not yet assigned to target // download fails as artifact is not yet assigned to target
mvc.perform(get("/controller/artifacts/v1/filename/{filename}", "file1.tar.bz2")) mvc.perform(get("/controller/artifacts/v1/filename/{filename}", "file1.tar.bz2"))
@@ -537,16 +522,15 @@ public class DdiArtifactDownloadTest extends AbstractRestIntegrationTest {
@Description("Downloads an MD5SUM file by the related artifacts filename.") @Description("Downloads an MD5SUM file by the related artifacts filename.")
public void downloadMd5sumFileByName() throws Exception { public void downloadMd5sumFileByName() throws Exception {
// create target // create target
Target target = entityFactory.generateTarget("4712"); final Target target = testdataFactory.createTarget();
target = targetManagement.createTarget(target);
// create ds // create ds
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
// create artifact // create artifact
final byte random[] = RandomUtils.nextBytes(5 * 1024); final byte random[] = RandomUtils.nextBytes(5 * 1024);
final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), getOsModule(ds),
ds.findFirstModuleByType(osType).getId(), "file1.tar.bz2", false); "file1.tar.bz2", false);
// download // download
final MvcResult result = mvc final MvcResult result = mvc

View File

@@ -27,6 +27,7 @@ import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.test.util.TestdataFactory;
import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest; import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest;
import org.eclipse.hawkbit.rest.util.JsonBuilder; import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; 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.") @Description("Test of the controller can continue a started update even after a cancel command if it so desires.")
public void rootRsCancelActionButContinueAnyway() throws Exception { public void rootRsCancelActionButContinueAnyway() throws Exception {
// prepare test data // prepare test data
final Target target = entityFactory.generateTarget("4712");
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
final Target savedTarget = targetManagement.createTarget(target); final Target savedTarget = testdataFactory.createTarget();
final List<Target> toAssign = new ArrayList<Target>(); final Action updateAction = deploymentManagement.findActionWithDetails(
toAssign.add(savedTarget); assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getActions().get(0));
final Action updateAction = deploymentManagement
.findActionWithDetails(deploymentManagement.assignDistributionSet(ds, toAssign).getActions().get(0));
final Action cancelAction = deploymentManagement.cancelAction(updateAction, final Action cancelAction = deploymentManagement.cancelAction(updateAction,
targetManagement.findTargetByControllerID(savedTarget.getControllerId())); targetManagement.findTargetByControllerID(savedTarget.getControllerId()));
// controller rejects cancelation // controller rejects cancelation
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()) + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant())
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "rejected")) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "rejected"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
@@ -71,9 +68,10 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
final long current = System.currentTimeMillis(); final long current = System.currentTimeMillis();
// get update action anyway // get update action anyway
mvc.perform(get("/{tenant}/controller/v1/4712/deploymentBase/" + updateAction.getId(), mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/deploymentBase/"
tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) + updateAction.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.id", equalTo(String.valueOf(updateAction.getId())))) .andExpect(jsonPath("$.id", equalTo(String.valueOf(updateAction.getId()))))
.andExpect(jsonPath("$.deployment.download", equalTo("forced"))) .andExpect(jsonPath("$.deployment.download", equalTo("forced")))
.andExpect(jsonPath("$.deployment.update", equalTo("forced"))) .andExpect(jsonPath("$.deployment.update", equalTo("forced")))
@@ -85,50 +83,46 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
contains(ds.findFirstModuleByType(appType).getVersion()))); contains(ds.findFirstModuleByType(appType).getVersion())));
// and finish it // and finish it
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + updateAction.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/deploymentBase/"
tenantAware.getCurrentTenant()).content( + updateAction.getId() + "/feedback", tenantAware.getCurrentTenant()).content(
JsonBuilder.deploymentActionFeedback(updateAction.getId().toString(), "closed", "success")) JsonBuilder.deploymentActionFeedback(updateAction.getId().toString(), "closed", "success"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
// check database after test // check database after test
assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet().getId()) assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID)
.isEqualTo(ds.getId()); .getAssignedDistributionSet().getId()).isEqualTo(ds.getId());
assertThat(targetManagement.findTargetByControllerIDWithDetails("4712").getTargetInfo() assertThat(targetManagement.findTargetByControllerIDWithDetails(TestdataFactory.DEFAULT_CONTROLLER_ID)
.getInstalledDistributionSet().getId()).isEqualTo(ds.getId()); .getTargetInfo().getInstalledDistributionSet().getId()).isEqualTo(ds.getId());
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getInstallationDate()) assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
.isGreaterThanOrEqualTo(current); .getInstallationDate()).isGreaterThanOrEqualTo(current);
} }
@Test @Test
@Description("Test for cancel operation of a update action.") @Description("Test for cancel operation of a update action.")
public void rootRsCancelAction() throws Exception { public void rootRsCancelAction() throws Exception {
final Target target = entityFactory.generateTarget("4712");
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
final Target savedTarget = targetManagement.createTarget(target); final Target savedTarget = testdataFactory.createTarget();
final List<Target> toAssign = new ArrayList<Target>(); final Action updateAction = deploymentManagement.findActionWithDetails(
toAssign.add(savedTarget); assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getActions().get(0));
final Action updateAction = deploymentManagement
.findActionWithDetails(deploymentManagement.assignDistributionSet(ds, toAssign).getActions().get(0));
long current = System.currentTimeMillis(); long current = System.currentTimeMillis();
mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant())) mvc.perform(get("/{tenant}/controller/v1/{controller}", tenantAware.getCurrentTenant(),
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) TestdataFactory.DEFAULT_CONTROLLER_ID)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_JSON_HAL_UTF)) .andExpect(content().contentType(APPLICATION_JSON_HAL_UTF))
.andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00"))) .andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00")))
.andExpect(jsonPath("$._links.deploymentBase.href", .andExpect(jsonPath("$._links.deploymentBase.href",
startsWith("http://localhost/" + tenantAware.getCurrentTenant() startsWith("http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/"
+ "/controller/v1/4712/deploymentBase/" + updateAction.getId()))); + TestdataFactory.DEFAULT_CONTROLLER_ID + "/deploymentBase/" + updateAction.getId())));
Thread.sleep(1); // is required: otherwise processing the next line is Thread.sleep(1); // is required: otherwise processing the next line is
// often too fast and // often too fast and
// the following assert will fail // the following assert will fail
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
.isLessThanOrEqualTo(System.currentTimeMillis()); .getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
.isGreaterThanOrEqualTo(current); .getLastTargetQuery()).isGreaterThanOrEqualTo(current);
// Retrieved is reported // Retrieved is reported
@@ -147,39 +141,38 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
assertThat(activeActionsByTarget.get(0).getStatus()).isEqualTo(Status.CANCELING); assertThat(activeActionsByTarget.get(0).getStatus()).isEqualTo(Status.CANCELING);
current = System.currentTimeMillis(); current = System.currentTimeMillis();
mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant())) mvc.perform(get("/{tenant}/controller/v1/{controller}", tenantAware.getCurrentTenant(),
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) TestdataFactory.DEFAULT_CONTROLLER_ID)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_JSON_HAL_UTF)) .andExpect(content().contentType(APPLICATION_JSON_HAL_UTF))
.andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00"))) .andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00")))
.andExpect(jsonPath("$._links.cancelAction.href", .andExpect(jsonPath("$._links.cancelAction.href",
equalTo("http://localhost/" + tenantAware.getCurrentTenant() equalTo("http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/"
+ "/controller/v1/4712/cancelAction/" + cancelAction.getId()))); + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId())));
Thread.sleep(1); // is required: otherwise processing the next line is Thread.sleep(1); // is required: otherwise processing the next line is
// often too fast and // often too fast and
// the following assert will fail // the following assert will fail
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
.isLessThanOrEqualTo(System.currentTimeMillis()); .getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
.isGreaterThanOrEqualTo(current); .getLastTargetQuery()).isGreaterThanOrEqualTo(current);
current = System.currentTimeMillis(); current = System.currentTimeMillis();
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
.isLessThanOrEqualTo(System.currentTimeMillis()); .getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
mvc.perform( mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
get("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId(), tenantAware.getCurrentTenant()) + cancelAction.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON))
.accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.id", equalTo(String.valueOf(cancelAction.getId())))) .andExpect(jsonPath("$.id", equalTo(String.valueOf(cancelAction.getId()))))
.andExpect(jsonPath("$.cancelAction.stopId", equalTo(String.valueOf(updateAction.getId())))); .andExpect(jsonPath("$.cancelAction.stopId", equalTo(String.valueOf(updateAction.getId()))));
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
.isLessThanOrEqualTo(System.currentTimeMillis()); .getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
.isGreaterThanOrEqualTo(current); .getLastTargetQuery()).isGreaterThanOrEqualTo(current);
// controller confirmed cancelled action, should not be active anymore // controller confirmed cancelled action, should not be active anymore
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON) + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)
.content(JsonBuilder.cancelActionFeedback(updateAction.getId().toString(), "closed")) .content(JsonBuilder.cancelActionFeedback(updateAction.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
@@ -197,14 +190,17 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
public void badCancelAction() throws Exception { public void badCancelAction() throws Exception {
// not allowed methods // not allowed methods
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/1", tenantAware.getCurrentTenant())) mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/1",
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed()); tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isMethodNotAllowed());
mvc.perform(put("/{tenant}/controller/v1/4712/cancelAction/1", tenantAware.getCurrentTenant())) mvc.perform(put("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/1",
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed()); tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isMethodNotAllowed());
mvc.perform(delete("/{tenant}/controller/v1/4712/cancelAction/1", tenantAware.getCurrentTenant())) mvc.perform(delete("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/1",
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed()); tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isMethodNotAllowed());
// non existing target // non existing target
mvc.perform(get("/{tenant}/controller/v1/34534543/cancelAction/1", tenantAware.getCurrentTenant()) mvc.perform(get("/{tenant}/controller/v1/34534543/cancelAction/1", tenantAware.getCurrentTenant())
@@ -221,13 +217,12 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
} }
private Action createCancelAction(final String targetid) { private Action createCancelAction(final String targetid) {
final Target target = entityFactory.generateTarget(targetid);
final DistributionSet ds = testdataFactory.createDistributionSet(targetid); final DistributionSet ds = testdataFactory.createDistributionSet(targetid);
final Target savedTarget = targetManagement.createTarget(target); final Target savedTarget = testdataFactory.createTarget(targetid);
final List<Target> toAssign = new ArrayList<Target>(); final List<Target> toAssign = new ArrayList<>();
toAssign.add(savedTarget); toAssign.add(savedTarget);
final Action updateAction = deploymentManagement final Action updateAction = deploymentManagement
.findActionWithDetails(deploymentManagement.assignDistributionSet(ds, toAssign).getActions().get(0)); .findActionWithDetails(assignDistributionSet(ds, toAssign).getActions().get(0));
return deploymentManagement.cancelAction(updateAction, return deploymentManagement.cancelAction(updateAction,
targetManagement.findTargetByControllerID(savedTarget.getControllerId())); targetManagement.findTargetByControllerID(savedTarget.getControllerId()));
@@ -237,13 +232,12 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
@Description("Tests the feedback channel of the cancel operation.") @Description("Tests the feedback channel of the cancel operation.")
public void rootRsCancelActionFeedback() throws Exception { public void rootRsCancelActionFeedback() throws Exception {
final Target target = entityFactory.generateTarget("4712");
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
final Target savedTarget = targetManagement.createTarget(target); final Target savedTarget = testdataFactory.createTarget();
final Action updateAction = deploymentManagement.findActionWithDetails( 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 // cancel action manually
final Action cancelAction = deploymentManagement.cancelAction(updateAction, final Action cancelAction = deploymentManagement.cancelAction(updateAction,
@@ -252,49 +246,49 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
long current = System.currentTimeMillis(); long current = System.currentTimeMillis();
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()) + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant())
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "proceeding")) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "proceeding"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
.isGreaterThanOrEqualTo(current); .getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(3); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(3);
current = System.currentTimeMillis(); current = System.currentTimeMillis();
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()) + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant())
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "resumed")) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "resumed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
.isGreaterThanOrEqualTo(current); .getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(4); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(4);
current = System.currentTimeMillis(); current = System.currentTimeMillis();
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()) + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant())
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "scheduled")) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "scheduled"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
.isGreaterThanOrEqualTo(current); .getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(5); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(5);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
// cancelation canceled -> should remove the action from active // cancelation canceled -> should remove the action from active
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
current = System.currentTimeMillis(); current = System.currentTimeMillis();
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()) + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant())
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "canceled")) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "canceled"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
.isGreaterThanOrEqualTo(current); .getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(6); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(6);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
@@ -303,25 +297,25 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
// error // error
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
current = System.currentTimeMillis(); current = System.currentTimeMillis();
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()) + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant())
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "rejected")) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "rejected"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
.isGreaterThanOrEqualTo(current); .getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(7); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(7);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
// cancelaction closed -> should remove the action from active // cancelaction closed -> should remove the action from active
current = System.currentTimeMillis(); current = System.currentTimeMillis();
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()) + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant())
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed")) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery()) assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
.isGreaterThanOrEqualTo(current); .getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(8); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(8);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(0); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(0);
} }
@@ -329,19 +323,18 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
@Test @Test
@Description("Tests the feeback chanel of for multiple open cancel operations on the same target.") @Description("Tests the feeback chanel of for multiple open cancel operations on the same target.")
public void multipleCancelActionFeedback() throws Exception { public void multipleCancelActionFeedback() throws Exception {
final Target target = entityFactory.generateTarget("4712");
final DistributionSet ds = testdataFactory.createDistributionSet("", true); final DistributionSet ds = testdataFactory.createDistributionSet("", true);
final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true); final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true);
final DistributionSet ds3 = testdataFactory.createDistributionSet("3", true); final DistributionSet ds3 = testdataFactory.createDistributionSet("3", true);
final Target savedTarget = targetManagement.createTarget(target); final Target savedTarget = testdataFactory.createTarget();
final Action updateAction = deploymentManagement.findActionWithDetails( 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( 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( 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); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(3);
@@ -355,26 +348,25 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(3); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(3);
assertThat(deploymentManagement.findActionsByTarget(savedTarget)).hasSize(3); assertThat(deploymentManagement.findActionsByTarget(savedTarget)).hasSize(3);
mvc.perform( mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
get("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId(), tenantAware.getCurrentTenant()) + cancelAction.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON))
.accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id", equalTo(String.valueOf(cancelAction.getId())))) .andExpect(jsonPath("$.id", equalTo(String.valueOf(cancelAction.getId()))))
.andExpect(jsonPath("$.cancelAction.stopId", equalTo(String.valueOf(updateAction.getId())))); .andExpect(jsonPath("$.cancelAction.stopId", equalTo(String.valueOf(updateAction.getId()))));
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(6); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(6);
mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant())) mvc.perform(get("/{tenant}/controller/v1/{controllerId}", tenantAware.getCurrentTenant(),
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) TestdataFactory.DEFAULT_CONTROLLER_ID)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_JSON_HAL_UTF)) .andExpect(content().contentType(APPLICATION_JSON_HAL_UTF))
.andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00"))) .andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00")))
.andExpect(jsonPath("$._links.cancelAction.href", .andExpect(jsonPath("$._links.cancelAction.href",
equalTo("http://localhost/" + tenantAware.getCurrentTenant() equalTo("http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/"
+ "/controller/v1/4712/cancelAction/" + cancelAction.getId()))); + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId())));
// now lets return feedback for the first cancelation // now lets return feedback for the first cancelation
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()) + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant())
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed")) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
@@ -383,32 +375,35 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
// 1 update actions, 1 cancel actions // 1 update actions, 1 cancel actions
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2);
assertThat(deploymentManagement.findActionsByTarget(savedTarget)).hasSize(3); assertThat(deploymentManagement.findActionsByTarget(savedTarget)).hasSize(3);
mvc.perform(get("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction2.getId(), mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) + cancelAction2.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.id", equalTo(String.valueOf(cancelAction2.getId())))) .andExpect(jsonPath("$.id", equalTo(String.valueOf(cancelAction2.getId()))))
.andExpect(jsonPath("$.cancelAction.stopId", equalTo(String.valueOf(updateAction2.getId())))); .andExpect(jsonPath("$.cancelAction.stopId", equalTo(String.valueOf(updateAction2.getId()))));
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(8); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(8);
mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant())) mvc.perform(get("/{tenant}/controller/v1/{controller}", tenantAware.getCurrentTenant(),
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) TestdataFactory.DEFAULT_CONTROLLER_ID)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_JSON_HAL_UTF)) .andExpect(content().contentType(APPLICATION_JSON_HAL_UTF))
.andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00"))) .andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00")))
.andExpect(jsonPath("$._links.cancelAction.href", .andExpect(jsonPath("$._links.cancelAction.href",
equalTo("http://localhost/" + tenantAware.getCurrentTenant() equalTo("http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/"
+ "/controller/v1/4712/cancelAction/" + cancelAction2.getId()))); + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction2.getId())));
// now lets return feedback for the second cancelation // now lets return feedback for the second cancelation
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction2.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()) + cancelAction2.getId() + "/feedback", tenantAware.getCurrentTenant())
.content(JsonBuilder.cancelActionFeedback(cancelAction2.getId().toString(), "closed")) .content(JsonBuilder.cancelActionFeedback(cancelAction2.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(9); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(9);
assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet()).isEqualTo(ds3); assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID)
mvc.perform(get("/{tenant}/controller/v1/4712/deploymentBase/" + updateAction3.getId(), .getAssignedDistributionSet()).isEqualTo(ds3);
tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); 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); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(10);
// 1 update actions, 0 cancel actions // 1 update actions, 0 cancel actions
@@ -421,18 +416,20 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
// action is in cancelling state // action is in cancelling state
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
assertThat(deploymentManagement.findActionsByTarget(savedTarget)).hasSize(3); 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(), mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) + cancelAction3.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.id", equalTo(String.valueOf(cancelAction3.getId())))) .andExpect(jsonPath("$.id", equalTo(String.valueOf(cancelAction3.getId()))))
.andExpect(jsonPath("$.cancelAction.stopId", equalTo(String.valueOf(updateAction3.getId())))); .andExpect(jsonPath("$.cancelAction.stopId", equalTo(String.valueOf(updateAction3.getId()))));
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(12); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(12);
// now lets return feedback for the third cancelation // now lets return feedback for the third cancelation
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction3.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()) + cancelAction3.getId() + "/feedback", tenantAware.getCurrentTenant())
.content(JsonBuilder.cancelActionFeedback(cancelAction3.getId().toString(), "closed")) .content(JsonBuilder.cancelActionFeedback(cancelAction3.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON_UTF8)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON_UTF8))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
@@ -446,14 +443,11 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
@Test @Test
@Description("Tests the feeback channel closing for too many feedbacks, i.e. denial of service prevention.") @Description("Tests the feeback channel closing for too many feedbacks, i.e. denial of service prevention.")
public void tooMuchCancelActionFeedback() throws Exception { public void tooMuchCancelActionFeedback() throws Exception {
final Target target = targetManagement.createTarget(entityFactory.generateTarget("4712")); final Target target = testdataFactory.createTarget();
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
final List<Target> toAssign = new ArrayList<Target>();
toAssign.add(target);
final Action action = deploymentManagement.findActionWithDetails( 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, final Action cancelAction = deploymentManagement.cancelAction(action,
targetManagement.findTargetByControllerID(target.getControllerId())); targetManagement.findTargetByControllerID(target.getControllerId()));
@@ -463,49 +457,49 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
// stores an action status, so // stores an action status, so
// only 97 action status left // only 97 action status left
for (int i = 0; i < 98; i++) { for (int i = 0; i < 98; i++) {
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()).content(feedback).contentType(MediaType.APPLICATION_JSON) + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()).content(feedback)
.accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()); .andExpect(status().isOk());
} }
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()).content(feedback).contentType(MediaType.APPLICATION_JSON) + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()).content(feedback)
.accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isForbidden()); .andExpect(status().isForbidden());
} }
@Test @Test
@Description("test the correct rejection of various invalid feedback requests") @Description("test the correct rejection of various invalid feedback requests")
public void badCancelActionFeedback() throws Exception { public void badCancelActionFeedback() throws Exception {
final Action cancelAction = createCancelAction("4712"); final Action cancelAction = createCancelAction(TestdataFactory.DEFAULT_CONTROLLER_ID);
final Action cancelAction2 = createCancelAction("4715"); final Action cancelAction2 = createCancelAction("4715");
// not allowed methods // not allowed methods
mvc.perform(put("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", mvc.perform(put("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()) + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant())
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed")) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
mvc.perform(delete("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", mvc.perform(delete("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print()) + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()))
.andExpect(status().isMethodNotAllowed()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
mvc.perform(get("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print()) + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant()))
.andExpect(status().isMethodNotAllowed()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
// bad content type // bad content type
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()) + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant())
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed")) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_ATOM_XML).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_ATOM_XML).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isUnsupportedMediaType()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isUnsupportedMediaType());
// bad body // bad body
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()) + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant())
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "546456456")) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "546456456"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
@@ -518,25 +512,27 @@ public class DdiCancelActionTest extends AbstractRestIntegrationTest {
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
// invalid action // invalid action
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()).content(JsonBuilder.cancelActionFeedback("sdfsdfsdfs", "closed")) + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant())
.content(JsonBuilder.cancelActionFeedback("sdfsdfsdfs", "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()).content(JsonBuilder.cancelActionFeedback("1234", "closed")) + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant())
.content(JsonBuilder.cancelActionFeedback("1234", "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
// right action but for wrong target // right action but for wrong target
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()) + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant())
.content(JsonBuilder.cancelActionFeedback(cancelAction2.getId().toString(), "closed")) .content(JsonBuilder.cancelActionFeedback(cancelAction2.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
// finally get it right :) // finally get it right :)
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
tenantAware.getCurrentTenant()) + cancelAction.getId() + "/feedback", tenantAware.getCurrentTenant())
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed")) .content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());

View File

@@ -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.) " @Description("We verify that the config data (i.e. device attributes like serial number, hardware revision etc.) "
+ "are requested only once from the device.") + "are requested only once from the device.")
public void requestConfigDataIfEmpty() throws Exception { public void requestConfigDataIfEmpty() throws Exception {
final Target target = entityFactory.generateTarget("4712"); final Target savedTarget = testdataFactory.createTarget("4712");
final Target savedTarget = targetManagement.createTarget(target);
final long current = System.currentTimeMillis(); final long current = System.currentTimeMillis();
mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant())) mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant()))
@@ -84,7 +83,7 @@ public class DdiConfigDataTest extends AbstractRestIntegrationTest {
@Description("We verify that the config data (i.e. device attributes like serial number, hardware revision etc.) " @Description("We verify that the config data (i.e. device attributes like serial number, hardware revision etc.) "
+ "can be uploaded correctly by the controller.") + "can be uploaded correctly by the controller.")
public void putConfigData() throws Exception { public void putConfigData() throws Exception {
targetManagement.createTarget(entityFactory.generateTarget("4717")); testdataFactory.createTarget("4717");
// initial // initial
final Map<String, String> attributes = new HashMap<>(); final Map<String, String> attributes = new HashMap<>();
@@ -127,7 +126,7 @@ public class DdiConfigDataTest extends AbstractRestIntegrationTest {
@Description("We verify that the config data (i.e. device attributes like serial number, hardware revision etc.) " @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.") + "upload limitation is inplace which is meant to protect the server from malicious attempts.")
public void putToMuchConfigData() throws Exception { public void putToMuchConfigData() throws Exception {
targetManagement.createTarget(entityFactory.generateTarget("4717")); testdataFactory.createTarget("4717");
// initial // initial
Map<String, String> attributes = new HashMap<>(); Map<String, String> attributes = new HashMap<>();
@@ -150,8 +149,7 @@ public class DdiConfigDataTest extends AbstractRestIntegrationTest {
@Description("We verify that the config data (i.e. device attributes like serial number, hardware revision etc.) " @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.") + "resource behaves as exptected in cae of invalid request attempts.")
public void badConfigData() throws Exception { public void badConfigData() throws Exception {
final Target target = entityFactory.generateTarget("4712"); final Target savedTarget = testdataFactory.createTarget("4712");
final Target savedTarget = targetManagement.createTarget(target);
// not allowed methods // not allowed methods
mvc.perform(post("/{tenant}/controller/v1/4712/configData", tenantAware.getCurrentTenant())) mvc.perform(post("/{tenant}/controller/v1/4712/configData", tenantAware.getCurrentTenant()))

View File

@@ -79,7 +79,7 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTest {
final Target target = testdataFactory.createTarget(); final Target target = testdataFactory.createTarget();
final DistributionSet distributionSet = testdataFactory.createDistributionSet(""); 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(); final Long softwareModuleId = distributionSet.getModules().stream().findFirst().get().getId();
mvc.perform(get("/{tenant}/controller/v1/{targetNotExist}/softwaremodules/{softwareModuleId}/artifacts", mvc.perform(get("/{tenant}/controller/v1/{targetNotExist}/softwaremodules/{softwareModuleId}/artifacts",
@@ -101,29 +101,29 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTest {
@Description("Forced deployment to a controller. Checks if the resource reponse payload for a given deployment is as expected.") @Description("Forced deployment to a controller. Checks if the resource reponse payload for a given deployment is as expected.")
public void deplomentForceAction() throws Exception { public void deplomentForceAction() throws Exception {
// Prepare test data // Prepare test data
final Target target = entityFactory.generateTarget("4712");
final DistributionSet ds = testdataFactory.createDistributionSet("", true); final DistributionSet ds = testdataFactory.createDistributionSet("", true);
final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true); final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true);
final byte random[] = RandomUtils.nextBytes(5 * 1024); final byte random[] = RandomUtils.nextBytes(5 * 1024);
final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), getOsModule(ds),
ds.findFirstModuleByType(osType).getId(), "test1", false); "test1", false);
final Artifact artifactSignature = artifactManagement.createArtifact(new ByteArrayInputStream(random), 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.findActiveActionsByTarget(savedTarget)).isEmpty();
assertThat(deploymentManagement.countActionsAll()).isEqualTo(0); assertThat(deploymentManagement.countActionsAll()).isEqualTo(0);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(0); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(0);
List<Target> saved = deploymentManagement.assignDistributionSet(ds.getId(), ActionType.FORCED, List<Target> 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); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
final Action action = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0); final Action action = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0);
assertThat(deploymentManagement.countActionsAll()).isEqualTo(1); assertThat(deploymentManagement.countActionsAll()).isEqualTo(1);
saved = deploymentManagement.assignDistributionSet(ds2, saved).getAssignedEntity(); saved = assignDistributionSet(ds2, saved).getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2);
assertThat(deploymentManagement.countActionsAll()).isEqualTo(2); assertThat(deploymentManagement.countActionsAll()).isEqualTo(2);
@@ -225,11 +225,12 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTest {
@Description("Checks that the deployementBase URL changes when the action is switched from soft to forced in TIMEFORCED case.") @Description("Checks that the deployementBase URL changes when the action is switched from soft to forced in TIMEFORCED case.")
public void changeEtagIfActionSwitchesFromSoftToForced() throws Exception { public void changeEtagIfActionSwitchesFromSoftToForced() throws Exception {
// Prepare test data // Prepare test data
final Target target = targetManagement.createTarget(entityFactory.generateTarget("4712")); final Target target = testdataFactory.createTarget("4712");
final DistributionSet ds = testdataFactory.createDistributionSet("", true); final DistributionSet ds = testdataFactory.createDistributionSet("", true);
final DistributionSetAssignmentResult result = deploymentManagement.assignDistributionSet(ds.getId(), 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); final Action action = deploymentManagement.findActiveActionsByTarget(result.getAssignedEntity().get(0)).get(0);
@@ -264,29 +265,29 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTest {
@Description("Attempt/soft deployment to a controller. Checks if the resource reponse payload for a given deployment is as expected.") @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 { public void deplomentAttemptAction() throws Exception {
// Prepare test data // Prepare test data
final Target target = entityFactory.generateTarget("4712");
final DistributionSet ds = testdataFactory.createDistributionSet("", true); final DistributionSet ds = testdataFactory.createDistributionSet("", true);
final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true); final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true);
final byte random[] = RandomUtils.nextBytes(5 * 1024); final byte random[] = RandomUtils.nextBytes(5 * 1024);
final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), getOsModule(ds),
ds.findFirstModuleByType(osType).getId(), "test1", false); "test1", false);
final Artifact artifactSignature = artifactManagement.createArtifact(new ByteArrayInputStream(random), 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.findActiveActionsByTarget(savedTarget)).isEmpty();
assertThat(deploymentManagement.countActionsAll()).isEqualTo(0); assertThat(deploymentManagement.countActionsAll()).isEqualTo(0);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(0); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(0);
List<Target> saved = deploymentManagement.assignDistributionSet(ds.getId(), ActionType.SOFT, List<Target> 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); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
final Action action = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0); final Action action = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0);
assertThat(deploymentManagement.countActionsAll()).isEqualTo(1); assertThat(deploymentManagement.countActionsAll()).isEqualTo(1);
saved = deploymentManagement.assignDistributionSet(ds2, saved).getAssignedEntity(); saved = assignDistributionSet(ds2, saved).getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2);
assertThat(deploymentManagement.countActionsAll()).isEqualTo(2); assertThat(deploymentManagement.countActionsAll()).isEqualTo(2);
@@ -334,41 +335,34 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTest {
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].filename", contains("test1"))) .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].filename", contains("test1")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.md5", .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.md5",
contains(artifact.getMd5Hash()))) contains(artifact.getMd5Hash())))
.andExpect( .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.sha1",
jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.sha1", contains(artifact.getSha1Hash())))
contains(artifact.getSha1Hash())))
.andExpect( .andExpect(
jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.download.href", jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.download.href",
contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant() contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant()
+ "/controller/v1/4712/softwaremodules/" + "/controller/v1/4712/softwaremodules/"
+ findDistributionSetByAction.findFirstModuleByType(osType).getId() + getOsModule(findDistributionSetByAction) + "/artifacts/test1")))
+ "/artifacts/test1")))
.andExpect( .andExpect(
jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.md5sum.href", jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.md5sum.href",
contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant() contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant()
+ "/controller/v1/4712/softwaremodules/" + "/controller/v1/4712/softwaremodules/"
+ findDistributionSetByAction.findFirstModuleByType(osType).getId() + getOsModule(findDistributionSetByAction) + "/artifacts/test1.MD5SUM")))
+ "/artifacts/test1.MD5SUM")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].size", contains(5 * 1024))) .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].size", contains(5 * 1024)))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].filename", .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].filename",
contains("test1.signature"))) contains("test1.signature")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].hashes.md5", .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].hashes.md5",
contains(artifactSignature.getMd5Hash()))) contains(artifactSignature.getMd5Hash())))
.andExpect( .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].hashes.sha1",
jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].hashes.sha1", contains(artifactSignature.getSha1Hash())))
contains(artifactSignature.getSha1Hash())))
.andExpect( .andExpect(
jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.download.href", jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.download.href",
contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant() contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant()
+ "/controller/v1/4712/softwaremodules/" + "/controller/v1/4712/softwaremodules/"
+ findDistributionSetByAction.findFirstModuleByType(osType).getId() + getOsModule(findDistributionSetByAction) + "/artifacts/test1.signature")))
+ "/artifacts/test1.signature"))) .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.md5sum.href",
.andExpect( contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant()
jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.md5sum.href", + "/controller/v1/4712/softwaremodules/" + getOsModule(findDistributionSetByAction)
contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant() + "/artifacts/test1.signature.MD5SUM")))
+ "/controller/v1/4712/softwaremodules/"
+ findDistributionSetByAction.findFirstModuleByType(osType).getId()
+ "/artifacts/test1.signature.MD5SUM")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].version", .andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].version",
contains(ds.findFirstModuleByType(appType).getVersion()))) contains(ds.findFirstModuleByType(appType).getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].name", .andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].name",
@@ -388,29 +382,28 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTest {
@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.") @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 { public void deplomentAutoForceAction() throws Exception {
// Prepare test data // Prepare test data
final Target target = entityFactory.generateTarget("4712");
final DistributionSet ds = testdataFactory.createDistributionSet("", true); final DistributionSet ds = testdataFactory.createDistributionSet("", true);
final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true); final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true);
final byte random[] = RandomUtils.nextBytes(5 * 1024); final byte random[] = RandomUtils.nextBytes(5 * 1024);
final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), getOsModule(ds),
ds.findFirstModuleByType(osType).getId(), "test1", false); "test1", false);
final Artifact artifactSignature = artifactManagement.createArtifact(new ByteArrayInputStream(random), 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.findActiveActionsByTarget(savedTarget)).isEmpty();
assertThat(deploymentManagement.countActionsAll()).isEqualTo(0); assertThat(deploymentManagement.countActionsAll()).isEqualTo(0);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(0); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(0);
List<Target> saved = deploymentManagement.assignDistributionSet(ds.getId(), ActionType.TIMEFORCED, List<Target> 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); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
final Action action = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0); final Action action = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0);
assertThat(deploymentManagement.countActionsAll()).isEqualTo(1); assertThat(deploymentManagement.countActionsAll()).isEqualTo(1);
saved = deploymentManagement.assignDistributionSet(ds2, saved).getAssignedEntity(); saved = assignDistributionSet(ds2, saved).getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2);
@@ -511,7 +504,7 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTest {
@Test @Test
@Description("Test various invalid access attempts to the deployment resource und the expected behaviour of the server.") @Description("Test various invalid access attempts to the deployment resource und the expected behaviour of the server.")
public void badDeploymentAction() throws Exception { public void badDeploymentAction() throws Exception {
final Target target = targetManagement.createTarget(entityFactory.generateTarget("4712")); final Target target = testdataFactory.createTarget("4712");
// not allowed methods // not allowed methods
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/1", tenantAware.getCurrentTenant())) mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/1", tenantAware.getCurrentTenant()))
@@ -536,8 +529,8 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTest {
toAssign.add(target); toAssign.add(target);
final DistributionSet savedSet = testdataFactory.createDistributionSet(""); final DistributionSet savedSet = testdataFactory.createDistributionSet("");
final Action action1 = deploymentManagement.findActionWithDetails( final Action action1 = deploymentManagement
deploymentManagement.assignDistributionSet(savedSet, toAssign).getActions().get(0)); .findActionWithDetails(assignDistributionSet(savedSet, toAssign).getActions().get(0));
mvc.perform( mvc.perform(
get("/{tenant}/controller/v1/4712/deploymentBase/" + action1.getId(), tenantAware.getCurrentTenant())) get("/{tenant}/controller/v1/4712/deploymentBase/" + action1.getId(), tenantAware.getCurrentTenant()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
@@ -551,13 +544,10 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTest {
@Description("The server protects itself against to many feedback upload attempts. The test verfies that " @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.") + "it is not possible to exceed the configured maximum number of feedback uplods.")
public void toMuchDeplomentActionFeedback() throws Exception { 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 DistributionSet ds = testdataFactory.createDistributionSet("");
final List<Target> toAssign = new ArrayList<>(); assignDistributionSet(ds.getId(), "4712");
toAssign.add(target);
deploymentManagement.assignDistributionSet(ds.getId(), new String[] { "4712" });
final Action action = deploymentManagement.findActionsByTarget(target).get(0); final Action action = deploymentManagement.findActionsByTarget(target).get(0);
final String feedback = JsonBuilder.deploymentActionFeedback(action.getId().toString(), "proceeding"); final String feedback = JsonBuilder.deploymentActionFeedback(action.getId().toString(), "proceeding");
@@ -578,12 +568,9 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTest {
@Test @Test
@Description("Multiple uploads of deployment status feedback to the server.") @Description("Multiple uploads of deployment status feedback to the server.")
public void multipleDeplomentActionFeedback() throws Exception { public void multipleDeplomentActionFeedback() throws Exception {
final Target target1 = entityFactory.generateTarget("4712"); final Target savedTarget1 = testdataFactory.createTarget("4712");
final Target target2 = entityFactory.generateTarget("4713"); testdataFactory.createTarget("4713");
final Target target3 = entityFactory.generateTarget("4714"); testdataFactory.createTarget("4714");
final Target savedTarget1 = targetManagement.createTarget(target1);
targetManagement.createTarget(target2);
targetManagement.createTarget(target3);
final DistributionSet ds1 = testdataFactory.createDistributionSet("1", true); final DistributionSet ds1 = testdataFactory.createDistributionSet("1", true);
final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true); final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true);
@@ -592,12 +579,12 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTest {
final List<Target> toAssign = new ArrayList<>(); final List<Target> toAssign = new ArrayList<>();
toAssign.add(savedTarget1); toAssign.add(savedTarget1);
final Action action1 = deploymentManagement.findActionWithDetails( final Action action1 = deploymentManagement
deploymentManagement.assignDistributionSet(ds1.getId(), new String[] { "4712" }).getActions().get(0)); .findActionWithDetails(assignDistributionSet(ds1.getId(), "4712").getActions().get(0));
final Action action2 = deploymentManagement.findActionWithDetails( final Action action2 = deploymentManagement
deploymentManagement.assignDistributionSet(ds2.getId(), new String[] { "4712" }).getActions().get(0)); .findActionWithDetails(assignDistributionSet(ds2.getId(), "4712").getActions().get(0));
final Action action3 = deploymentManagement.findActionWithDetails( final Action action3 = deploymentManagement
deploymentManagement.assignDistributionSet(ds3.getId(), new String[] { "4712" }).getActions().get(0)); .findActionWithDetails(assignDistributionSet(ds3.getId(), "4712").getActions().get(0));
Target myT = targetManagement.findTargetByControllerID("4712"); Target myT = targetManagement.findTargetByControllerID("4712");
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
@@ -680,17 +667,15 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTest {
@Test @Test
@Description("Verfies that an update action is correctly set to error if the controller provides error feedback.") @Description("Verfies that an update action is correctly set to error if the controller provides error feedback.")
public void rootRsSingleDeplomentActionWithErrorFeedback() throws Exception { public void rootRsSingleDeplomentActionWithErrorFeedback() throws Exception {
final Target target = entityFactory.generateTarget("4712");
DistributionSet ds = testdataFactory.createDistributionSet(""); DistributionSet ds = testdataFactory.createDistributionSet("");
final Target savedTarget = testdataFactory.createTarget("4712");
final Target savedTarget = targetManagement.createTarget(target);
List<Target> toAssign = new ArrayList<>(); List<Target> toAssign = new ArrayList<>();
toAssign.add(savedTarget); toAssign.add(savedTarget);
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.UNKNOWN); .isEqualTo(TargetUpdateStatus.UNKNOWN);
deploymentManagement.assignDistributionSet(ds, toAssign); assignDistributionSet(ds, toAssign);
final Action action = deploymentManagement.findActionsByDistributionSet(pageReq, ds).getContent().get(0); final Action action = deploymentManagement.findActionsByDistributionSet(pageReq, ds).getContent().get(0);
long current = System.currentTimeMillis(); long current = System.currentTimeMillis();
@@ -720,10 +705,10 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTest {
assertThat(actionStatusMessages).haveAtLeast(1, new ActionStatusCondition(Status.ERROR)); assertThat(actionStatusMessages).haveAtLeast(1, new ActionStatusCondition(Status.ERROR));
// redo // redo
toAssign = new ArrayList<Target>(); toAssign = new ArrayList<>();
toAssign.add(targetManagement.findTargetByControllerID("4712")); toAssign.add(targetManagement.findTargetByControllerID("4712"));
ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId()); ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId());
deploymentManagement.assignDistributionSet(ds, toAssign); assignDistributionSet(ds, toAssign);
final Action action2 = deploymentManagement.findActiveActionsByTarget(myT).get(0); final Action action2 = deploymentManagement.findActiveActionsByTarget(myT).get(0);
current = System.currentTimeMillis(); current = System.currentTimeMillis();
lastModified = targetManagement.findTargetByControllerID("4712").getLastModifiedAt(); lastModified = targetManagement.findTargetByControllerID("4712").getLastModifiedAt();
@@ -757,17 +742,15 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTest {
@Test @Test
@Description("Verfies that the controller can provided as much feedback entries as necessry as long as it is in the configured limites.") @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 { public void rootRsSingleDeplomentActionFeedback() throws Exception {
final Target target = entityFactory.generateTarget("4712");
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
final Target savedTarget = targetManagement.createTarget(target); final Target savedTarget = testdataFactory.createTarget("4712");
final List<Target> toAssign = new ArrayList<>(); final List<Target> toAssign = Lists.newArrayList(savedTarget);
toAssign.add(savedTarget);
Target myT = targetManagement.findTargetByControllerID("4712"); Target myT = targetManagement.findTargetByControllerID("4712");
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.UNKNOWN); assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.UNKNOWN);
deploymentManagement.assignDistributionSet(ds, toAssign); assignDistributionSet(ds, toAssign);
final Action action = deploymentManagement.findActionsByDistributionSet(pageReq, ds).getContent().get(0); final Action action = deploymentManagement.findActionsByDistributionSet(pageReq, ds).getContent().get(0);
myT = targetManagement.findTargetByControllerID("4712"); myT = targetManagement.findTargetByControllerID("4712");
@@ -914,8 +897,6 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTest {
@Test @Test
@Description("Various forbidden request appempts on the feedback resource. Ensures correct answering behaviour as expected to these kind of errors.") @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 { public void badDeplomentActionFeedback() throws Exception {
final Target target = entityFactory.generateTarget("4712");
final Target target2 = entityFactory.generateTarget("4713");
final DistributionSet savedSet = testdataFactory.createDistributionSet(""); final DistributionSet savedSet = testdataFactory.createDistributionSet("");
final DistributionSet savedSet2 = testdataFactory.createDistributionSet("1"); final DistributionSet savedSet2 = testdataFactory.createDistributionSet("1");
@@ -925,8 +906,8 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTest {
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isNotFound()); .andExpect(status().isNotFound());
Target savedTarget = targetManagement.createTarget(target); Target savedTarget = testdataFactory.createTarget("4712");
final Target savedTarget2 = targetManagement.createTarget(target2); final Target savedTarget2 = testdataFactory.createTarget("4713");
// Action does not exists // Action does not exists
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/1234/feedback", tenantAware.getCurrentTenant()) mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/1234/feedback", tenantAware.getCurrentTenant())
@@ -937,9 +918,8 @@ public class DdiDeploymentBaseTest extends AbstractRestIntegrationTest {
final List<Target> toAssign = Lists.newArrayList(savedTarget); final List<Target> toAssign = Lists.newArrayList(savedTarget);
final List<Target> toAssign2 = Lists.newArrayList(savedTarget2); final List<Target> toAssign2 = Lists.newArrayList(savedTarget2);
savedTarget = deploymentManagement.assignDistributionSet(savedSet, toAssign).getAssignedEntity().iterator() savedTarget = assignDistributionSet(savedSet, toAssign).getAssignedEntity().iterator().next();
.next(); assignDistributionSet(savedSet2, toAssign2);
deploymentManagement.assignDistributionSet(savedSet2, toAssign2);
// wrong format // wrong format
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/AAAA/feedback", tenantAware.getCurrentTenant()) mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/AAAA/feedback", tenantAware.getCurrentTenant())

View File

@@ -23,11 +23,12 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 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.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.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.TargetCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetUpdatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.TargetUpdatedEvent;
import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action;
@@ -96,7 +97,7 @@ public class DdiRootControllerTest extends AbstractRestIntegrationTest {
// create target first with "knownPrincipal" user and audit data // create target first with "knownPrincipal" user and audit data
final String knownTargetControllerId = "target1"; final String knownTargetControllerId = "target1";
final String knownCreatedBy = "knownPrincipal"; final String knownCreatedBy = "knownPrincipal";
targetManagement.createTarget(entityFactory.generateTarget(knownTargetControllerId)); testdataFactory.createTarget(knownTargetControllerId);
final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownTargetControllerId); final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownTargetControllerId);
assertThat(findTargetByControllerID.getCreatedBy()).isEqualTo(knownCreatedBy); assertThat(findTargetByControllerID.getCreatedBy()).isEqualTo(knownCreatedBy);
assertThat(findTargetByControllerID.getCreatedAt()).isNotNull(); assertThat(findTargetByControllerID.getCreatedAt()).isNotNull();
@@ -186,7 +187,7 @@ public class DdiRootControllerTest extends AbstractRestIntegrationTest {
final Target target = targetManagement.findTargetByControllerID("4711"); final Target target = targetManagement.findTargetByControllerID("4711");
final DistributionSet ds = testdataFactory.createDistributionSet(""); 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 Action updateAction = deploymentManagement.findActiveActionsByTarget(target).get(0);
final String etagWithFirstUpdate = mvc final String etagWithFirstUpdate = mvc
@@ -219,7 +220,7 @@ public class DdiRootControllerTest extends AbstractRestIntegrationTest {
// Now another deployment // Now another deployment
final DistributionSet ds2 = testdataFactory.createDistributionSet("2"); 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); final Action updateAction2 = deploymentManagement.findActiveActionsByTarget(target).get(0);
@@ -240,8 +241,7 @@ public class DdiRootControllerTest extends AbstractRestIntegrationTest {
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1), @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 1) }) @Expect(type = TargetUpdatedEvent.class, count = 1) })
public void rootRsPrecommissioned() throws Exception { public void rootRsPrecommissioned() throws Exception {
final Target target = entityFactory.generateTarget("4711"); final Target target = testdataFactory.createTarget("4711");
targetManagement.createTarget(target);
assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getUpdateStatus()) assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.UNKNOWN); .isEqualTo(TargetUpdateStatus.UNKNOWN);
@@ -296,15 +296,16 @@ public class DdiRootControllerTest extends AbstractRestIntegrationTest {
@Test @Test
@Description("Controller trys to finish an update process after it has been finished by an error action status.") @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 { public void tryToFinishAnUpdateProcessAfterItHasBeenFinished() throws Exception {
// mock
final Target target = entityFactory.generateTarget("911");
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
Target savedTarget = targetManagement.createTarget(target); Target savedTarget = testdataFactory.createTarget("911");
final List<Target> toAssign = new ArrayList<>(); savedTarget = assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getAssignedEntity().iterator()
toAssign.add(savedTarget); .next();
savedTarget = deploymentManagement.assignDistributionSet(ds, toAssign).getAssignedEntity().iterator().next();
final Action savedAction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0); final Action savedAction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0);
mvc.perform(post("/{tenant}/controller/v1/911/deploymentBase/" + savedAction.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/911/deploymentBase/" + savedAction.getId() + "/feedback",
tenantAware.getCurrentTenant()) tenantAware.getCurrentTenant())

View File

@@ -13,7 +13,6 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action;
@@ -27,6 +26,7 @@ import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.MvcResult;
import com.google.common.collect.Lists;
import com.google.common.net.HttpHeaders; import com.google.common.net.HttpHeaders;
import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Description;
@@ -147,11 +147,10 @@ public class DosFilterTest extends AbstractRestIntegrationTest {
private Long prepareDeploymentBase() { private Long prepareDeploymentBase() {
final DistributionSet ds = testdataFactory.createDistributionSet("test"); final DistributionSet ds = testdataFactory.createDistributionSet("test");
final Target target = targetManagement.createTarget(entityFactory.generateTarget("4711")); final Target target = testdataFactory.createTarget("4711");
final List<Target> toAssign = new ArrayList<>(); final List<Target> toAssign = Lists.newArrayList(target);
toAssign.add(target);
final Iterable<Target> saved = deploymentManagement.assignDistributionSet(ds, toAssign).getAssignedEntity(); final Iterable<Target> saved = assignDistributionSet(ds, toAssign).getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(target)).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(target)).hasSize(1);
final Action uaction = deploymentManagement.findActiveActionsByTarget(target).get(0); final Action uaction = deploymentManagement.findActiveActionsByTarget(target).get(0);

View File

@@ -7,6 +7,7 @@
# http://www.eclipse.org/legal/epl-v10.html # http://www.eclipse.org/legal/epl-v10.html
# #
#logging.level.org.eclipse.hawkbit.rest.util.MockMvcResultPrinter=DEBUG
logging.level.=INFO logging.level.=INFO
logging.level.org.eclipse.persistence=ERROR logging.level.org.eclipse.persistence=ERROR

View File

@@ -11,6 +11,7 @@ package org.eclipse.hawkbit.amqp;
import java.net.URI; import java.net.URI;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Collections; import java.util.Collections;
import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
@@ -25,11 +26,11 @@ import org.eclipse.hawkbit.im.authentication.TenantAwareAuthenticationDetails;
import org.eclipse.hawkbit.repository.ControllerManagement; import org.eclipse.hawkbit.repository.ControllerManagement;
import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.RepositoryConstants; 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.TenantNotExistException;
import org.eclipse.hawkbit.repository.exception.TooManyStatusEntriesException; import org.eclipse.hawkbit.repository.exception.TooManyStatusEntriesException;
import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status; 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.repository.model.Target;
import org.eclipse.hawkbit.util.IpUtil; import org.eclipse.hawkbit.util.IpUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
@@ -224,42 +225,66 @@ public class AmqpMessageHandlerService extends BaseAmqpService {
final ActionUpdateStatus actionUpdateStatus = convertMessage(message, ActionUpdateStatus.class); final ActionUpdateStatus actionUpdateStatus = convertMessage(message, ActionUpdateStatus.class);
final Action action = checkActionExist(message, actionUpdateStatus); final Action action = checkActionExist(message, actionUpdateStatus);
final ActionStatus actionStatus = createActionStatus(message, actionUpdateStatus, action); final List<String> messages = actionUpdateStatus.getMessage();
if (ArrayUtils.isNotEmpty(message.getMessageProperties().getCorrelationId())) {
messages.add(RepositoryConstants.SERVER_MESSAGE_PREFIX + "DMF message correlation-id "
+ convertCorrelationId(message));
}
updateLastPollTime(action.getTarget()); 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()) { switch (actionUpdateStatus.getActionStatus()) {
case DOWNLOAD: case DOWNLOAD:
actionStatus.setStatus(Status.DOWNLOAD); status = Status.DOWNLOAD;
break; break;
case RETRIEVED: case RETRIEVED:
actionStatus.setStatus(Status.RETRIEVED); status = Status.RETRIEVED;
break; break;
case RUNNING: case RUNNING:
actionStatus.setStatus(Status.RUNNING); status = Status.RUNNING;
break; break;
case CANCELED: case CANCELED:
actionStatus.setStatus(Status.CANCELED); status = Status.CANCELED;
break; break;
case FINISHED: case FINISHED:
actionStatus.setStatus(Status.FINISHED); status = Status.FINISHED;
break; break;
case ERROR: case ERROR:
actionStatus.setStatus(Status.ERROR); status = Status.ERROR;
break; break;
case WARNING: case WARNING:
actionStatus.setStatus(Status.WARNING); status = Status.WARNING;
break; break;
case CANCEL_REJECTED: case CANCEL_REJECTED:
handleCancelRejected(message, action, actionStatus); status = hanldeCancelRejectedState(message, action);
break; break;
default: default:
logAndThrowMessageError(message, "Status for action does not exisit."); logAndThrowMessageError(message, "Status for action does not exisit.");
} }
final Action addUpdateActionStatus = getUpdateActionStatus(actionStatus); return status;
}
if (!addUpdateActionStatus.isActive()) { private Status hanldeCancelRejectedState(final Message message, final Action action) {
lookIfUpdateAvailable(action.getTarget()); 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 @@ public class AmqpMessageHandlerService extends BaseAmqpService {
controllerManagement.updateTargetStatus(target.getTargetInfo(), null, System.currentTimeMillis(), null); 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) { private static String convertCorrelationId(final Message message) {
return new String(message.getMessageProperties().getCorrelationId(), StandardCharsets.UTF_8); return new String(message.getMessageProperties().getCorrelationId(), StandardCharsets.UTF_8);
} }
private Action getUpdateActionStatus(final ActionStatus actionStatus) { private Action getUpdateActionStatus(final Status status, final ActionStatusCreate actionStatus) {
if (actionStatus.getStatus().equals(Status.CANCELED)) { if (Status.CANCELED.equals(status)) {
return controllerManagement.addCancelActionStatus(actionStatus); return controllerManagement.addCancelActionStatus(actionStatus);
} }
return controllerManagement.addUpdateActionStatus(actionStatus); return controllerManagement.addUpdateActionStatus(actionStatus);
@@ -310,18 +320,4 @@ public class AmqpMessageHandlerService extends BaseAmqpService {
} }
return action; 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());
}
}
} }

View File

@@ -123,8 +123,7 @@ public class AmqpControllerAuthenticationTest {
final DdiSecurityProperties secruityProperties = mock(DdiSecurityProperties.class); final DdiSecurityProperties secruityProperties = mock(DdiSecurityProperties.class);
final Rp rp = mock(Rp.class); final Rp rp = mock(Rp.class);
final org.eclipse.hawkbit.security.DdiSecurityProperties.Authentication ddiAuthentication = mock( final DdiSecurityProperties.Authentication ddiAuthentication = mock(DdiSecurityProperties.Authentication.class);
org.eclipse.hawkbit.security.DdiSecurityProperties.Authentication.class);
final Anonymous anonymous = mock(Anonymous.class); final Anonymous anonymous = mock(Anonymous.class);
when(secruityProperties.getRp()).thenReturn(rp); when(secruityProperties.getRp()).thenReturn(rp);
when(rp.getSslIssuerHashHeader()).thenReturn("X-Ssl-Issuer-Hash-%d"); when(rp.getSslIssuerHashHeader()).thenReturn("X-Ssl-Issuer-Hash-%d");

View File

@@ -34,9 +34,7 @@ import org.eclipse.hawkbit.repository.SystemManagement;
import org.eclipse.hawkbit.repository.event.remote.TargetAssignDistributionSetEvent; 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.CancelTargetAssignmentEvent;
import org.eclipse.hawkbit.repository.jpa.ActionRepository; 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;
import org.eclipse.hawkbit.repository.model.Action.ActionType;
import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModule;
@@ -93,9 +91,8 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest {
@Override @Override
public void before() throws Exception { public void before() throws Exception {
super.before(); super.before();
final Target generateTarget = entityFactory.generateTarget(CONTROLLER_ID, TEST_TOKEN); testTarget = targetManagement.createTarget(entityFactory.target().create().controllerId(CONTROLLER_ID)
generateTarget.getTargetInfo().setAddress(AMQP_URI.toString()); .securityToken(TEST_TOKEN).address(AMQP_URI.toString()));
testTarget = targetManagement.createTarget(generateTarget);
this.rabbitTemplate = Mockito.mock(RabbitTemplate.class); this.rabbitTemplate = Mockito.mock(RabbitTemplate.class);
when(rabbitTemplate.getMessageConverter()).thenReturn(new Jackson2JsonMessageConverter()); when(rabbitTemplate.getMessageConverter()).thenReturn(new Jackson2JsonMessageConverter());
@@ -121,15 +118,13 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest {
@Test @Test
@Description("Verfies that download and install event with no software modul works") @Description("Verfies that download and install event with no software modul works")
public void testSendDownloadRequesWithEmptySoftwareModules() { public void testSendDownloadRequesWithEmptySoftwareModules() {
final Action action = createAction(
testdataFactory.createDistributionSetWithNoSoftwareModules(UUID.randomUUID().toString(), "1.0"));
final TargetAssignDistributionSetEvent targetAssignDistributionSetEvent = new TargetAssignDistributionSetEvent( final TargetAssignDistributionSetEvent targetAssignDistributionSetEvent = new TargetAssignDistributionSetEvent(
action, serviceMatcher.getServiceId()); "DEFAULT", 1L, 1L, CONTROLLER_ID, serviceMatcher.getServiceId());
amqpMessageDispatcherService.targetAssignDistributionSet(targetAssignDistributionSetEvent); amqpMessageDispatcherService.targetAssignDistributionSet(targetAssignDistributionSetEvent);
final Message sendMessage = getCaptureAdressEvent(targetAssignDistributionSetEvent); final Message sendMessage = getCaptureAdressEvent(targetAssignDistributionSetEvent);
final DownloadAndUpdateRequest downloadAndUpdateRequest = assertDownloadAndInstallMessage(sendMessage, action); final DownloadAndUpdateRequest downloadAndUpdateRequest = assertDownloadAndInstallMessage(sendMessage, 1L);
assertThat(downloadAndUpdateRequest.getTargetSecurityToken()).isEqualTo(TEST_TOKEN); assertThat(downloadAndUpdateRequest.getTargetSecurityToken()).isEqualTo(TEST_TOKEN);
assertTrue("No softwaremmodule should be contained in the request", assertTrue("No softwaremmodule should be contained in the request",
downloadAndUpdateRequest.getSoftwareModules().isEmpty()); downloadAndUpdateRequest.getSoftwareModules().isEmpty());
@@ -142,14 +137,8 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest {
return sendMessage; return sendMessage;
} }
private JpaAction createAction(final DistributionSet testDs) { private Action createAction(final DistributionSet testDs) {
final Action action = entityFactory.generateAction(); return deploymentManagement.findAction(assignDistributionSet(testDs, testTarget).getActions().get(0));
final JpaAction jpaAction = (JpaAction) action;
action.setDistributionSet(testDs);
action.setTarget(testTarget);
jpaAction.setActionType(ActionType.FORCED);
return actionRepository.save(jpaAction);
} }
@Test @Test
@@ -163,7 +152,8 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest {
action, serviceMatcher.getServiceId()); action, serviceMatcher.getServiceId());
amqpMessageDispatcherService.targetAssignDistributionSet(targetAssignDistributionSetEvent); amqpMessageDispatcherService.targetAssignDistributionSet(targetAssignDistributionSetEvent);
final Message sendMessage = getCaptureAdressEvent(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(createDistributionSet.getModules()).hasSameSizeAs(downloadAndUpdateRequest.getSoftwareModules());
assertThat(downloadAndUpdateRequest.getTargetSecurityToken()).isEqualTo(TEST_TOKEN); assertThat(downloadAndUpdateRequest.getTargetSecurityToken()).isEqualTo(TEST_TOKEN);
for (final org.eclipse.hawkbit.dmf.json.model.SoftwareModule softwareModule : downloadAndUpdateRequest for (final org.eclipse.hawkbit.dmf.json.model.SoftwareModule softwareModule : downloadAndUpdateRequest
@@ -187,13 +177,14 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest {
@Test @Test
@Description("Verfies that download and install event with software moduls and artifacts works") @Description("Verfies that download and install event with software moduls and artifacts works")
public void testSendDownloadRequest() { public void testSendDownloadRequest() {
final DistributionSet dsA = testdataFactory.createDistributionSet(UUID.randomUUID().toString()); DistributionSet dsA = testdataFactory.createDistributionSet(UUID.randomUUID().toString());
final SoftwareModule module = dsA.getModules().iterator().next(); SoftwareModule module = dsA.getModules().iterator().next();
final List<DbArtifact> receivedList = new ArrayList<>(); final List<DbArtifact> receivedList = new ArrayList<>();
for (final Artifact artifact : testdataFactory.createArtifacts(module.getId())) { for (final Artifact artifact : testdataFactory.createArtifacts(module.getId())) {
module.addArtifact(artifact);
receivedList.add(new DbArtifact()); receivedList.add(new DbArtifact());
} }
module = softwareManagement.findSoftwareModuleById(module.getId());
dsA = distributionSetManagement.findDistributionSetById(dsA.getId());
final Action action = createAction(dsA); final Action action = createAction(dsA);
@@ -203,7 +194,8 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest {
action, serviceMatcher.getServiceId()); action, serviceMatcher.getServiceId());
amqpMessageDispatcherService.targetAssignDistributionSet(targetAssignDistributionSetEvent); amqpMessageDispatcherService.targetAssignDistributionSet(targetAssignDistributionSetEvent);
final Message sendMessage = getCaptureAdressEvent(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, assertEquals("DownloadAndUpdateRequest event should contains 3 software modules", 3,
downloadAndUpdateRequest.getSoftwareModules().size()); downloadAndUpdateRequest.getSoftwareModules().size());
@@ -251,11 +243,11 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest {
} }
private DownloadAndUpdateRequest assertDownloadAndInstallMessage(final Message sendMessage, final Action action) { private DownloadAndUpdateRequest assertDownloadAndInstallMessage(final Message sendMessage, final Long action) {
assertEventMessage(sendMessage); assertEventMessage(sendMessage);
final DownloadAndUpdateRequest downloadAndUpdateRequest = convertMessage(sendMessage, final DownloadAndUpdateRequest downloadAndUpdateRequest = convertMessage(sendMessage,
DownloadAndUpdateRequest.class); 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, assertEquals("The topic of the event shuold contain DOWNLOAD_AND_INSTALL", EventTopic.DOWNLOAD_AND_INSTALL,
sendMessage.getMessageProperties().getHeaders().get(MessageHeaderKey.TOPIC)); sendMessage.getMessageProperties().getHeaders().get(MessageHeaderKey.TOPIC));
assertEquals("Security token of target", downloadAndUpdateRequest.getTargetSecurityToken(), TEST_TOKEN); assertEquals("Security token of target", downloadAndUpdateRequest.getTargetSecurityToken(), TEST_TOKEN);

View File

@@ -40,16 +40,16 @@ import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken.FileResource;
import org.eclipse.hawkbit.repository.ArtifactManagement; import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.ControllerManagement; import org.eclipse.hawkbit.repository.ControllerManagement;
import org.eclipse.hawkbit.repository.EntityFactory; 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.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.jpa.model.helper.SecurityTokenGeneratorHolder;
import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetInfo; import org.eclipse.hawkbit.repository.model.TargetInfo;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.security.SecurityTokenGenerator; import org.eclipse.hawkbit.security.SecurityTokenGenerator;
@@ -359,7 +359,11 @@ public class AmqpMessageHandlerServiceTest {
final Action action = createActionWithTarget(22L, Status.FINISHED); final Action action = createActionWithTarget(22L, Status.FINISHED);
when(controllerManagementMock.findActionWithDetails(Matchers.any())).thenReturn(action); when(controllerManagementMock.findActionWithDetails(Matchers.any())).thenReturn(action);
when(controllerManagementMock.addUpdateActionStatus(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 // for the test the same action can be used
when(controllerManagementMock.findOldestActiveActionByTarget(Matchers.any())).thenReturn(Optional.of(action)); when(controllerManagementMock.findOldestActiveActionByTarget(Matchers.any())).thenReturn(Optional.of(action));
@@ -424,8 +428,8 @@ public class AmqpMessageHandlerServiceTest {
initalizeSecurityTokenGenerator(); initalizeSecurityTokenGenerator();
// Mock // Mock
final JpaAction actionMock = mock(JpaAction.class); final Action actionMock = mock(Action.class);
final JpaTarget targetMock = mock(JpaTarget.class); final Target targetMock = mock(Target.class);
final TargetInfo targetInfoMock = mock(TargetInfo.class); final TargetInfo targetInfoMock = mock(TargetInfo.class);
final DistributionSet distributionSetMock = mock(DistributionSet.class); final DistributionSet distributionSetMock = mock(DistributionSet.class);

View File

@@ -62,7 +62,7 @@ public class ActionUpdateStatus {
return Collections.emptyList(); return Collections.emptyList();
} }
return Collections.unmodifiableList(message); return message;
} }
public boolean addMessage(final String message) { public boolean addMessage(final String message) {

View File

@@ -41,7 +41,7 @@ public class MgmtDistributionSetRequestBodyPost extends MgmtDistributionSetReque
private List<MgmtSoftwareModuleAssigment> modules; private List<MgmtSoftwareModuleAssigment> modules;
@JsonProperty @JsonProperty
private boolean requiredMigrationStep; private Boolean requiredMigrationStep;
@JsonProperty @JsonProperty
private String type; private String type;
@@ -105,7 +105,7 @@ public class MgmtDistributionSetRequestBodyPost extends MgmtDistributionSetReque
/** /**
* @return the requiredMigrationStep * @return the requiredMigrationStep
*/ */
public boolean isRequiredMigrationStep() { public Boolean isRequiredMigrationStep() {
return requiredMigrationStep; return requiredMigrationStep;
} }
@@ -115,7 +115,7 @@ public class MgmtDistributionSetRequestBodyPost extends MgmtDistributionSetReque
* *
* @return updated body * @return updated body
*/ */
public MgmtDistributionSetRequestBodyPost setRequiredMigrationStep(final boolean requiredMigrationStep) { public MgmtDistributionSetRequestBodyPost setRequiredMigrationStep(final Boolean requiredMigrationStep) {
this.requiredMigrationStep = requiredMigrationStep; this.requiredMigrationStep = requiredMigrationStep;
return this; return this;

View File

@@ -18,14 +18,11 @@ import com.fasterxml.jackson.annotation.JsonProperty;
* Request Body for DistributionSetType POST. * Request Body for DistributionSetType POST.
* *
*/ */
public class MgmtDistributionSetTypeRequestBodyPost { public class MgmtDistributionSetTypeRequestBodyPost extends MgmtDistributionSetTypeRequestBodyPut {
@JsonProperty(required = true) @JsonProperty(required = true)
private String name; private String name;
@JsonProperty
private String description;
@JsonProperty @JsonProperty
private String key; private String key;
@@ -35,6 +32,18 @@ public class MgmtDistributionSetTypeRequestBodyPost {
@JsonProperty @JsonProperty
private List<MgmtSoftwareModuleTypeAssigment> optionalmodules; private List<MgmtSoftwareModuleTypeAssigment> 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 * @return the name
*/ */
@@ -53,24 +62,6 @@ public class MgmtDistributionSetTypeRequestBodyPost {
return this; 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 * @return the key
*/ */

View File

@@ -19,22 +19,25 @@ public class MgmtDistributionSetTypeRequestBodyPut {
@JsonProperty @JsonProperty
private String description; private String description;
/** @JsonProperty
* @return the description private String colour;
*/
public String getDescription() { public String getDescription() {
return description; return description;
} }
/**
* @param description
* the description to set
*
* @return updated body
*/
public MgmtDistributionSetTypeRequestBodyPut setDescription(final String description) { public MgmtDistributionSetTypeRequestBodyPut setDescription(final String description) {
this.description = description; this.description = description;
return this; return this;
} }
public String getColour() {
return colour;
}
public MgmtDistributionSetTypeRequestBodyPut setColour(final String colour) {
this.colour = colour;
return this;
}
} }

View File

@@ -14,20 +14,29 @@ import com.fasterxml.jackson.annotation.JsonProperty;
* Request Body for SoftwareModuleType POST. * Request Body for SoftwareModuleType POST.
* *
*/ */
public class MgmtSoftwareModuleTypeRequestBodyPost { public class MgmtSoftwareModuleTypeRequestBodyPost extends MgmtSoftwareModuleTypeRequestBodyPut {
@JsonProperty(required = true) @JsonProperty(required = true)
private String name; private String name;
@JsonProperty
private String description;
@JsonProperty @JsonProperty
private String key; private String key;
@JsonProperty @JsonProperty
private int maxAssignments; 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 * @return the name
*/ */
@@ -46,24 +55,6 @@ public class MgmtSoftwareModuleTypeRequestBodyPost {
return this; 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 * @return the key
*/ */

View File

@@ -19,22 +19,25 @@ public class MgmtSoftwareModuleTypeRequestBodyPut {
@JsonProperty @JsonProperty
private String description; private String description;
/** @JsonProperty
* @return the description private String colour;
*/
public String getDescription() { public String getDescription() {
return description; return description;
} }
/**
* @param description
* the description to set
*
* @return updated body
*/
public MgmtSoftwareModuleTypeRequestBodyPut setDescription(final String description) { public MgmtSoftwareModuleTypeRequestBodyPut setDescription(final String description) {
this.description = description; this.description = description;
return this; return this;
} }
public String getColour() {
return colour;
}
public MgmtSoftwareModuleTypeRequestBodyPut setColour(final String colour) {
this.colour = colour;
return this;
}
} }

View File

@@ -24,15 +24,12 @@ import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtTargetAssignmentR
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetRestApi; import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetRestApi;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTypeRestApi; import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTypeRestApi;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; 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.EntityFactory;
import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.builder.DistributionSetCreate;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetAssignmentResult; import org.eclipse.hawkbit.repository.model.DistributionSetAssignmentResult;
import org.eclipse.hawkbit.repository.model.DistributionSetMetadata; 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.SoftwareModule;
/** /**
* A mapper which maps repository model to RESTful model representation and * A mapper which maps repository model to RESTful model representation and
@@ -43,45 +40,17 @@ public final class MgmtDistributionSetMapper {
// Utility class // 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. * {@link MgmtDistributionSetRequestBodyPost}s to {@link DistributionSet}s.
* *
* @param sets * @param sets
* to convert * to convert
* @param softwareManagement
* to use for conversion
* @return converted list of {@link DistributionSet}s * @return converted list of {@link DistributionSet}s
*/ */
static List<DistributionSet> dsFromRequest(final Collection<MgmtDistributionSetRequestBodyPost> sets, static List<DistributionSetCreate> dsFromRequest(final Collection<MgmtDistributionSetRequestBodyPost> sets,
final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement,
final EntityFactory entityFactory) { final EntityFactory entityFactory) {
return sets.stream() return sets.stream().map(dsRest -> fromRequest(dsRest, entityFactory)).collect(Collectors.toList());
.map(dsRest -> fromRequest(dsRest, softwareManagement, distributionSetManagement, entityFactory))
.collect(Collectors.toList());
} }
/** /**
@@ -89,59 +58,42 @@ public final class MgmtDistributionSetMapper {
* *
* @param dsRest * @param dsRest
* to convert * to convert
* @param softwareManagement
* to use for conversion
* @return converted {@link DistributionSet} * @return converted {@link DistributionSet}
*/ */
static DistributionSet fromRequest(final MgmtDistributionSetRequestBodyPost dsRest, static DistributionSetCreate fromRequest(final MgmtDistributionSetRequestBodyPost dsRest,
final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement,
final EntityFactory entityFactory) { final EntityFactory entityFactory) {
final DistributionSet result = entityFactory.generateDistributionSet(); final List<Long> modules = new ArrayList<>();
result.setDescription(dsRest.getDescription());
result.setName(dsRest.getName());
result.setType(findDistributionSetTypeWithExceptionIfNotFound(dsRest.getType(), distributionSetManagement));
result.setRequiredMigrationStep(dsRest.isRequiredMigrationStep());
result.setVersion(dsRest.getVersion());
if (dsRest.getOs() != null) { if (dsRest.getOs() != null) {
result.addModule(findSoftwareModuleWithExceptionIfNotFound(dsRest.getOs().getId(), softwareManagement)); modules.add(dsRest.getOs().getId());
} }
if (dsRest.getApplication() != null) { if (dsRest.getApplication() != null) {
result.addModule( modules.add(dsRest.getApplication().getId());
findSoftwareModuleWithExceptionIfNotFound(dsRest.getApplication().getId(), softwareManagement));
} }
if (dsRest.getRuntime() != null) { if (dsRest.getRuntime() != null) {
result.addModule( modules.add(dsRest.getRuntime().getId());
findSoftwareModuleWithExceptionIfNotFound(dsRest.getRuntime().getId(), softwareManagement));
} }
if (dsRest.getModules() != null) { if (dsRest.getModules() != null) {
dsRest.getModules().forEach(module -> result dsRest.getModules().forEach(module -> modules.add(module.getId()));
.addModule(findSoftwareModuleWithExceptionIfNotFound(module.getId(), softwareManagement)));
} }
return result; return entityFactory.distributionSet().create().name(dsRest.getName()).version(dsRest.getVersion())
.description(dsRest.getDescription()).type(dsRest.getType()).modules(modules)
.requiredMigrationStep(dsRest.isRequiredMigrationStep());
} }
/** static List<MetaData> fromRequestDsMetadata(final List<MgmtMetadata> metadata, final EntityFactory entityFactory) {
* From {@link MgmtMetadata} to {@link DistributionSetMetadata}.
*
* @param ds
* @param metadata
* @return
*/
static List<DistributionSetMetadata> fromRequestDsMetadata(final DistributionSet ds,
final List<MgmtMetadata> metadata, final EntityFactory entityFactory) {
if (metadata == null) { if (metadata == null) {
return Collections.emptyList(); return Collections.emptyList();
} }
return metadata.stream().map(metadataRest -> entityFactory.generateDistributionSetMetadata(ds, return metadata.stream()
metadataRest.getKey(), metadataRest.getValue())).collect(Collectors.toList()); .map(metadataRest -> entityFactory.generateMetadata(metadataRest.getKey(), metadataRest.getValue()))
.collect(Collectors.toList());
} }
/** /**

View File

@@ -9,9 +9,7 @@
package org.eclipse.hawkbit.mgmt.rest.resource; package org.eclipse.hawkbit.mgmt.rest.resource;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata; import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata;
@@ -102,10 +100,9 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting); final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Page<DistributionSet> findDsPage; final Page<DistributionSet> findDsPage;
if (rsqlParam != null) { if (rsqlParam != null) {
findDsPage = this.distributionSetManagement.findDistributionSetsAll(rsqlParam, pageable, false); findDsPage = distributionSetManagement.findDistributionSetsAll(rsqlParam, pageable, false);
} else { } else {
findDsPage = this.distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageable, false, findDsPage = distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageable, false, null);
null);
} }
final List<MgmtDistributionSet> rest = MgmtDistributionSetMapper.toResponseFromDsList(findDsPage.getContent()); final List<MgmtDistributionSet> rest = MgmtDistributionSetMapper.toResponseFromDsList(findDsPage.getContent());
@@ -127,12 +124,11 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
LOG.debug("creating {} distribution sets", sets.size()); LOG.debug("creating {} distribution sets", sets.size());
// set default Ds type if ds type is null // set default Ds type if ds type is null
final String defaultDsKey = systemSecurityContext 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)); sets.stream().filter(ds -> ds.getType() == null).forEach(ds -> ds.setType(defaultDsKey));
final Collection<DistributionSet> createdDSets = this.distributionSetManagement final Collection<DistributionSet> createdDSets = distributionSetManagement
.createDistributionSets(MgmtDistributionSetMapper.dsFromRequest(sets, this.softwareManagement, .createDistributionSets(MgmtDistributionSetMapper.dsFromRequest(sets, entityFactory));
this.distributionSetManagement, entityFactory));
LOG.debug("{} distribution sets created, return status {}", sets.size(), HttpStatus.CREATED); LOG.debug("{} distribution sets created, return status {}", sets.size(), HttpStatus.CREATED);
return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDistributionSets(createdDSets), return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDistributionSets(createdDSets),
@@ -143,7 +139,7 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
public ResponseEntity<Void> deleteDistributionSet(@PathVariable("distributionSetId") final Long distributionSetId) { public ResponseEntity<Void> deleteDistributionSet(@PathVariable("distributionSetId") final Long distributionSetId) {
final DistributionSet set = findDistributionSetWithExceptionIfNotFound(distributionSetId); final DistributionSet set = findDistributionSetWithExceptionIfNotFound(distributionSetId);
this.distributionSetManagement.deleteDistributionSet(set); distributionSetManagement.deleteDistributionSet(set);
return new ResponseEntity<>(HttpStatus.OK); return new ResponseEntity<>(HttpStatus.OK);
} }
@@ -152,21 +148,11 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
public ResponseEntity<MgmtDistributionSet> updateDistributionSet( public ResponseEntity<MgmtDistributionSet> updateDistributionSet(
@PathVariable("distributionSetId") final Long distributionSetId, @PathVariable("distributionSetId") final Long distributionSetId,
@RequestBody final MgmtDistributionSetRequestBodyPut toUpdate) { @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<>( 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); HttpStatus.OK);
} }
@@ -224,20 +210,18 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
pageable); pageable);
} }
return new ResponseEntity<>( return new ResponseEntity<>(new PagedList<>(MgmtTargetMapper.toResponse(targetsInstalledDS.getContent()),
new PagedList<MgmtTarget>(MgmtTargetMapper.toResponse(targetsInstalledDS.getContent()), targetsInstalledDS.getTotalElements()), HttpStatus.OK);
targetsInstalledDS.getTotalElements()),
HttpStatus.OK);
} }
@Override @Override
public ResponseEntity<PagedList<MgmtTargetFilterQuery>> getAutoAssignTargetFilterQueries( public ResponseEntity<PagedList<MgmtTargetFilterQuery>> getAutoAssignTargetFilterQueries(
@PathVariable("distributionSetId") Long distributionSetId, @PathVariable("distributionSetId") final Long distributionSetId,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) int pagingOffsetParam, @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) int pagingLimitParam, @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) String sortParam, @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) String rsqlParam) { @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) {
DistributionSet distributionSet = findDistributionSetWithExceptionIfNotFound(distributionSetId); final DistributionSet distributionSet = findDistributionSetWithExceptionIfNotFound(distributionSetId);
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam); final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
@@ -294,11 +278,11 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
final Page<DistributionSetMetadata> metaDataPage; final Page<DistributionSetMetadata> metaDataPage;
if (rsqlParam != null) { if (rsqlParam != null) {
metaDataPage = this.distributionSetManagement metaDataPage = distributionSetManagement.findDistributionSetMetadataByDistributionSetId(distributionSetId,
.findDistributionSetMetadataByDistributionSetId(distributionSetId, rsqlParam, pageable); rsqlParam, pageable);
} else { } else {
metaDataPage = this.distributionSetManagement metaDataPage = distributionSetManagement.findDistributionSetMetadataByDistributionSetId(distributionSetId,
.findDistributionSetMetadataByDistributionSetId(distributionSetId, pageable); pageable);
} }
return new ResponseEntity<>( return new ResponseEntity<>(
@@ -314,8 +298,8 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
@PathVariable("metadataKey") final String metadataKey) { @PathVariable("metadataKey") final String metadataKey) {
// check if distribution set exists otherwise throw exception // check if distribution set exists otherwise throw exception
// immediately // immediately
final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId); final DistributionSetMetadata findOne = distributionSetManagement.findDistributionSetMetadata(distributionSetId,
final DistributionSetMetadata findOne = this.distributionSetManagement.findOne(ds, metadataKey); metadataKey);
return ResponseEntity.<MgmtMetadata> ok(MgmtDistributionSetMapper.toResponseDsMetadata(findOne)); return ResponseEntity.<MgmtMetadata> ok(MgmtDistributionSetMapper.toResponseDsMetadata(findOne));
} }
@@ -324,9 +308,8 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
@PathVariable("metadataKey") final String metadataKey, @RequestBody final MgmtMetadata metadata) { @PathVariable("metadataKey") final String metadataKey, @RequestBody final MgmtMetadata metadata) {
// check if distribution set exists otherwise throw exception // check if distribution set exists otherwise throw exception
// immediately // immediately
final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId); final DistributionSetMetadata updated = distributionSetManagement.updateDistributionSetMetadata(
final DistributionSetMetadata updated = this.distributionSetManagement.updateDistributionSetMetadata( distributionSetId, entityFactory.generateMetadata(metadataKey, metadata.getValue()));
entityFactory.generateDistributionSetMetadata(ds, metadataKey, metadata.getValue()));
return ResponseEntity.ok(MgmtDistributionSetMapper.toResponseDsMetadata(updated)); return ResponseEntity.ok(MgmtDistributionSetMapper.toResponseDsMetadata(updated));
} }
@@ -335,8 +318,7 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
@PathVariable("metadataKey") final String metadataKey) { @PathVariable("metadataKey") final String metadataKey) {
// check if distribution set exists otherwise throw exception // check if distribution set exists otherwise throw exception
// immediately // immediately
final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId); distributionSetManagement.deleteDistributionSetMetadata(distributionSetId, metadataKey);
this.distributionSetManagement.deleteDistributionSetMetadata(ds, metadataKey);
return ResponseEntity.ok().build(); return ResponseEntity.ok().build();
} }
@@ -346,10 +328,8 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
@RequestBody final List<MgmtMetadata> metadataRest) { @RequestBody final List<MgmtMetadata> metadataRest) {
// check if distribution set exists otherwise throw exception // check if distribution set exists otherwise throw exception
// immediately // immediately
final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId); final List<DistributionSetMetadata> created = distributionSetManagement.createDistributionSetMetadata(
distributionSetId, MgmtDistributionSetMapper.fromRequestDsMetadata(metadataRest, entityFactory));
final List<DistributionSetMetadata> created = this.distributionSetManagement.createDistributionSetMetadata(
MgmtDistributionSetMapper.fromRequestDsMetadata(ds, metadataRest, entityFactory));
return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDsMetadata(created), HttpStatus.CREATED); return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDsMetadata(created), HttpStatus.CREATED);
} }
@@ -357,21 +337,9 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
@Override @Override
public ResponseEntity<Void> assignSoftwareModules(@PathVariable("distributionSetId") final Long distributionSetId, public ResponseEntity<Void> assignSoftwareModules(@PathVariable("distributionSetId") final Long distributionSetId,
@RequestBody final List<MgmtSoftwareModuleAssigment> softwareModuleIDs) { @RequestBody final List<MgmtSoftwareModuleAssigment> softwareModuleIDs) {
// check if distribution set exists otherwise throw exception
// immediately
final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId);
final Set<SoftwareModule> softwareModuleToBeAssigned = new HashSet<>(); distributionSetManagement.assignSoftwareModules(distributionSetId,
for (final MgmtSoftwareModuleAssigment sm : softwareModuleIDs) { softwareModuleIDs.stream().map(module -> module.getId()).collect(Collectors.toList()));
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);
return new ResponseEntity<>(HttpStatus.OK); return new ResponseEntity<>(HttpStatus.OK);
} }
@@ -379,11 +347,7 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
public ResponseEntity<Void> deleteAssignSoftwareModules( public ResponseEntity<Void> deleteAssignSoftwareModules(
@PathVariable("distributionSetId") final Long distributionSetId, @PathVariable("distributionSetId") final Long distributionSetId,
@PathVariable("softwareModuleId") final Long softwareModuleId) { @PathVariable("softwareModuleId") final Long softwareModuleId) {
// check if distribution set and software module exist otherwise throw distributionSetManagement.unassignSoftwareModule(distributionSetId, softwareModuleId);
// exception immediately
final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId);
final SoftwareModule sm = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId);
this.distributionSetManagement.unassignSoftwareModule(ds, sm);
return ResponseEntity.ok().build(); return ResponseEntity.ok().build();
} }
@@ -400,26 +364,18 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeSoftwareModuleSortParam(sortParam); final Sort sorting = PagingUtility.sanitizeSoftwareModuleSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting); final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Page<SoftwareModule> softwaremodules = this.softwareManagement.findSoftwareModuleByAssignedTo(pageable, final Page<SoftwareModule> softwaremodules = softwareManagement.findSoftwareModuleByAssignedTo(pageable,
foundDs); foundDs);
return new ResponseEntity<>(new PagedList<>(MgmtSoftwareModuleMapper.toResponse(softwaremodules.getContent()), return new ResponseEntity<>(new PagedList<>(MgmtSoftwareModuleMapper.toResponse(softwaremodules.getContent()),
softwaremodules.getTotalElements()), HttpStatus.OK); softwaremodules.getTotalElements()), HttpStatus.OK);
} }
private DistributionSet findDistributionSetWithExceptionIfNotFound(final Long distributionSetId) { private DistributionSet findDistributionSetWithExceptionIfNotFound(final Long distributionSetId) {
final DistributionSet set = this.distributionSetManagement.findDistributionSetById(distributionSetId); final DistributionSet set = distributionSetManagement.findDistributionSetById(distributionSetId);
if (set == null) { if (set == null) {
throw new EntityNotFoundException("DistributionSet with Id {" + distributionSetId + "} does not exist"); throw new EntityNotFoundException("DistributionSet with Id {" + distributionSetId + "} does not exist");
} }
return set; 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;
}
} }

View File

@@ -101,7 +101,7 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
LOG.debug("creating {} ds tags", tags.size()); LOG.debug("creating {} ds tags", tags.size());
final List<DistributionSetTag> createdTags = this.tagManagement final List<DistributionSetTag> createdTags = this.tagManagement
.createDistributionSetTags(MgmtTagMapper.mapDistributionSetTagFromRequest(entityFactory, tags)); .createDistributionSetTags(MgmtTagMapper.mapTagFromRequest(entityFactory, tags));
return new ResponseEntity<>(MgmtTagMapper.toResponseDistributionSetTag(createdTags), HttpStatus.CREATED); return new ResponseEntity<>(MgmtTagMapper.toResponseDistributionSetTag(createdTags), HttpStatus.CREATED);
} }
@@ -110,16 +110,12 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
public ResponseEntity<MgmtTag> updateDistributionSetTag( public ResponseEntity<MgmtTag> updateDistributionSetTag(
@PathVariable("distributionsetTagId") final Long distributionsetTagId, @PathVariable("distributionsetTagId") final Long distributionsetTagId,
@RequestBody final MgmtTagRequestBodyPut restDSTagRest) { @RequestBody final MgmtTagRequestBodyPut restDSTagRest) {
LOG.debug("update {} ds tag", restDSTagRest);
final DistributionSetTag distributionSetTag = findDistributionTagById(distributionsetTagId); return new ResponseEntity<>(
MgmtTagMapper.updateTag(restDSTagRest, distributionSetTag); MgmtTagMapper.toResponse(tagManagement.updateDistributionSetTag(
final DistributionSetTag updateDistributionSetTag = this.tagManagement entityFactory.tag().update(distributionsetTagId).name(restDSTagRest.getName())
.updateDistributionSetTag(distributionSetTag); .description(restDSTagRest.getDescription()).colour(restDSTagRest.getColour()))),
HttpStatus.OK);
LOG.debug("ds tag updated");
return new ResponseEntity<>(MgmtTagMapper.toResponse(updateDistributionSetTag), HttpStatus.OK);
} }
@Override @Override
@@ -213,7 +209,7 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
return tag; return tag;
} }
private List<Long> findDistributionSetIds( private static List<Long> findDistributionSetIds(
final List<MgmtAssignedDistributionSetRequestBody> assignedDistributionSetRequestBodies) { final List<MgmtAssignedDistributionSetRequestBody> assignedDistributionSetRequestBodies) {
return assignedDistributionSetRequestBodies.stream().map(request -> request.getDistributionSetId()) return assignedDistributionSetRequestBodies.stream().map(request -> request.getDistributionSetId())
.collect(Collectors.toList()); .collect(Collectors.toList());

View File

@@ -14,18 +14,17 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetType; import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetType;
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRequestBodyPost; import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.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.MgmtDistributionSetTypeRestApi;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.builder.DistributionSetTypeCreate;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.DistributionSetType; 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 * A mapper which maps repository model to RESTful model representation and
@@ -39,57 +38,32 @@ final class MgmtDistributionSetTypeMapper {
} }
static List<DistributionSetType> smFromRequest(final EntityFactory entityFactory, static List<DistributionSetTypeCreate> smFromRequest(final EntityFactory entityFactory,
final SoftwareManagement softwareManagement,
final Collection<MgmtDistributionSetTypeRequestBodyPost> smTypesRest) { final Collection<MgmtDistributionSetTypeRequestBodyPost> smTypesRest) {
if (smTypesRest == null) { if (smTypesRest == null) {
return Collections.emptyList(); return Collections.emptyList();
} }
return smTypesRest.stream().map(smRest -> fromRequest(entityFactory, softwareManagement, smRest)) return smTypesRest.stream().map(smRest -> fromRequest(entityFactory, smRest)).collect(Collectors.toList());
.collect(Collectors.toList());
} }
static DistributionSetType fromRequest(final EntityFactory entityFactory, static DistributionSetTypeCreate fromRequest(final EntityFactory entityFactory,
final SoftwareManagement softwareManagement, final MgmtDistributionSetTypeRequestBodyPost smsRest) { final MgmtDistributionSetTypeRequestBodyPost smsRest) {
return entityFactory.distributionSetType().create().key(smsRest.getKey()).name(smsRest.getName())
final DistributionSetType result = entityFactory.generateDistributionSetType(smsRest.getKey(), .description(smsRest.getDescription()).colour(smsRest.getColour())
smsRest.getName(), smsRest.getDescription()); .mandatory(getMandatoryModules(smsRest)).optional(getOptionalmodules(smsRest));
addMandatoryModules(softwareManagement, smsRest, result);
addOptionalModules(softwareManagement, smsRest, result);
return result;
} }
private static void addOptionalModules(final SoftwareManagement softwareManagement, private static Collection<Long> getMandatoryModules(final MgmtDistributionSetTypeRequestBodyPost smsRest) {
final MgmtDistributionSetTypeRequestBodyPost smsRest, final DistributionSetType result) { return Optional.ofNullable(smsRest.getMandatorymodules()).map(
if (!CollectionUtils.isEmpty(smsRest.getOptionalmodules())) { modules -> modules.stream().map(MgmtSoftwareModuleTypeAssigment::getId).collect(Collectors.toList()))
smsRest.getOptionalmodules().stream().map(opt -> { .orElse(Collections.emptyList());
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 void addMandatoryModules(final SoftwareManagement softwareManagement, private static Collection<Long> getOptionalmodules(final MgmtDistributionSetTypeRequestBodyPost smsRest) {
final MgmtDistributionSetTypeRequestBodyPost smsRest, final DistributionSetType result) { return Optional.ofNullable(smsRest.getOptionalmodules()).map(
if (!CollectionUtils.isEmpty(smsRest.getMandatorymodules())) { modules -> modules.stream().map(MgmtSoftwareModuleTypeAssigment::getId).collect(Collectors.toList()))
smsRest.getMandatorymodules().stream().map(mand -> { .orElse(Collections.emptyList());
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);
}
} }
static List<MgmtDistributionSetType> toTypesResponse(final List<DistributionSetType> types) { static List<MgmtDistributionSetType> toTypesResponse(final List<DistributionSetType> types) {

View File

@@ -44,6 +44,8 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.google.common.collect.Lists;
/** /**
* REST Resource handling for {@link SoftwareModule} and related * REST Resource handling for {@link SoftwareModule} and related
* {@link Artifact} CRUD operations. * {@link Artifact} CRUD operations.
@@ -110,17 +112,9 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @PathVariable("distributionSetTypeId") final Long distributionSetTypeId,
@RequestBody final MgmtDistributionSetTypeRequestBodyPut restDistributionSetType) { @RequestBody final MgmtDistributionSetTypeRequestBodyPut restDistributionSetType) {
final DistributionSetType type = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); return ResponseEntity.ok(toResponse(distributionSetManagement.updateDistributionSetType(entityFactory
.distributionSetType().update(distributionSetTypeId)
// only description can be modified .description(restDistributionSetType.getDescription()).colour(restDistributionSetType.getColour()))));
if (restDistributionSetType.getDescription() != null) {
type.setDescription(restDistributionSetType.getDescription());
}
final DistributionSetType updatedDistributionSetType = distributionSetManagement
.updateDistributionSetType(type);
return ResponseEntity.ok(toResponse(updatedDistributionSetType));
} }
@Override @Override
@@ -128,7 +122,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
@RequestBody final List<MgmtDistributionSetTypeRequestBodyPost> distributionSetTypes) { @RequestBody final List<MgmtDistributionSetTypeRequestBodyPost> distributionSetTypes) {
final List<DistributionSetType> createdSoftwareModules = distributionSetManagement.createDistributionSetTypes( final List<DistributionSetType> createdSoftwareModules = distributionSetManagement.createDistributionSetTypes(
MgmtDistributionSetTypeMapper.smFromRequest(entityFactory, softwareManagement, distributionSetTypes)); MgmtDistributionSetTypeMapper.smFromRequest(entityFactory, distributionSetTypes));
return ResponseEntity.status(CREATED).body(toTypesResponse(createdSoftwareModules)); return ResponseEntity.status(CREATED).body(toTypesResponse(createdSoftwareModules));
} }
@@ -196,17 +190,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
public ResponseEntity<Void> removeMandatoryModule( public ResponseEntity<Void> removeMandatoryModule(
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @PathVariable("distributionSetTypeId") final Long distributionSetTypeId,
@PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) { @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) {
distributionSetManagement.unassignSoftwareModuleType(distributionSetTypeId, 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);
return ResponseEntity.ok().build(); return ResponseEntity.ok().build();
} }
@@ -216,28 +200,15 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @PathVariable("distributionSetTypeId") final Long distributionSetTypeId,
@PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) { @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) {
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); return removeMandatoryModule(distributionSetTypeId, softwareModuleTypeId);
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();
} }
@Override @Override
public ResponseEntity<Void> addMandatoryModule( public ResponseEntity<Void> addMandatoryModule(
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @RequestBody final MgmtId smtId) { @PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @RequestBody final MgmtId smtId) {
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); distributionSetManagement.assignMandatorySoftwareModuleTypes(distributionSetTypeId,
final SoftwareModuleType smType = findSoftwareModuleTypeWithExceptionIfNotFound(smtId.getId()); Lists.newArrayList(smtId.getId()));
foundType.addMandatoryModuleType(smType);
distributionSetManagement.updateDistributionSetType(foundType);
return ResponseEntity.ok().build(); return ResponseEntity.ok().build();
} }
@@ -246,11 +217,8 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
public ResponseEntity<Void> addOptionalModule( public ResponseEntity<Void> addOptionalModule(
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @RequestBody final MgmtId smtId) { @PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @RequestBody final MgmtId smtId) {
final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); distributionSetManagement.assignOptionalSoftwareModuleTypes(distributionSetTypeId,
final SoftwareModuleType smType = findSoftwareModuleTypeWithExceptionIfNotFound(smtId.getId()); Lists.newArrayList(smtId.getId()));
foundType.addOptionalModuleType(smType);
distributionSetManagement.updateDistributionSetType(foundType);
return ResponseEntity.ok().build(); return ResponseEntity.ok().build();
} }

View File

@@ -15,6 +15,7 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; 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;
import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutCondition.Condition; import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutCondition.Condition;
import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutErrorAction; import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutErrorAction;
@@ -28,8 +29,8 @@ import org.eclipse.hawkbit.mgmt.json.model.rolloutgroup.MgmtRolloutGroupResponse
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRolloutRestApi; import org.eclipse.hawkbit.mgmt.rest.api.MgmtRolloutRestApi;
import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.exception.ConstraintViolationException; import org.eclipse.hawkbit.repository.builder.RolloutCreate;
import org.eclipse.hawkbit.repository.model.Action.ActionType; import org.eclipse.hawkbit.repository.builder.RolloutGroupCreate;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.Rollout;
import org.eclipse.hawkbit.repository.model.RolloutGroup; import org.eclipse.hawkbit.repository.model.RolloutGroup;
@@ -37,6 +38,8 @@ import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupErrorAction
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupErrorCondition; import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupErrorCondition;
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessAction; import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessAction;
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessCondition; 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; import org.eclipse.hawkbit.repository.model.TotalTargetCountStatus;
/** /**
@@ -91,60 +94,49 @@ final class MgmtRolloutMapper {
return body; return body;
} }
static Rollout fromRequest(final EntityFactory entityFactory, final MgmtRolloutRestRequestBody restRequest, static RolloutCreate fromRequest(final EntityFactory entityFactory, final MgmtRolloutRestRequestBody restRequest,
final DistributionSet distributionSet) { 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 entityFactory.rollout().create().name(restRequest.getName()).description(restRequest.getDescription())
return rollout; .set(distributionSet).targetFilterQuery(restRequest.getTargetFilterQuery())
.actionType(MgmtRestModelMapper.convertActionType(restRequest.getType()))
.forcedTime(restRequest.getForcetime());
} }
static RolloutGroup fromRequest(final EntityFactory entityFactory, final MgmtRolloutGroup restRequest) { static RolloutGroupCreate fromRequest(final EntityFactory entityFactory, final MgmtRolloutGroup restRequest) {
final RolloutGroup group = entityFactory.generateRolloutGroup();
group.setName(restRequest.getName());
group.setDescription(restRequest.getDescription());
if (restRequest.getTargetFilterQuery() != null) { return entityFactory.rolloutGroup().create().name(restRequest.getName())
group.setTargetFilterQuery(restRequest.getTargetFilterQuery()); .description(restRequest.getDescription()).targetFilterQuery(restRequest.getTargetFilterQuery())
} .targetPercentage(restRequest.getTargetPercentage()).conditions(fromRequest(restRequest, false));
}
final Float targetPercentage = restRequest.getTargetPercentage(); static RolloutGroupConditions fromRequest(final AbstractMgmtRolloutConditionsEntity restRequest,
if (targetPercentage == null) { final boolean withDefaults) {
group.setTargetPercentage(100); final RolloutGroupConditionBuilder conditions = new RolloutGroupConditionBuilder();
} else if (targetPercentage <= 0 || targetPercentage > 100) {
throw new ConstraintViolationException("Target percentage out of Range >0 - 100."); if (withDefaults) {
} else { conditions.withDefaults();
group.setTargetPercentage(restRequest.getTargetPercentage());
} }
if (restRequest.getSuccessCondition() != null) { if (restRequest.getSuccessCondition() != null) {
group.setSuccessCondition(mapFinishCondition(restRequest.getSuccessCondition().getCondition())); conditions.successCondition(mapFinishCondition(restRequest.getSuccessCondition().getCondition()),
group.setSuccessConditionExp(restRequest.getSuccessCondition().getExpression()); restRequest.getSuccessCondition().getExpression());
} }
if (restRequest.getSuccessAction() != null) { if (restRequest.getSuccessAction() != null) {
group.setSuccessAction(map(restRequest.getSuccessAction().getAction())); conditions.successAction(map(restRequest.getSuccessAction().getAction()),
group.setSuccessActionExp(restRequest.getSuccessAction().getExpression()); restRequest.getSuccessAction().getExpression());
}
if (restRequest.getErrorCondition() != null) {
group.setErrorCondition(mapErrorCondition(restRequest.getErrorCondition().getCondition()));
group.setErrorConditionExp(restRequest.getErrorCondition().getExpression());
}
if (restRequest.getErrorAction() != null) {
group.setErrorAction(map(restRequest.getErrorAction().getAction()));
group.setErrorActionExp(restRequest.getErrorAction().getExpression());
} }
return group; if (restRequest.getErrorCondition() != null) {
conditions.errorCondition(mapErrorCondition(restRequest.getErrorCondition().getCondition()),
restRequest.getErrorCondition().getExpression());
}
if (restRequest.getErrorAction() != null) {
conditions.errorAction(map(restRequest.getErrorAction().getAction()),
restRequest.getErrorAction().getExpression());
}
return conditions.build();
} }
static List<MgmtRolloutGroupResponseBody> toResponseRolloutGroup(final List<RolloutGroup> rollouts) { static List<MgmtRolloutGroupResponseBody> toResponseRolloutGroup(final List<RolloutGroup> rollouts) {

View File

@@ -24,16 +24,13 @@ import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.RolloutGroupManagement; import org.eclipse.hawkbit.repository.RolloutGroupManagement;
import org.eclipse.hawkbit.repository.RolloutManagement; import org.eclipse.hawkbit.repository.RolloutManagement;
import org.eclipse.hawkbit.repository.TargetFilterQueryManagement; 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.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.RolloutVerificationException;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.Rollout;
import org.eclipse.hawkbit.repository.model.RolloutGroup; import org.eclipse.hawkbit.repository.model.RolloutGroup;
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupErrorAction;
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupErrorCondition;
import org.eclipse.hawkbit.repository.model.RolloutGroup.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.RolloutGroupConditions;
import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.Target;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -110,56 +107,23 @@ public class MgmtRolloutResource implements MgmtRolloutRestApi {
targetFilterQueryManagement.verifyTargetFilterQuerySyntax(rolloutRequestBody.getTargetFilterQuery()); targetFilterQueryManagement.verifyTargetFilterQuerySyntax(rolloutRequestBody.getTargetFilterQuery());
final DistributionSet distributionSet = findDistributionSetOrThrowException(rolloutRequestBody); final DistributionSet distributionSet = findDistributionSetOrThrowException(rolloutRequestBody);
final RolloutGroupConditions rolloutGroupConditions = MgmtRolloutMapper.fromRequest(rolloutRequestBody, true);
// success condition final RolloutCreate create = MgmtRolloutMapper.fromRequest(entityFactory, rolloutRequestBody, distributionSet);
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);
Rollout rollout;
if (rolloutRequestBody.getGroups() != null) { if (rolloutRequestBody.getGroups() != null) {
final List<RolloutGroup> rolloutGroups = rolloutRequestBody.getGroups().stream() final List<RolloutGroupCreate> rolloutGroups = rolloutRequestBody.getGroups().stream()
.map(mgmtRolloutGroup -> MgmtRolloutMapper.fromRequest(entityFactory, mgmtRolloutGroup)) .map(mgmtRolloutGroup -> MgmtRolloutMapper.fromRequest(entityFactory, mgmtRolloutGroup))
.collect(Collectors.toList()); .collect(Collectors.toList());
rollout = rolloutManagement.createRollout(rollout, rolloutGroups, rolloutGroupConditions); rollout = rolloutManagement.createRollout(create, rolloutGroups, rolloutGroupConditions);
} else if (rolloutRequestBody.getAmountGroups() != null) { } else if (rolloutRequestBody.getAmountGroups() != null) {
rollout = rolloutManagement.createRollout(rollout, rolloutRequestBody.getAmountGroups(), rollout = rolloutManagement.createRollout(create, rolloutRequestBody.getAmountGroups(),
rolloutGroupConditions); rolloutGroupConditions);
} else { } 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)); return ResponseEntity.status(HttpStatus.CREATED).body(MgmtRolloutMapper.toResponseRollout(rollout));
@@ -247,8 +211,7 @@ public class MgmtRolloutResource implements MgmtRolloutRestApi {
rolloutGroupTargets = pageTargets; rolloutGroupTargets = pageTargets;
} }
final List<MgmtTarget> rest = MgmtTargetMapper.toResponse(rolloutGroupTargets.getContent()); final List<MgmtTarget> rest = MgmtTargetMapper.toResponse(rolloutGroupTargets.getContent());
return new ResponseEntity<>(new PagedList<MgmtTarget>(rest, rolloutGroupTargets.getTotalElements()), return new ResponseEntity<>(new PagedList<>(rest, rolloutGroupTargets.getTotalElements()), HttpStatus.OK);
HttpStatus.OK);
} }
private Rollout findRolloutOrThrowException(final Long rolloutId) { private Rollout findRolloutOrThrowException(final Long rolloutId) {

View File

@@ -25,13 +25,11 @@ import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleRestApi; import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleRestApi;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleTypeRestApi; import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleTypeRestApi;
import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.SoftwareManagement; 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.model.Artifact; 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.SoftwareModule;
import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; 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 * A mapper which maps repository model to RESTful model representation and
@@ -43,46 +41,30 @@ public final class MgmtSoftwareModuleMapper {
// Utility class // Utility class
} }
private static SoftwareModuleType getSoftwareModuleTypeFromKeyString(final String type, static SoftwareModuleCreate fromRequest(final EntityFactory entityFactory,
final SoftwareManagement softwareManagement) { final MgmtSoftwareModuleRequestBodyPost smsRest) {
if (type == null) { return entityFactory.softwareModule().create().type(smsRest.getType()).name(smsRest.getName())
throw new ConstraintViolationException("type cannot be null"); .version(smsRest.getVersion()).description(smsRest.getDescription()).vendor(smsRest.getVendor());
}
final SoftwareModuleType smType = softwareManagement.findSoftwareModuleTypeByKey(type.trim());
if (smType == null) {
throw new EntityNotFoundException(type.trim());
}
return smType;
} }
static SoftwareModule fromRequest(final EntityFactory entityFactory, static List<MetaData> fromRequestSwMetadata(final EntityFactory entityFactory,
final MgmtSoftwareModuleRequestBodyPost smsRest, final SoftwareManagement softwareManagement) { final Collection<MgmtMetadata> metadata) {
return entityFactory.generateSoftwareModule(
getSoftwareModuleTypeFromKeyString(smsRest.getType(), softwareManagement), smsRest.getName(),
smsRest.getVersion(), smsRest.getDescription(), smsRest.getVendor());
}
static List<SoftwareModuleMetadata> fromRequestSwMetadata(final EntityFactory entityFactory,
final SoftwareModule sw, final Collection<MgmtMetadata> metadata) {
if (metadata == null) { if (metadata == null) {
return Collections.emptyList(); return Collections.emptyList();
} }
return metadata.stream().map(metadataRest -> entityFactory.generateSoftwareModuleMetadata(sw, return metadata.stream()
metadataRest.getKey(), metadataRest.getValue())).collect(Collectors.toList()); .map(metadataRest -> entityFactory.generateMetadata(metadataRest.getKey(), metadataRest.getValue()))
.collect(Collectors.toList());
} }
static List<SoftwareModule> smFromRequest(final EntityFactory entityFactory, static List<SoftwareModuleCreate> smFromRequest(final EntityFactory entityFactory,
final Collection<MgmtSoftwareModuleRequestBodyPost> smsRest, final SoftwareManagement softwareManagement) { final Collection<MgmtSoftwareModuleRequestBodyPost> smsRest) {
if (smsRest == null) { if (smsRest == null) {
return Collections.emptyList(); return Collections.emptyList();
} }
return smsRest.stream().map(smRest -> fromRequest(entityFactory, smRest, softwareManagement)) return smsRest.stream().map(smRest -> fromRequest(entityFactory, smRest)).collect(Collectors.toList());
.collect(Collectors.toList());
} }
/** /**

View File

@@ -170,8 +170,8 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
@RequestBody final List<MgmtSoftwareModuleRequestBodyPost> softwareModules) { @RequestBody final List<MgmtSoftwareModuleRequestBodyPost> softwareModules) {
LOG.debug("creating {} softwareModules", softwareModules.size()); LOG.debug("creating {} softwareModules", softwareModules.size());
final Collection<SoftwareModule> createdSoftwareModules = softwareManagement.createSoftwareModule( final Collection<SoftwareModule> createdSoftwareModules = softwareManagement
MgmtSoftwareModuleMapper.smFromRequest(entityFactory, softwareModules, softwareManagement)); .createSoftwareModule(MgmtSoftwareModuleMapper.smFromRequest(entityFactory, softwareModules));
LOG.debug("{} softwareModules created, return status {}", softwareModules.size(), HttpStatus.CREATED); LOG.debug("{} softwareModules created, return status {}", softwareModules.size(), HttpStatus.CREATED);
return ResponseEntity.status(CREATED).body(toResponse(createdSoftwareModules)); return ResponseEntity.status(CREATED).body(toResponse(createdSoftwareModules));
@@ -182,18 +182,9 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
@PathVariable("softwareModuleId") final Long softwareModuleId, @PathVariable("softwareModuleId") final Long softwareModuleId,
@RequestBody final MgmtSoftwareModuleRequestBodyPut restSoftwareModule) { @RequestBody final MgmtSoftwareModuleRequestBodyPut restSoftwareModule) {
final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null); return ResponseEntity.ok(toResponse(
softwareManagement.updateSoftwareModule(entityFactory.softwareModule().update(softwareModuleId)
// only description and vendor can be modified .description(restSoftwareModule.getDescription()).vendor(restSoftwareModule.getVendor()))));
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));
} }
@Override @Override
@@ -238,8 +229,8 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
public ResponseEntity<MgmtMetadata> getMetadataValue(@PathVariable("softwareModuleId") final Long softwareModuleId, public ResponseEntity<MgmtMetadata> getMetadataValue(@PathVariable("softwareModuleId") final Long softwareModuleId,
@PathVariable("metadataKey") final String metadataKey) { @PathVariable("metadataKey") final String metadataKey) {
final SoftwareModule sw = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null); final SoftwareModuleMetadata findOne = softwareManagement.findSoftwareModuleMetadata(softwareModuleId,
final SoftwareModuleMetadata findOne = softwareManagement.findSoftwareModuleMetadata(sw.getId(), metadataKey); metadataKey);
return ResponseEntity.ok(toResponseSwMetadata(findOne)); return ResponseEntity.ok(toResponseSwMetadata(findOne));
} }
@@ -247,10 +238,8 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
@Override @Override
public ResponseEntity<MgmtMetadata> updateMetadata(@PathVariable("softwareModuleId") final Long softwareModuleId, public ResponseEntity<MgmtMetadata> updateMetadata(@PathVariable("softwareModuleId") final Long softwareModuleId,
@PathVariable("metadataKey") final String metadataKey, @RequestBody final MgmtMetadata metadata) { @PathVariable("metadataKey") final String metadataKey, @RequestBody final MgmtMetadata metadata) {
final SoftwareModuleMetadata updated = softwareManagement.updateSoftwareModuleMetadata(softwareModuleId,
final SoftwareModule sw = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null); entityFactory.generateMetadata(metadataKey, metadata.getValue()));
final SoftwareModuleMetadata updated = softwareManagement.updateSoftwareModuleMetadata(
entityFactory.generateSoftwareModuleMetadata(sw, metadataKey, metadata.getValue()));
return ResponseEntity.ok(toResponseSwMetadata(updated)); return ResponseEntity.ok(toResponseSwMetadata(updated));
} }
@@ -258,9 +247,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
@Override @Override
public ResponseEntity<Void> deleteMetadata(@PathVariable("softwareModuleId") final Long softwareModuleId, public ResponseEntity<Void> deleteMetadata(@PathVariable("softwareModuleId") final Long softwareModuleId,
@PathVariable("metadataKey") final String metadataKey) { @PathVariable("metadataKey") final String metadataKey) {
softwareManagement.deleteSoftwareModuleMetadata(softwareModuleId, metadataKey);
final SoftwareModule sw = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null);
softwareManagement.deleteSoftwareModuleMetadata(sw.getId(), metadataKey);
return ResponseEntity.ok().build(); return ResponseEntity.ok().build();
} }
@@ -270,9 +257,8 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
@PathVariable("softwareModuleId") final Long softwareModuleId, @PathVariable("softwareModuleId") final Long softwareModuleId,
@RequestBody final List<MgmtMetadata> metadataRest) { @RequestBody final List<MgmtMetadata> metadataRest) {
final SoftwareModule sw = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null); final List<SoftwareModuleMetadata> created = softwareManagement.createSoftwareModuleMetadata(softwareModuleId,
final List<SoftwareModuleMetadata> created = softwareManagement.createSoftwareModuleMetadata( MgmtSoftwareModuleMapper.fromRequestSwMetadata(entityFactory, metadataRest));
MgmtSoftwareModuleMapper.fromRequestSwMetadata(entityFactory, sw, metadataRest));
return ResponseEntity.status(CREATED).body(toResponseSwMetadata(created)); return ResponseEntity.status(CREATED).body(toResponseSwMetadata(created));
} }

View File

@@ -20,6 +20,7 @@ import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModule
import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeRequestBodyPost; import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeRequestBodyPost;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleTypeRestApi; import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleTypeRestApi;
import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeCreate;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
/** /**
@@ -34,7 +35,7 @@ final class MgmtSoftwareModuleTypeMapper {
} }
static List<SoftwareModuleType> smFromRequest(final EntityFactory entityFactory, static List<SoftwareModuleTypeCreate> smFromRequest(final EntityFactory entityFactory,
final Collection<MgmtSoftwareModuleTypeRequestBodyPost> smTypesRest) { final Collection<MgmtSoftwareModuleTypeRequestBodyPost> smTypesRest) {
if (smTypesRest == null) { if (smTypesRest == null) {
return Collections.emptyList(); return Collections.emptyList();
@@ -43,15 +44,11 @@ final class MgmtSoftwareModuleTypeMapper {
return smTypesRest.stream().map(smRest -> fromRequest(entityFactory, smRest)).collect(Collectors.toList()); 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 MgmtSoftwareModuleTypeRequestBodyPost smsRest) {
final SoftwareModuleType result = entityFactory.generateSoftwareModuleType(); return entityFactory.softwareModuleType().create().key(smsRest.getKey()).name(smsRest.getName())
result.setName(smsRest.getName()); .description(smsRest.getDescription()).colour(smsRest.getColour())
result.setKey(smsRest.getKey()); .maxAssignments(smsRest.getMaxAssignments());
result.setDescription(smsRest.getDescription());
result.setMaxAssignments(smsRest.getMaxAssignments());
return result;
} }
static List<MgmtSoftwareModuleType> toTypesResponse(final Collection<SoftwareModuleType> types) { static List<MgmtSoftwareModuleType> toTypesResponse(final Collection<SoftwareModuleType> types) {

View File

@@ -64,11 +64,11 @@ public class MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRes
final Slice<SoftwareModuleType> findModuleTypessAll; final Slice<SoftwareModuleType> findModuleTypessAll;
Long countModulesAll; Long countModulesAll;
if (rsqlParam != null) { if (rsqlParam != null) {
findModuleTypessAll = this.softwareManagement.findSoftwareModuleTypesAll(rsqlParam, pageable); findModuleTypessAll = softwareManagement.findSoftwareModuleTypesAll(rsqlParam, pageable);
countModulesAll = ((Page<SoftwareModuleType>) findModuleTypessAll).getTotalElements(); countModulesAll = ((Page<SoftwareModuleType>) findModuleTypessAll).getTotalElements();
} else { } else {
findModuleTypessAll = this.softwareManagement.findSoftwareModuleTypesAll(pageable); findModuleTypessAll = softwareManagement.findSoftwareModuleTypesAll(pageable);
countModulesAll = this.softwareManagement.countSoftwareModuleTypesAll(); countModulesAll = softwareManagement.countSoftwareModuleTypesAll();
} }
final List<MgmtSoftwareModuleType> rest = MgmtSoftwareModuleTypeMapper final List<MgmtSoftwareModuleType> rest = MgmtSoftwareModuleTypeMapper
@@ -89,7 +89,7 @@ public class MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRes
@PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) { @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) {
final SoftwareModuleType module = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId); final SoftwareModuleType module = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId);
this.softwareManagement.deleteSoftwareModuleType(module); softwareManagement.deleteSoftwareModuleType(module);
return new ResponseEntity<>(HttpStatus.OK); return new ResponseEntity<>(HttpStatus.OK);
} }
@@ -98,14 +98,11 @@ public class MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRes
public ResponseEntity<MgmtSoftwareModuleType> updateSoftwareModuleType( public ResponseEntity<MgmtSoftwareModuleType> updateSoftwareModuleType(
@PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId, @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId,
@RequestBody final MgmtSoftwareModuleTypeRequestBodyPut restSoftwareModuleType) { @RequestBody final MgmtSoftwareModuleTypeRequestBodyPut restSoftwareModuleType) {
final SoftwareModuleType type = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId);
// only description can be modified final SoftwareModuleType updatedSoftwareModuleType = softwareManagement.updateSoftwareModuleType(entityFactory
if (restSoftwareModuleType.getDescription() != null) { .softwareModuleType().update(softwareModuleTypeId).description(restSoftwareModuleType.getDescription())
type.setDescription(restSoftwareModuleType.getDescription()); .colour(restSoftwareModuleType.getColour()));
}
final SoftwareModuleType updatedSoftwareModuleType = this.softwareManagement.updateSoftwareModuleType(type);
return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toResponse(updatedSoftwareModuleType), HttpStatus.OK); return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toResponse(updatedSoftwareModuleType), HttpStatus.OK);
} }
@@ -113,7 +110,7 @@ public class MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRes
public ResponseEntity<List<MgmtSoftwareModuleType>> createSoftwareModuleTypes( public ResponseEntity<List<MgmtSoftwareModuleType>> createSoftwareModuleTypes(
@RequestBody final List<MgmtSoftwareModuleTypeRequestBodyPost> softwareModuleTypes) { @RequestBody final List<MgmtSoftwareModuleTypeRequestBodyPost> softwareModuleTypes) {
final List<SoftwareModuleType> createdSoftwareModules = this.softwareManagement.createSoftwareModuleType( final List<SoftwareModuleType> createdSoftwareModules = softwareManagement.createSoftwareModuleType(
MgmtSoftwareModuleTypeMapper.smFromRequest(entityFactory, softwareModuleTypes)); MgmtSoftwareModuleTypeMapper.smFromRequest(entityFactory, softwareModuleTypes));
return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toTypesResponse(createdSoftwareModules), return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toTypesResponse(createdSoftwareModules),
@@ -121,7 +118,7 @@ public class MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRes
} }
private SoftwareModuleType findSoftwareModuleTypeWithExceptionIfNotFound(final Long softwareModuleTypeId) { private SoftwareModuleType findSoftwareModuleTypeWithExceptionIfNotFound(final Long softwareModuleTypeId) {
final SoftwareModuleType module = this.softwareManagement.findSoftwareModuleTypeById(softwareModuleTypeId); final SoftwareModuleType module = softwareManagement.findSoftwareModuleTypeById(softwareModuleTypeId);
if (module == null) { if (module == null) {
throw new EntityNotFoundException( throw new EntityNotFoundException(
"SoftwareModuleType with Id {" + softwareModuleTypeId + "} does not exist"); "SoftwareModuleType with Id {" + softwareModuleTypeId + "} does not exist");

View File

@@ -12,13 +12,16 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.List; 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.MgmtTag;
import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTagRequestBodyPut; import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTagRequestBodyPut;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTagRestApi; import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTagRestApi;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetTagRestApi; import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetTagRestApi;
import org.eclipse.hawkbit.repository.EntityFactory; 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.DistributionSetTag;
import org.eclipse.hawkbit.repository.model.Tag; import org.eclipse.hawkbit.repository.model.Tag;
import org.eclipse.hawkbit.repository.model.TargetTag; import org.eclipse.hawkbit.repository.model.TargetTag;
@@ -96,24 +99,12 @@ final class MgmtTagMapper {
return response; return response;
} }
static List<TargetTag> mapTargeTagFromRequest(final EntityFactory entityFactory, static List<TagCreate> mapTagFromRequest(final EntityFactory entityFactory,
final Iterable<MgmtTagRequestBodyPut> tags) { final Collection<MgmtTagRequestBodyPut> tags) {
final List<TargetTag> mappedList = new ArrayList<>(); return tags.stream()
for (final MgmtTagRequestBodyPut targetTagRest : tags) { .map(tagRest -> entityFactory.tag().create().name(tagRest.getName())
mappedList.add(entityFactory.generateTargetTag(targetTagRest.getName(), targetTagRest.getDescription(), .description(tagRest.getDescription()).colour(tagRest.getColour()))
targetTagRest.getColour())); .collect(Collectors.toList());
}
return mappedList;
}
static List<DistributionSetTag> mapDistributionSetTagFromRequest(final EntityFactory entityFactory,
final Iterable<MgmtTagRequestBodyPut> tags) {
final List<DistributionSetTag> mappedList = new ArrayList<>();
for (final MgmtTagRequestBodyPut targetTagRest : tags) {
mappedList.add(entityFactory.generateDistributionSetTag(targetTagRest.getName(),
targetTagRest.getDescription(), targetTagRest.getColour()));
}
return mappedList;
} }
private static void mapTag(final MgmtTag response, final Tag tag) { private static void mapTag(final MgmtTag response, final Tag tag) {
@@ -121,18 +112,4 @@ final class MgmtTagMapper {
response.setTagId(tag.getId()); response.setTagId(tag.getId());
response.setColour(tag.getColour()); 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());
}
}
} }

View File

@@ -19,6 +19,7 @@ import org.eclipse.hawkbit.mgmt.json.model.targetfilter.MgmtTargetFilterQuery;
import org.eclipse.hawkbit.mgmt.json.model.targetfilter.MgmtTargetFilterQueryRequestBody; import org.eclipse.hawkbit.mgmt.json.model.targetfilter.MgmtTargetFilterQueryRequestBody;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetFilterQueryRestApi; import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetFilterQueryRestApi;
import org.eclipse.hawkbit.repository.EntityFactory; 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.DistributionSet;
import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.eclipse.hawkbit.repository.model.TargetFilterQuery;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
@@ -55,7 +56,7 @@ public final class MgmtTargetFilterQueryMapper {
* the target * the target
* @return the response * @return the response
*/ */
public static MgmtTargetFilterQuery toResponse(final TargetFilterQuery filter) { static MgmtTargetFilterQuery toResponse(final TargetFilterQuery filter) {
final MgmtTargetFilterQuery targetRest = new MgmtTargetFilterQuery(); final MgmtTargetFilterQuery targetRest = new MgmtTargetFilterQuery();
targetRest.setFilterId(filter.getId()); targetRest.setFilterId(filter.getId());
targetRest.setName(filter.getName()); targetRest.setName(filter.getName());
@@ -67,7 +68,7 @@ public final class MgmtTargetFilterQueryMapper {
targetRest.setCreatedAt(filter.getCreatedAt()); targetRest.setCreatedAt(filter.getCreatedAt());
targetRest.setLastModifiedAt(filter.getLastModifiedAt()); targetRest.setLastModifiedAt(filter.getLastModifiedAt());
DistributionSet distributionSet = filter.getAutoAssignDistributionSet(); final DistributionSet distributionSet = filter.getAutoAssignDistributionSet();
if (distributionSet != null) { if (distributionSet != null) {
targetRest.setAutoAssignDistributionSet(distributionSet.getId()); targetRest.setAutoAssignDistributionSet(distributionSet.getId());
} }
@@ -80,13 +81,10 @@ public final class MgmtTargetFilterQueryMapper {
return targetRest; return targetRest;
} }
static TargetFilterQuery fromRequest(final EntityFactory entityFactory, static TargetFilterQueryCreate fromRequest(final EntityFactory entityFactory,
final MgmtTargetFilterQueryRequestBody filterRest) { final MgmtTargetFilterQueryRequestBody filterRest) {
final TargetFilterQuery filter = entityFactory.generateTargetFilterQuery();
filter.setName(filterRest.getName());
filter.setQuery(filterRest.getQuery());
return filter; return entityFactory.targetFilterQuery().create().name(filterRest.getName()).query(filterRest.getQuery());
} }
} }

View File

@@ -17,7 +17,6 @@ import org.eclipse.hawkbit.mgmt.json.model.targetfilter.MgmtTargetFilterQuery;
import org.eclipse.hawkbit.mgmt.json.model.targetfilter.MgmtTargetFilterQueryRequestBody; import org.eclipse.hawkbit.mgmt.json.model.targetfilter.MgmtTargetFilterQueryRequestBody;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetFilterQueryRestApi; import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetFilterQueryRestApi;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.TargetFilterQueryManagement; import org.eclipse.hawkbit.repository.TargetFilterQueryManagement;
@@ -48,14 +47,11 @@ public class MgmtTargetFilterQueryResource implements MgmtTargetFilterQueryRestA
@Autowired @Autowired
private TargetFilterQueryManagement filterManagement; private TargetFilterQueryManagement filterManagement;
@Autowired
private DistributionSetManagement distributionSetManagement;
@Autowired @Autowired
private EntityFactory entityFactory; private EntityFactory entityFactory;
@Override @Override
public ResponseEntity<MgmtTargetFilterQuery> getFilter(@PathVariable("filterId") Long filterId) { public ResponseEntity<MgmtTargetFilterQuery> getFilter(@PathVariable("filterId") final Long filterId) {
final TargetFilterQuery findTarget = findFilterWithExceptionIfNotFound(filterId); final TargetFilterQuery findTarget = findFilterWithExceptionIfNotFound(filterId);
// to single response include poll status // to single response include poll status
final MgmtTargetFilterQuery response = MgmtTargetFilterQueryMapper.toResponse(findTarget); final MgmtTargetFilterQuery response = MgmtTargetFilterQueryMapper.toResponse(findTarget);
@@ -65,10 +61,10 @@ public class MgmtTargetFilterQueryResource implements MgmtTargetFilterQueryRestA
@Override @Override
public ResponseEntity<PagedList<MgmtTargetFilterQuery>> getFilters( public ResponseEntity<PagedList<MgmtTargetFilterQuery>> getFilters(
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) int pagingOffsetParam, @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) int pagingLimitParam, @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) String sortParam, @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) String rsqlParam) { @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) {
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam); final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
@@ -78,8 +74,8 @@ public class MgmtTargetFilterQueryResource implements MgmtTargetFilterQueryRestA
final Slice<TargetFilterQuery> findTargetFiltersAll; final Slice<TargetFilterQuery> findTargetFiltersAll;
final Long countTargetsAll; final Long countTargetsAll;
if (rsqlParam != null) { if (rsqlParam != null) {
final Page<TargetFilterQuery> findFilterPage = filterManagement final Page<TargetFilterQuery> findFilterPage = filterManagement.findTargetFilterQueryByFilter(pageable,
.findTargetFilterQueryByFilter(pageable, rsqlParam); rsqlParam);
countTargetsAll = findFilterPage.getTotalElements(); countTargetsAll = findFilterPage.getTotalElements();
findTargetFiltersAll = findFilterPage; findTargetFiltersAll = findFilterPage;
} else { } else {
@@ -89,11 +85,12 @@ public class MgmtTargetFilterQueryResource implements MgmtTargetFilterQueryRestA
final List<MgmtTargetFilterQuery> rest = MgmtTargetFilterQueryMapper final List<MgmtTargetFilterQuery> rest = MgmtTargetFilterQueryMapper
.toResponse(findTargetFiltersAll.getContent()); .toResponse(findTargetFiltersAll.getContent());
return new ResponseEntity<>(new PagedList<MgmtTargetFilterQuery>(rest, countTargetsAll), HttpStatus.OK); return new ResponseEntity<>(new PagedList<>(rest, countTargetsAll), HttpStatus.OK);
} }
@Override @Override
public ResponseEntity<MgmtTargetFilterQuery> createFilter(@RequestBody MgmtTargetFilterQueryRequestBody filter) { public ResponseEntity<MgmtTargetFilterQuery> createFilter(
@RequestBody final MgmtTargetFilterQueryRequestBody filter) {
final TargetFilterQuery createdTarget = filterManagement final TargetFilterQuery createdTarget = filterManagement
.createTargetFilterQuery(MgmtTargetFilterQueryMapper.fromRequest(entityFactory, filter)); .createTargetFilterQuery(MgmtTargetFilterQueryMapper.fromRequest(entityFactory, filter));
@@ -101,65 +98,48 @@ public class MgmtTargetFilterQueryResource implements MgmtTargetFilterQueryRestA
} }
@Override @Override
public ResponseEntity<MgmtTargetFilterQuery> updateFilter(@PathVariable("filterId") Long filterId, public ResponseEntity<MgmtTargetFilterQuery> updateFilter(@PathVariable("filterId") final Long filterId,
@RequestBody MgmtTargetFilterQueryRequestBody targetFilterRest) { @RequestBody final MgmtTargetFilterQueryRequestBody targetFilterRest) {
LOG.debug("updating target filter query {}", filterId);
final TargetFilterQuery existingFilter = findFilterWithExceptionIfNotFound(filterId); final TargetFilterQuery updateFilter = filterManagement
LOG.debug("updating target filter query {}", existingFilter.getId()); .updateTargetFilterQuery(entityFactory.targetFilterQuery().update(filterId)
if (targetFilterRest.getName() != null) { .name(targetFilterRest.getName()).query(targetFilterRest.getQuery()));
existingFilter.setName(targetFilterRest.getName());
}
if (targetFilterRest.getQuery() != null) {
existingFilter.setQuery(targetFilterRest.getQuery());
}
final TargetFilterQuery updateFilter = filterManagement.updateTargetFilterQuery(existingFilter);
return new ResponseEntity<>(MgmtTargetFilterQueryMapper.toResponse(updateFilter), HttpStatus.OK); return new ResponseEntity<>(MgmtTargetFilterQueryMapper.toResponse(updateFilter), HttpStatus.OK);
} }
@Override @Override
public ResponseEntity<Void> deleteFilter(@PathVariable("filterId") Long filterId) { public ResponseEntity<Void> deleteFilter(@PathVariable("filterId") final Long filterId) {
final TargetFilterQuery filter = findFilterWithExceptionIfNotFound(filterId); findFilterWithExceptionIfNotFound(filterId);
filterManagement.deleteTargetFilterQuery(filter.getId()); filterManagement.deleteTargetFilterQuery(filterId);
LOG.debug("{} target filter query deleted, return status {}", filterId, HttpStatus.OK); LOG.debug("{} target filter query deleted, return status {}", filterId, HttpStatus.OK);
return new ResponseEntity<>(HttpStatus.OK); return new ResponseEntity<>(HttpStatus.OK);
} }
@Override @Override
public ResponseEntity<MgmtTargetFilterQuery> postAssignedDistributionSet(@PathVariable("filterId") Long filterId, public ResponseEntity<MgmtTargetFilterQuery> postAssignedDistributionSet(
@RequestBody MgmtId dsId) { @PathVariable("filterId") final Long filterId, @RequestBody final MgmtId dsId) {
final TargetFilterQuery filter = findFilterWithExceptionIfNotFound(filterId);
DistributionSet distributionSet; final TargetFilterQuery updateFilter = filterManagement.updateTargetFilterQueryAutoAssignDS(filterId,
distributionSet = distributionSetManagement.findDistributionSetById(dsId.getId()); dsId.getId());
if (distributionSet == null) {
throw new EntityNotFoundException("DistributionSet with Id {" + dsId + "} does not exist");
}
filter.setAutoAssignDistributionSet(distributionSet);
final TargetFilterQuery updateFilter = filterManagement.updateTargetFilterQuery(filter);
return new ResponseEntity<>(MgmtTargetFilterQueryMapper.toResponse(updateFilter), HttpStatus.OK); return new ResponseEntity<>(MgmtTargetFilterQueryMapper.toResponse(updateFilter), HttpStatus.OK);
} }
@Override @Override
public ResponseEntity<MgmtDistributionSet> getAssignedDistributionSet(@PathVariable("filterId") Long filterId) { public ResponseEntity<MgmtDistributionSet> getAssignedDistributionSet(
@PathVariable("filterId") final Long filterId) {
final TargetFilterQuery filter = findFilterWithExceptionIfNotFound(filterId); final TargetFilterQuery filter = findFilterWithExceptionIfNotFound(filterId);
DistributionSet autoAssignDistributionSet = filter.getAutoAssignDistributionSet(); final DistributionSet autoAssignDistributionSet = filter.getAutoAssignDistributionSet();
MgmtDistributionSet distributionSetRest = MgmtDistributionSetMapper.toResponse(autoAssignDistributionSet); final MgmtDistributionSet distributionSetRest = MgmtDistributionSetMapper.toResponse(autoAssignDistributionSet);
final HttpStatus retStatus = distributionSetRest == null ? HttpStatus.NO_CONTENT : HttpStatus.OK; final HttpStatus retStatus = distributionSetRest == null ? HttpStatus.NO_CONTENT : HttpStatus.OK;
return new ResponseEntity<>(distributionSetRest, retStatus); return new ResponseEntity<>(distributionSetRest, retStatus);
} }
@Override @Override
public ResponseEntity<Void> deleteAssignedDistributionSet(@PathVariable("filterId") Long filterId) { public ResponseEntity<Void> deleteAssignedDistributionSet(@PathVariable("filterId") final Long filterId) {
final TargetFilterQuery filter = findFilterWithExceptionIfNotFound(filterId); filterManagement.updateTargetFilterQueryAutoAssignDS(filterId, null);
filter.setAutoAssignDistributionSet(null);
filterManagement.updateTargetFilterQuery(filter);
return new ResponseEntity<>(HttpStatus.NO_CONTENT); return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} }

View File

@@ -28,6 +28,7 @@ import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetRestApi; import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetRestApi;
import org.eclipse.hawkbit.repository.ActionFields; import org.eclipse.hawkbit.repository.ActionFields;
import org.eclipse.hawkbit.repository.EntityFactory; 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.Action;
import org.eclipse.hawkbit.repository.model.ActionStatus; import org.eclipse.hawkbit.repository.model.ActionStatus;
import org.eclipse.hawkbit.repository.model.PollStatus; import org.eclipse.hawkbit.repository.model.PollStatus;
@@ -171,7 +172,7 @@ public final class MgmtTargetMapper {
return targetRest; return targetRest;
} }
static List<Target> fromRequest(final EntityFactory entityFactory, static List<TargetCreate> fromRequest(final EntityFactory entityFactory,
final Collection<MgmtTargetRequestBody> targetsRest) { final Collection<MgmtTargetRequestBody> targetsRest) {
if (targetsRest == null) { if (targetsRest == null) {
return Collections.emptyList(); return Collections.emptyList();
@@ -181,13 +182,10 @@ public final class MgmtTargetMapper {
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
static Target fromRequest(final EntityFactory entityFactory, final MgmtTargetRequestBody targetRest) { static TargetCreate fromRequest(final EntityFactory entityFactory, final MgmtTargetRequestBody targetRest) {
final Target target = entityFactory.generateTarget(targetRest.getControllerId(), targetRest.getSecurityToken()); return entityFactory.target().create().controllerId(targetRest.getControllerId()).name(targetRest.getName())
target.setDescription(targetRest.getDescription()); .description(targetRest.getDescription()).securityToken(targetRest.getSecurityToken())
target.setName(targetRest.getName()); .address(targetRest.getAddress());
target.getTargetInfo().setAddress(targetRest.getAddress());
return target;
} }
static List<MgmtActionStatus> toActionStatusRestResponse(final Collection<ActionStatus> actionStatus) { static List<MgmtActionStatus> toActionStatusRestResponse(final Collection<ActionStatus> actionStatus) {

View File

@@ -52,6 +52,8 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.google.common.collect.Lists;
/** /**
* REST Resource handling target CRUD operations. * REST Resource handling target CRUD operations.
*/ */
@@ -103,7 +105,7 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
} }
final List<MgmtTarget> rest = MgmtTargetMapper.toResponse(findTargetsAll.getContent()); final List<MgmtTarget> rest = MgmtTargetMapper.toResponse(findTargetsAll.getContent());
return new ResponseEntity<>(new PagedList<MgmtTarget>(rest, countTargetsAll), HttpStatus.OK); return new ResponseEntity<>(new PagedList<>(rest, countTargetsAll), HttpStatus.OK);
} }
@Override @Override
@@ -118,22 +120,10 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
@Override @Override
public ResponseEntity<MgmtTarget> updateTarget(@PathVariable("controllerId") final String controllerId, public ResponseEntity<MgmtTarget> updateTarget(@PathVariable("controllerId") final String controllerId,
@RequestBody final MgmtTargetRequestBody targetRest) { @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); return new ResponseEntity<>(MgmtTargetMapper.toResponse(updateTarget), HttpStatus.OK);
} }
@@ -291,8 +281,8 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
final ActionType type = (dsId.getType() != null) ? MgmtRestModelMapper.convertActionType(dsId.getType()) final ActionType type = (dsId.getType() != null) ? MgmtRestModelMapper.convertActionType(dsId.getType())
: ActionType.FORCED; : ActionType.FORCED;
final Iterator<Target> changed = this.deploymentManagement final Iterator<Target> changed = this.deploymentManagement
.assignDistributionSet(dsId.getId(), type, dsId.getForcetime(), controllerId).getAssignedEntity() .assignDistributionSet(dsId.getId(), type, dsId.getForcetime(), Lists.newArrayList(controllerId))
.iterator(); .getAssignedEntity().iterator();
if (changed.hasNext()) { if (changed.hasNext()) {
return new ResponseEntity<>(HttpStatus.OK); return new ResponseEntity<>(HttpStatus.OK);
} }

View File

@@ -97,7 +97,7 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
public ResponseEntity<List<MgmtTag>> createTargetTags(@RequestBody final List<MgmtTagRequestBodyPut> tags) { public ResponseEntity<List<MgmtTag>> createTargetTags(@RequestBody final List<MgmtTagRequestBodyPut> tags) {
LOG.debug("creating {} target tags", tags.size()); LOG.debug("creating {} target tags", tags.size());
final List<TargetTag> createdTargetTags = this.tagManagement final List<TargetTag> createdTargetTags = this.tagManagement
.createTargetTags(MgmtTagMapper.mapTargeTagFromRequest(entityFactory, tags)); .createTargetTags(MgmtTagMapper.mapTagFromRequest(entityFactory, tags));
return new ResponseEntity<>(MgmtTagMapper.toResponse(createdTargetTags), HttpStatus.CREATED); return new ResponseEntity<>(MgmtTagMapper.toResponse(createdTargetTags), HttpStatus.CREATED);
} }
@@ -106,9 +106,9 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
@RequestBody final MgmtTagRequestBodyPut restTargetTagRest) { @RequestBody final MgmtTagRequestBodyPut restTargetTagRest) {
LOG.debug("update {} target tag", restTargetTagRest); LOG.debug("update {} target tag", restTargetTagRest);
final TargetTag targetTag = findTargetTagById(targetTagId); final TargetTag updateTargetTag = tagManagement
MgmtTagMapper.updateTag(restTargetTagRest, targetTag); .updateTargetTag(entityFactory.tag().update(targetTagId).name(restTargetTagRest.getName())
final TargetTag updateTargetTag = this.tagManagement.updateTargetTag(targetTag); .description(restTargetTagRest.getDescription()).colour(restTargetTagRest.getColour()));
LOG.debug("target tag updated"); LOG.debug("target tag updated");

View File

@@ -22,7 +22,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.Collection;
import java.util.Collections;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@@ -30,8 +31,11 @@ import java.util.Set;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; 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.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.TestdataFactory;
import org.eclipse.hawkbit.repository.test.util.WithUser; import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest; import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest;
@@ -46,6 +50,7 @@ import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.MvcResult;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.JsonPath;
import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Features;
@@ -72,8 +77,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
// create DisSet // create DisSet
final DistributionSet disSet = testdataFactory.createDistributionSetWithNoSoftwareModules("Eris", "560a"); final DistributionSet disSet = testdataFactory.createDistributionSetWithNoSoftwareModules("Eris", "560a");
final List<Long> smIDs = new ArrayList<>(); final List<Long> smIDs = new ArrayList<>();
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "Dysnomia ", "15,772", null, null); final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
sm = softwareManagement.createSoftwareModule(sm);
smIDs.add(sm.getId()); smIDs.add(sm.getId());
final JSONArray smList = new JSONArray(); final JSONArray smList = new JSONArray();
for (final Long smID : smIDs) { for (final Long smID : smIDs) {
@@ -88,10 +92,10 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final String[] knownTargetIds = new String[] { "1", "2" }; final String[] knownTargetIds = new String[] { "1", "2" };
final JSONArray list = new JSONArray(); final JSONArray list = new JSONArray();
for (final String targetId : knownTargetIds) { for (final String targetId : knownTargetIds) {
targetManagement.createTarget(entityFactory.generateTarget(targetId)); testdataFactory.createTarget(targetId);
list.put(new JSONObject().put("id", Long.valueOf(targetId))); list.put(new JSONObject().put("id", Long.valueOf(targetId)));
} }
deploymentManagement.assignDistributionSet(disSet.getId(), knownTargetIds[0]); assignDistributionSet(disSet.getId(), knownTargetIds[0]);
mvc.perform( mvc.perform(
post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedTargets") post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedTargets")
.contentType(MediaType.APPLICATION_JSON).content(list.toString())) .contentType(MediaType.APPLICATION_JSON).content(list.toString()))
@@ -104,8 +108,8 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
// to the target. // to the target.
mvc.perform(delete(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM/" mvc.perform(delete(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM/"
+ smIDs.get(0)).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) + smIDs.get(0)).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isLocked()) .andExpect(status().isForbidden())
.andExpect(jsonPath("$.errorCode", equalTo("hawkbit.server.error.entitiylocked"))); .andExpect(jsonPath("$.errorCode", equalTo("hawkbit.server.error.entityreadonly")));
} }
@Test @Test
@@ -115,8 +119,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
// create DisSet // create DisSet
final DistributionSet disSet = testdataFactory.createDistributionSetWithNoSoftwareModules("Mars", "686,980"); final DistributionSet disSet = testdataFactory.createDistributionSetWithNoSoftwareModules("Mars", "686,980");
final List<Long> smIDs = new ArrayList<>(); final List<Long> smIDs = new ArrayList<>();
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "Phobos", "0,3189", null, null); final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
sm = softwareManagement.createSoftwareModule(sm);
smIDs.add(sm.getId()); smIDs.add(sm.getId());
final JSONArray smList = new JSONArray(); final JSONArray smList = new JSONArray();
for (final Long smID : smIDs) { for (final Long smID : smIDs) {
@@ -131,11 +134,11 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final String[] knownTargetIds = new String[] { "1", "2" }; final String[] knownTargetIds = new String[] { "1", "2" };
final JSONArray list = new JSONArray(); final JSONArray list = new JSONArray();
for (final String targetId : knownTargetIds) { for (final String targetId : knownTargetIds) {
targetManagement.createTarget(entityFactory.generateTarget(targetId)); testdataFactory.createTarget(targetId);
list.put(new JSONObject().put("id", Long.valueOf(targetId))); list.put(new JSONObject().put("id", Long.valueOf(targetId)));
} }
// assign DisSet to target and test assignment // assign DisSet to target and test assignment
deploymentManagement.assignDistributionSet(disSet.getId(), knownTargetIds[0]); assignDistributionSet(disSet.getId(), knownTargetIds[0]);
mvc.perform( mvc.perform(
post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedTargets") post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedTargets")
.contentType(MediaType.APPLICATION_JSON).content(list.toString())) .contentType(MediaType.APPLICATION_JSON).content(list.toString()))
@@ -145,19 +148,14 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
.andExpect(jsonPath("$.total", equalTo(knownTargetIds.length))); .andExpect(jsonPath("$.total", equalTo(knownTargetIds.length)));
// Create another SM and post assignment // Create another SM and post assignment
final List<Long> smID2s = new ArrayList<>(); final SoftwareModule sm2 = testdataFactory.createSoftwareModuleApp();
SoftwareModule sm2 = entityFactory.generateSoftwareModule(appType, "Deimos", "1,262", null, null);
sm2 = softwareManagement.createSoftwareModule(sm2);
smID2s.add(sm2.getId());
final JSONArray smList2 = new JSONArray(); final JSONArray smList2 = new JSONArray();
for (final Long smID : smID2s) { smList2.put(new JSONObject().put("id", sm2.getId()));
smList2.put(new JSONObject().put("id", Long.valueOf(smID)));
}
mvc.perform(post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM") mvc.perform(post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM")
.contentType(MediaType.APPLICATION_JSON).content(smList2.toString())) .contentType(MediaType.APPLICATION_JSON).content(smList2.toString()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isLocked()) .andDo(MockMvcResultPrinter.print()).andExpect(status().isForbidden())
.andExpect(jsonPath("$.errorCode", equalTo("hawkbit.server.error.entitiylocked"))); .andExpect(jsonPath("$.errorCode", equalTo("hawkbit.server.error.entityreadonly")));
} }
@Test @Test
@@ -171,16 +169,8 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath("$.size", equalTo(disSet.getModules().size()))); .andExpect(jsonPath("$.size", equalTo(disSet.getModules().size())));
// create Software Modules // create Software Modules
final List<Long> smIDs = new ArrayList<>(); final List<Long> smIDs = Lists.newArrayList(testdataFactory.createSoftwareModuleOs().getId(),
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "Europa", "3,551", null, null); testdataFactory.createSoftwareModuleApp().getId());
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 JSONArray list = new JSONArray(); final JSONArray list = new JSONArray();
for (final Long smID : smIDs) { for (final Long smID : smIDs) {
list.put(new JSONObject().put("id", Long.valueOf(smID))); list.put(new JSONObject().put("id", Long.valueOf(smID)));
@@ -227,11 +217,11 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final String[] knownTargetIds = new String[] { "1", "2", "3", "4", "5" }; final String[] knownTargetIds = new String[] { "1", "2", "3", "4", "5" };
final JSONArray list = new JSONArray(); final JSONArray list = new JSONArray();
for (final String targetId : knownTargetIds) { for (final String targetId : knownTargetIds) {
targetManagement.createTarget(entityFactory.generateTarget(targetId)); testdataFactory.createTarget(targetId);
list.put(new JSONObject().put("id", Long.valueOf(targetId))); list.put(new JSONObject().put("id", Long.valueOf(targetId)));
} }
// assign already one target to DS // assign already one target to DS
deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetIds[0]); assignDistributionSet(createdDs.getId(), knownTargetIds[0]);
mvc.perform(post( mvc.perform(post(
MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets") MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets")
@@ -251,8 +241,8 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final String knownTargetId = "knownTargetId1"; final String knownTargetId = "knownTargetId1";
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1); final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next(); final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
targetManagement.createTarget(entityFactory.generateTarget(knownTargetId)); testdataFactory.createTarget(knownTargetId);
deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetId); assignDistributionSet(createdDs.getId(), knownTargetId);
mvc.perform(get( mvc.perform(get(
MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets")) MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets"))
@@ -278,15 +268,15 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final String knownTargetId = "knownTargetId1"; final String knownTargetId = "knownTargetId1";
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1); final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next(); 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 // create some dummy targets which are not assigned or installed
targetManagement.createTarget(entityFactory.generateTarget("dummy1")); testdataFactory.createTarget("dummy1");
targetManagement.createTarget(entityFactory.generateTarget("dummy2")); testdataFactory.createTarget("dummy2");
// assign knownTargetId to distribution set // assign knownTargetId to distribution set
deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetId); assignDistributionSet(createdDs.getId(), knownTargetId);
// make it in install state // make it in install state
testdataFactory.sendUpdateActionStatusToTargets(Lists.newArrayList(createTarget), Status.FINISHED, testdataFactory.sendUpdateActionStatusToTargets(Lists.newArrayList(createTarget), Status.FINISHED,
"some message"); Collections.singletonList("some message"));
mvc.perform(get( mvc.perform(get(
MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/installedTargets")) MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/installedTargets"))
@@ -302,11 +292,16 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1); final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next(); final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
targetFilterQueryManagement targetFilterQueryManagement.updateTargetFilterQueryAutoAssignDS(
.createTargetFilterQuery(entityFactory.generateTargetFilterQuery(knownFilterName, "x==y", createdDs)); targetFilterQueryManagement.createTargetFilterQuery(
entityFactory.targetFilterQuery().create().name(knownFilterName).query("x==y")).getId(),
createdDs.getId());
// create some dummy target filter queries // create some dummy target filter queries
targetFilterQueryManagement.createTargetFilterQuery(entityFactory.generateTargetFilterQuery("b", "x==y")); targetFilterQueryManagement
targetFilterQueryManagement.createTargetFilterQuery(entityFactory.generateTargetFilterQuery("c", "x==y")); .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() mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId()
+ "/autoAssignTargetFilters")).andExpect(status().isOk()).andExpect(jsonPath("$.size", equalTo(1))) + "/autoAssignTargetFilters")).andExpect(status().isOk()).andExpect(jsonPath("$.size", equalTo(1)))
@@ -334,14 +329,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next(); final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
final String query = "name==" + filterNamePrefix + "*"; final String query = "name==" + filterNamePrefix + "*";
// create target filter queries that should be found prepareTestFilters(filterNamePrefix, createdDs);
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"));
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId()
+ "/autoAssignTargetFilters").param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, query)) + "/autoAssignTargetFilters").param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, query))
@@ -358,20 +346,32 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next(); final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
final String query = "name==doesNotExist"; final String query = "name==doesNotExist";
// create target filter queries that should be found prepareTestFilters(filterNamePrefix, createdDs);
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"));
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId()
+ "/autoAssignTargetFilters").param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, query)) + "/autoAssignTargetFilters").param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, query))
.andExpect(status().isOk()).andExpect(jsonPath("$.size", equalTo(0))); .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 @Test
@Description("Ensures that DS in repository are listed with proper paging properties.") @Description("Ensures that DS in repository are listed with proper paging properties.")
public void getDistributionSetsWithoutAddtionalRequestParameters() throws Exception { public void getDistributionSetsWithoutAddtionalRequestParameters() throws Exception {
@@ -423,11 +423,8 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
.hasSize(0); .hasSize(0);
DistributionSet set = testdataFactory.createDistributionSet("one"); DistributionSet set = testdataFactory.createDistributionSet("one");
set.setRequiredMigrationStep(set.isRequiredMigrationStep()); set = distributionSetManagement.updateDistributionSet(entityFactory.distributionSet().update(set.getId())
set = distributionSetManagement.updateDistributionSet(set); .version("anotherVersion").requiredMigrationStep(true));
set.setVersion("anotherVersion");
set = distributionSetManagement.updateDistributionSet(set);
// load also lazy stuff // load also lazy stuff
set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()); set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId());
@@ -443,7 +440,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
equalTo("http://localhost/rest/v1/distributionsets/" + set.getId()))) equalTo("http://localhost/rest/v1/distributionsets/" + set.getId())))
.andExpect(jsonPath("$.content.[0].id", equalTo(set.getId().intValue()))) .andExpect(jsonPath("$.content.[0].id", equalTo(set.getId().intValue())))
.andExpect(jsonPath("$.content.[0].name", equalTo(set.getName()))) .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].description", equalTo(set.getDescription())))
.andExpect(jsonPath("$.content.[0].type", equalTo(set.getType().getKey()))) .andExpect(jsonPath("$.content.[0].type", equalTo(set.getType().getKey())))
.andExpect(jsonPath("$.content.[0].createdBy", equalTo(set.getCreatedBy()))) .andExpect(jsonPath("$.content.[0].createdBy", equalTo(set.getCreatedBy())))
@@ -457,7 +454,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
.andExpect(jsonPath("$.content.[0].modules.[?(@.type==" + appType.getKey() + ")].id", .andExpect(jsonPath("$.content.[0].modules.[?(@.type==" + appType.getKey() + ")].id",
contains(set.findFirstModuleByType(appType).getId().intValue()))) contains(set.findFirstModuleByType(appType).getId().intValue())))
.andExpect(jsonPath("$.content.[0].modules.[?(@.type==" + osType.getKey() + ")].id", .andExpect(jsonPath("$.content.[0].modules.[?(@.type==" + osType.getKey() + ")].id",
contains(set.findFirstModuleByType(osType).getId().intValue()))); contains(getOsModule(set).intValue())));
} }
@Test @Test
@@ -488,7 +485,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
.andExpect(jsonPath("$.modules.[?(@.type==" + appType.getKey() + ")].id", .andExpect(jsonPath("$.modules.[?(@.type==" + appType.getKey() + ")].id",
contains(set.findFirstModuleByType(appType).getId().intValue()))) contains(set.findFirstModuleByType(appType).getId().intValue())))
.andExpect(jsonPath("$.modules.[?(@.type==" + osType.getKey() + ")].id", .andExpect(jsonPath("$.modules.[?(@.type==" + osType.getKey() + ")].id",
contains(set.findFirstModuleByType(osType).getId().intValue()))); contains(getOsModule(set).intValue())));
} }
@@ -508,13 +505,9 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
DistributionSet two = testdataFactory.generateDistributionSet("two", "two", standardDsType, DistributionSet two = testdataFactory.generateDistributionSet("two", "two", standardDsType,
Lists.newArrayList(os, jvm, ah)); Lists.newArrayList(os, jvm, ah));
DistributionSet three = testdataFactory.generateDistributionSet("three", "three", standardDsType, DistributionSet three = testdataFactory.generateDistributionSet("three", "three", standardDsType,
Lists.newArrayList(os, jvm, ah)); Lists.newArrayList(os, jvm, ah), true);
three.setRequiredMigrationStep(true);
final List<DistributionSet> sets = new ArrayList<>(); final List<DistributionSet> sets = Lists.newArrayList(one, two, three);
sets.add(one);
sets.add(two);
sets.add(three);
final long current = System.currentTimeMillis(); final long current = System.currentTimeMillis();
@@ -640,8 +633,8 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
.hasSize(0); .hasSize(0);
final DistributionSet set = testdataFactory.createDistributionSet("one"); final DistributionSet set = testdataFactory.createDistributionSet("one");
targetManagement.createTarget(entityFactory.generateTarget("test")); testdataFactory.createTarget("test");
deploymentManagement.assignDistributionSet(set.getId(), "test"); assignDistributionSet(set.getId(), "test");
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)) assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
.hasSize(1); .hasSize(1);
@@ -670,12 +663,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)) assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
.hasSize(1); .hasSize(1);
final DistributionSet update = entityFactory.generateDistributionSet(); mvc.perform(put("/rest/v1/distributionsets/{dsId}", set.getId()).content("{\"version\":\"anotherVersion\"}")
update.setVersion("anotherVersion");
update.setName(null);
update.setType(standardDsType);
mvc.perform(put("/rest/v1/distributionsets/{dsId}", set.getId()).content(JsonBuilder.distributionSet(update))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
@@ -709,8 +697,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest()); .andExpect(status().isBadRequest());
final DistributionSet missingName = testdataFactory.generateDistributionSet("missingName"); final DistributionSet missingName = entityFactory.distributionSet().create().build();
missingName.setName(null);
mvc.perform( mvc.perform(
post("/rest/v1/distributionsets").content(JsonBuilder.distributionSets(Lists.newArrayList(missingName))) post("/rest/v1/distributionsets").content(JsonBuilder.distributionSets(Lists.newArrayList(missingName)))
.contentType(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON))
@@ -762,8 +749,10 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
.andExpect(jsonPath("[1]key", equalTo(knownKey2))) .andExpect(jsonPath("[1]key", equalTo(knownKey2)))
.andExpect(jsonPath("[1]value", equalTo(knownValue2))); .andExpect(jsonPath("[1]value", equalTo(knownValue2)));
final DistributionSetMetadata metaKey1 = distributionSetManagement.findOne(testDS, knownKey1); final DistributionSetMetadata metaKey1 = distributionSetManagement.findDistributionSetMetadata(testDS.getId(),
final DistributionSetMetadata metaKey2 = distributionSetManagement.findOne(testDS, knownKey2); knownKey1);
final DistributionSetMetadata metaKey2 = distributionSetManagement.findDistributionSetMetadata(testDS.getId(),
knownKey2);
assertThat(metaKey1.getValue()).isEqualTo(knownValue1); assertThat(metaKey1.getValue()).isEqualTo(knownValue1);
assertThat(metaKey2.getValue()).isEqualTo(knownValue2); assertThat(metaKey2.getValue()).isEqualTo(knownValue2);
@@ -778,8 +767,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final String updateValue = "valueForUpdate"; final String updateValue = "valueForUpdate";
final DistributionSet testDS = testdataFactory.createDistributionSet("one"); final DistributionSet testDS = testdataFactory.createDistributionSet("one");
distributionSetManagement.createDistributionSetMetadata( createDistributionSetMetadata(testDS.getId(), entityFactory.generateMetadata(knownKey, knownValue));
entityFactory.generateDistributionSetMetadata(testDS, knownKey, knownValue));
final JSONObject jsonObject = new JSONObject().put("key", knownKey).put("value", updateValue); final JSONObject jsonObject = new JSONObject().put("key", knownKey).put("value", updateValue);
@@ -789,7 +777,8 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("key", equalTo(knownKey))).andExpect(jsonPath("value", equalTo(updateValue))); .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); assertThat(assertDS.getValue()).isEqualTo(updateValue);
} }
@@ -802,14 +791,13 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final String knownValue = "knownValue"; final String knownValue = "knownValue";
final DistributionSet testDS = testdataFactory.createDistributionSet("one"); final DistributionSet testDS = testdataFactory.createDistributionSet("one");
distributionSetManagement.createDistributionSetMetadata( createDistributionSetMetadata(testDS.getId(), entityFactory.generateMetadata(knownKey, knownValue));
entityFactory.generateDistributionSetMetadata(testDS, knownKey, knownValue));
mvc.perform(delete("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey)) mvc.perform(delete("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
try { try {
distributionSetManagement.findOne(testDS, knownKey); distributionSetManagement.findDistributionSetMetadata(testDS.getId(), knownKey);
fail("expected EntityNotFoundException but didn't throw"); fail("expected EntityNotFoundException but didn't throw");
} catch (final EntityNotFoundException e) { } catch (final EntityNotFoundException e) {
// ok as expected // ok as expected
@@ -823,8 +811,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final String knownKey = "knownKey"; final String knownKey = "knownKey";
final String knownValue = "knownValue"; final String knownValue = "knownValue";
final DistributionSet testDS = testdataFactory.createDistributionSet("one"); final DistributionSet testDS = testdataFactory.createDistributionSet("one");
distributionSetManagement.createDistributionSetMetadata( createDistributionSetMetadata(testDS.getId(), entityFactory.generateMetadata(knownKey, knownValue));
entityFactory.generateDistributionSetMetadata(testDS, knownKey, knownValue));
mvc.perform(get("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey)) mvc.perform(get("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
@@ -842,9 +829,8 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final String knownValuePrefix = "knownValue"; final String knownValuePrefix = "knownValue";
final DistributionSet testDS = testdataFactory.createDistributionSet("one"); final DistributionSet testDS = testdataFactory.createDistributionSet("one");
for (int index = 0; index < totalMetadata; index++) { for (int index = 0; index < totalMetadata; index++) {
distributionSetManagement.createDistributionSetMetadata(entityFactory.generateDistributionSetMetadata( createDistributionSetMetadata(testDS.getId(),
distributionSetManagement.findDistributionSetById(testDS.getId()), knownKeyPrefix + index, entityFactory.generateMetadata(knownKeyPrefix + index, knownValuePrefix + index));
knownValuePrefix + index));
} }
mvc.perform(get("/rest/v1/distributionsets/{dsId}/metadata?offset=" + offsetParam + "&limit=" + limitParam, mvc.perform(get("/rest/v1/distributionsets/{dsId}/metadata?offset=" + offsetParam + "&limit=" + limitParam,
@@ -878,8 +864,8 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
public void filterDistributionSetComplete() throws Exception { public void filterDistributionSetComplete() throws Exception {
final int amount = 10; final int amount = 10;
testdataFactory.createDistributionSets(amount); testdataFactory.createDistributionSets(amount);
distributionSetManagement.createDistributionSet(entityFactory.generateDistributionSet("incomplete", "2", distributionSetManagement.createDistributionSet(
"incomplete", distributionSetManagement.findDistributionSetTypeByKey("os"), null)); entityFactory.distributionSet().create().name("incomplete").version("2").type("os"));
final String rsqlFindLikeDs1OrDs2 = "complete==" + Boolean.TRUE; final String rsqlFindLikeDs1OrDs2 = "complete==" + Boolean.TRUE;
@@ -895,21 +881,18 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1); final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next(); final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
// prepare targets // prepare targets
final String[] knownTargetIds = new String[] { "1", "2", "3", "4", "5" }; final Collection<String> knownTargetIds = Lists.newArrayList("1", "2", "3", "4", "5");
final JSONArray list = new JSONArray();
for (final String targetId : knownTargetIds) { knownTargetIds.forEach(controllerId -> targetManagement
targetManagement.createTarget(entityFactory.generateTarget(targetId)); .createTarget(entityFactory.target().create().controllerId(controllerId)));
list.put(new JSONObject().put("id", Long.valueOf(targetId)));
}
// assign already one target to DS // assign already one target to DS
deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetIds[0]); assignDistributionSet(createdDs.getId(), knownTargetIds.iterator().next());
final String rsqlFindTargetId1 = "controllerId==1"; final String rsqlFindTargetId1 = "controllerId==1";
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId()
+ "/assignedTargets?q=" + rsqlFindTargetId1).contentType(MediaType.APPLICATION_JSON) + "/assignedTargets?q=" + rsqlFindTargetId1).contentType(MediaType.APPLICATION_JSON))
.content(list.toString()))
.andExpect(status().isOk()).andExpect(jsonPath("total", equalTo(1))) .andExpect(status().isOk()).andExpect(jsonPath("total", equalTo(1)))
.andExpect(jsonPath("size", equalTo(1))).andExpect(jsonPath("content[0].controllerId", equalTo("1"))); .andExpect(jsonPath("size", equalTo(1))).andExpect(jsonPath("content[0].controllerId", equalTo("1")));
} }
@@ -922,9 +905,8 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
final String knownValuePrefix = "knownValue"; final String knownValuePrefix = "knownValue";
final DistributionSet testDS = testdataFactory.createDistributionSet("one"); final DistributionSet testDS = testdataFactory.createDistributionSet("one");
for (int index = 0; index < totalMetadata; index++) { for (int index = 0; index < totalMetadata; index++) {
distributionSetManagement.createDistributionSetMetadata(entityFactory.generateDistributionSetMetadata( createDistributionSetMetadata(testDS.getId(),
distributionSetManagement.findDistributionSetById(testDS.getId()), knownKeyPrefix + index, entityFactory.generateMetadata(knownKeyPrefix + index, knownValuePrefix + index));
knownValuePrefix + index));
} }
final String rsqlSearchValue1 = "value==knownValue1"; final String rsqlSearchValue1 = "value==knownValue1";
@@ -937,7 +919,7 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
private Set<DistributionSet> createDistributionSetsAlphabetical(final int amount) { private Set<DistributionSet> createDistributionSetsAlphabetical(final int amount) {
char character = 'a'; char character = 'a';
final Set<DistributionSet> created = new HashSet<>(); final Set<DistributionSet> created = Sets.newHashSetWithExpectedSize(amount);
for (int index = 0; index < amount; index++) { for (int index = 0; index < amount; index++) {
final String str = String.valueOf(character); final String str = String.valueOf(character);
created.add(testdataFactory.createDistributionSet(str)); created.add(testdataFactory.createDistributionSet(str));

View File

@@ -21,13 +21,13 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 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 java.util.List;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.model.DistributionSetType; 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.SoftwareModuleType;
import org.eclipse.hawkbit.repository.test.util.WithUser; import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest; import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest;
@@ -44,6 +44,7 @@ import com.jayway.jsonpath.JsonPath;
import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.allure.annotations.Stories; 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.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests.")
public void getDistributionSetTypes() throws Exception { public void getDistributionSetTypes() throws Exception {
DistributionSetType testType = distributionSetManagement.createDistributionSetType( DistributionSetType testType = distributionSetManagement
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")); .createDistributionSetType(entityFactory.distributionSetType().create().key("test123")
testType.setDescription("Desc1234"); .name("TestName123").description("Desc123").colour("col12"));
testType = distributionSetManagement.updateDistributionSetType(testType); testType = distributionSetManagement.updateDistributionSetType(
entityFactory.distributionSetType().update(testType.getId()).description("Desc1234"));
// 4 types overall (2 hawkbit tenant default, 1 test default and 1 // 4 types overall (2 hawkbit tenant default, 1 test default and 1
// generated in this test) // generated in this test)
@@ -99,10 +101,11 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests with sorting by KEY.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests with sorting by KEY.")
public void getDistributionSetTypesSortedByKey() throws Exception { public void getDistributionSetTypesSortedByKey() throws Exception {
DistributionSetType testType = distributionSetManagement.createDistributionSetType( DistributionSetType testType = distributionSetManagement
entityFactory.generateDistributionSetType("zzzzz", "TestName123", "Desc123")); .createDistributionSetType(entityFactory.distributionSetType().create().key("zzzzz").name("TestName123")
testType.setDescription("Desc1234"); .description("Desc123").colour("col12"));
testType = distributionSetManagement.updateDistributionSetType(testType); testType = distributionSetManagement.updateDistributionSetType(
entityFactory.distributionSetType().update(testType.getId()).description("Desc1234"));
// descending // descending
mvc.perform(get("/rest/v1/distributionsettypes").accept(MediaType.APPLICATION_JSON) mvc.perform(get("/rest/v1/distributionsettypes").accept(MediaType.APPLICATION_JSON)
@@ -138,35 +141,18 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes POST requests.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes POST requests.")
public void createDistributionSetTypes() throws JSONException, Exception { public void createDistributionSetTypes() throws JSONException, Exception {
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES); final List<DistributionSetType> types = createTestDistributionSetTestTypes();
final List<DistributionSetType> types = new ArrayList<>(); final MvcResult mvcResult = runPostDistributionSetType(types);
types.add(entityFactory.generateDistributionSetType("test1", "TestName1", "Desc1")
.addMandatoryModuleType(osType).addOptionalModuleType(runtimeType));
types.add(entityFactory.generateDistributionSetType("test2", "TestName2", "Desc2").addOptionalModuleType(osType)
.addOptionalModuleType(runtimeType).addOptionalModuleType(appType));
types.add(entityFactory.generateDistributionSetType("test3", "TestName3", "Desc3")
.addMandatoryModuleType(osType).addMandatoryModuleType(runtimeType));
final MvcResult mvcResult = mvc verifyCreatedDistributionSetTypes(mvcResult);
.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();
final DistributionSetType created1 = distributionSetManagement.findDistributionSetTypeByKey("test1"); @Step
final DistributionSetType created2 = distributionSetManagement.findDistributionSetTypeByKey("test2"); private void verifyCreatedDistributionSetTypes(final MvcResult mvcResult) throws UnsupportedEncodingException {
final DistributionSetType created3 = distributionSetManagement.findDistributionSetTypeByKey("test3"); 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.getMandatoryModuleTypes()).containsOnly(osType);
assertThat(created1.getOptionalModuleTypes()).containsOnly(runtimeType); assertThat(created1.getOptionalModuleTypes()).containsOnly(runtimeType);
@@ -206,12 +192,50 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(6); assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(6);
} }
@Step
private MvcResult runPostDistributionSetType(final List<DistributionSetType> 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<DistributionSetType> 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 @Test
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes POST requests.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes POST requests.")
public void addMandatoryModuleToDistributionSetType() throws JSONException, Exception { public void addMandatoryModuleToDistributionSetType() throws JSONException, Exception {
DistributionSetType testType = distributionSetManagement.createDistributionSetType( DistributionSetType testType = distributionSetManagement
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")); .createDistributionSetType(entityFactory.distributionSetType().create().key("test123")
.name("TestName123").description("Desc123").colour("col12"));
assertThat(testType.getOptLockRevision()).isEqualTo(1); assertThat(testType.getOptLockRevision()).isEqualTo(1);
mvc.perform(post("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes", testType.getId()) mvc.perform(post("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes", testType.getId())
@@ -229,8 +253,9 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes POST requests.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes POST requests.")
public void addOptionalModuleToDistributionSetType() throws JSONException, Exception { public void addOptionalModuleToDistributionSetType() throws JSONException, Exception {
DistributionSetType testType = distributionSetManagement.createDistributionSetType( DistributionSetType testType = distributionSetManagement
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")); .createDistributionSetType(entityFactory.distributionSetType().create().key("test123")
.name("TestName123").description("Desc123").colour("col12"));
assertThat(testType.getOptLockRevision()).isEqualTo(1); assertThat(testType.getOptLockRevision()).isEqualTo(1);
mvc.perform(post("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes", testType.getId()) mvc.perform(post("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes", testType.getId())
@@ -249,12 +274,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes GET requests.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes GET requests.")
public void getMandatoryModulesOfDistributionSetType() throws JSONException, Exception { public void getMandatoryModulesOfDistributionSetType() throws JSONException, Exception {
final DistributionSetType testType = distributionSetManagement.createDistributionSetType( final DistributionSetType testType = generateTestType();
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes", testType.getId()) mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes", testType.getId())
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
@@ -268,12 +288,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes GET requests.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes GET requests.")
public void getOptionalModulesOfDistributionSetType() throws JSONException, Exception { public void getOptionalModulesOfDistributionSetType() throws JSONException, Exception {
final DistributionSetType testType = distributionSetManagement.createDistributionSetType( final DistributionSetType testType = generateTestType();
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes", testType.getId()) mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes", testType.getId())
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
@@ -288,12 +303,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes/{ID} GET requests.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes/{ID} GET requests.")
public void getMandatoryModuleOfDistributionSetType() throws JSONException, Exception { public void getMandatoryModuleOfDistributionSetType() throws JSONException, Exception {
final DistributionSetType testType = distributionSetManagement.createDistributionSetType( final DistributionSetType testType = generateTestType();
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes/{smtId}", testType.getId(), mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes/{smtId}", testType.getId(),
osType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) osType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
@@ -306,16 +316,21 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
.andExpect(jsonPath("$.lastModifiedAt", equalTo(osType.getLastModifiedAt()))); .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 @Test
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes/{ID} GET requests.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes/{ID} GET requests.")
public void getOptionalModuleOfDistributionSetType() throws JSONException, Exception { public void getOptionalModuleOfDistributionSetType() throws JSONException, Exception {
final DistributionSetType testType = distributionSetManagement.createDistributionSetType( final DistributionSetType testType = generateTestType();
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes/{smtId}", testType.getId(), mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes/{smtId}", testType.getId(),
appType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) appType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
@@ -332,12 +347,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes/{ID} DELETE requests.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes/{ID} DELETE requests.")
public void removeMandatoryModuleToDistributionSetType() throws JSONException, Exception { public void removeMandatoryModuleToDistributionSetType() throws JSONException, Exception {
DistributionSetType testType = distributionSetManagement.createDistributionSetType( DistributionSetType testType = generateTestType();
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
mvc.perform(delete("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes/{smtId}", testType.getId(), mvc.perform(delete("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes/{smtId}", testType.getId(),
osType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) osType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
@@ -354,12 +364,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes/{ID} DELETE requests.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes/{ID} DELETE requests.")
public void removeOptionalModuleToDistributionSetType() throws JSONException, Exception { public void removeOptionalModuleToDistributionSetType() throws JSONException, Exception {
DistributionSetType testType = distributionSetManagement.createDistributionSetType( DistributionSetType testType = generateTestType();
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
mvc.perform(delete("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes/{smtId}", testType.getId(), mvc.perform(delete("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes/{smtId}", testType.getId(),
appType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) appType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
@@ -377,10 +382,11 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID} GET requests.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID} GET requests.")
public void getDistributionSetType() throws Exception { public void getDistributionSetType() throws Exception {
DistributionSetType testType = distributionSetManagement.createDistributionSetType( DistributionSetType testType = distributionSetManagement
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")); .createDistributionSetType(entityFactory.distributionSetType().create().key("test123")
testType.setDescription("Desc1234"); .name("TestName123").description("Desc123").colour("col12"));
testType = distributionSetManagement.updateDistributionSetType(testType); testType = distributionSetManagement.updateDistributionSetType(
entityFactory.distributionSetType().update(testType.getId()).description("Desc1234"));
mvc.perform(get("/rest/v1/distributionsettypes/{dstId}", testType.getId()).accept(MediaType.APPLICATION_JSON)) mvc.perform(get("/rest/v1/distributionsettypes/{dstId}", testType.getId()).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
@@ -396,8 +402,9 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/DistributionSetTypes/{ID} DELETE requests (hard delete scenario).") @Description("Checks the correct behaviour of /rest/v1/DistributionSetTypes/{ID} DELETE requests (hard delete scenario).")
public void deleteDistributionSetTypeUnused() throws Exception { public void deleteDistributionSetTypeUnused() throws Exception {
final DistributionSetType testType = distributionSetManagement.createDistributionSetType( final DistributionSetType testType = distributionSetManagement
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")); .createDistributionSetType(entityFactory.distributionSetType().create().key("test123")
.name("TestName123").description("Desc123").colour("col12"));
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES + 1); assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES + 1);
@@ -411,10 +418,12 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/DistributionSetTypes/{ID} DELETE requests (soft delete scenario).") @Description("Checks the correct behaviour of /rest/v1/DistributionSetTypes/{ID} DELETE requests (soft delete scenario).")
public void deleteDistributionSetTypeUsed() throws Exception { public void deleteDistributionSetTypeUsed() throws Exception {
final DistributionSetType testType = distributionSetManagement.createDistributionSetType( final DistributionSetType testType = distributionSetManagement
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")); .createDistributionSetType(entityFactory.distributionSetType().create().key("test123")
distributionSetManagement.createDistributionSet( .name("TestName123").description("Desc123").colour("col12"));
entityFactory.generateDistributionSet("sdfsd", "dsfsdf", "sdfsdf", testType, null));
distributionSetManagement.createDistributionSet(entityFactory.distributionSet().create().name("sdfsd")
.description("dsfsdf").version("1").type(testType));
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES + 1); assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES + 1);
assertThat(distributionSetManagement.countDistributionSetsAll()).isEqualTo(1); assertThat(distributionSetManagement.countDistributionSetsAll()).isEqualTo(1);
@@ -429,8 +438,9 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@Test @Test
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID} PUT requests.") @Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID} PUT requests.")
public void updateDistributionSetTypeOnlyDescriptionAndNameUntouched() throws Exception { public void updateDistributionSetTypeOnlyDescriptionAndNameUntouched() throws Exception {
final DistributionSetType testType = distributionSetManagement.createDistributionSetType( final DistributionSetType testType = distributionSetManagement
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")); .createDistributionSetType(entityFactory.distributionSetType().create().key("test123")
.name("TestName123").description("Desc123").colour("col"));
final String body = new JSONObject().put("id", testType.getId()).put("description", "foobardesc") final String body = new JSONObject().put("id", testType.getId()).put("description", "foobardesc")
.put("name", "nameShouldNotBeChanged").toString(); .put("name", "nameShouldNotBeChanged").toString();
@@ -488,11 +498,12 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@Test @Test
@Description("Ensures that the server is behaving as expected on invalid requests (wrong media type, wrong ID etc.).") @Description("Ensures that the server is behaving as expected on invalid requests (wrong media type, wrong ID etc.).")
public void invalidRequestsOnDistributionSetTypesResource() throws Exception { public void invalidRequestsOnDistributionSetTypesResource() throws Exception {
final DistributionSetType testType = distributionSetManagement.createDistributionSetType( // final DistributionSetType testDsType = distributionSetManagement
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")); // .createDistributionSetType(entityFactory.distributionSetType().create().key("test123")
// .name("TestName123").description("Desc123").colour("col"));
final SoftwareModuleType testSmType = softwareManagement.createSoftwareModuleType( final SoftwareModuleType testSmType = softwareManagement.createSoftwareModuleType(
entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5)); entityFactory.softwareModuleType().create().key("test123").name("TestName123"));
// DST does not exist // DST does not exist
mvc.perform(get("/rest/v1/distributionsettypes/12345678")).andDo(MockMvcResultPrinter.print()) mvc.perform(get("/rest/v1/distributionsettypes/12345678")).andDo(MockMvcResultPrinter.print())
@@ -532,10 +543,9 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
// Modules types at creation time invalid // Modules types at creation time invalid
final DistributionSetType testNewType = entityFactory.generateDistributionSetType("test123", "TestName123", final DistributionSetType testNewType = entityFactory.distributionSetType().create().key("test123")
"Desc123"); .name("TestName123").description("Desc123").colour("col").mandatory(Lists.newArrayList(osType.getId()))
testNewType.addMandatoryModuleType( .optional(Collections.emptyList()).build();
entityFactory.generateSoftwareModuleType("foo", "bar", "test", Integer.MAX_VALUE));
mvc.perform(post("/rest/v1/distributionsettypes") mvc.perform(post("/rest/v1/distributionsettypes")
.content(JsonBuilder.distributionSetTypes(Lists.newArrayList(testNewType))) .content(JsonBuilder.distributionSetTypes(Lists.newArrayList(testNewType)))
@@ -556,8 +566,8 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest()); .andExpect(status().isBadRequest());
final DistributionSetType toLongName = entityFactory.generateDistributionSetType("test123", final DistributionSetType toLongName = entityFactory.distributionSetType().create().key("test123")
RandomStringUtils.randomAscii(80), "Desc123"); .name(RandomStringUtils.randomAscii(80)).build();
mvc.perform(post("/rest/v1/distributionsettypes") mvc.perform(post("/rest/v1/distributionsettypes")
.content(JsonBuilder.distributionSetTypes(Lists.newArrayList(toLongName))) .content(JsonBuilder.distributionSetTypes(Lists.newArrayList(toLongName)))
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
@@ -580,10 +590,10 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
@Test @Test
@Description("Search erquest of software module types.") @Description("Search erquest of software module types.")
public void searchDistributionSetTypeRsql() throws Exception { public void searchDistributionSetTypeRsql() throws Exception {
final DistributionSetType testType = distributionSetManagement.createDistributionSetType( distributionSetManagement.createDistributionSetType(
entityFactory.generateDistributionSetType("test123", "TestName123", "Desc123")); entityFactory.distributionSetType().create().key("test123").name("TestName123"));
final DistributionSetType testType2 = distributionSetManagement.createDistributionSetType( distributionSetManagement.createDistributionSetType(
entityFactory.generateDistributionSetType("test1234", "TestName1234", "Desc123")); entityFactory.distributionSetType().create().key("test1234").name("TestName1234"));
final String rsqlFindLikeDs1OrDs2 = "name==TestName123,name==TestName1234"; final String rsqlFindLikeDs1OrDs2 = "name==TestName123,name==TestName1234";
@@ -597,9 +607,8 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegration
char character = 'a'; char character = 'a';
for (int index = 0; index < amount; index++) { for (int index = 0; index < amount; index++) {
final String str = String.valueOf(character); final String str = String.valueOf(character);
final SoftwareModule softwareModule = entityFactory.generateSoftwareModule(osType, str, str, str, str); softwareManagement.createSoftwareModule(
entityFactory.softwareModule().create().name(str).description(str).vendor(str).version(str));
softwareManagement.createSoftwareModule(softwareModule);
character++; character++;
} }
} }

View File

@@ -18,7 +18,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
@@ -45,6 +44,8 @@ import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import com.google.common.collect.Lists;
import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories; import ru.yandex.qatools.allure.annotations.Stories;
@@ -119,7 +120,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
@Test @Test
@Description("Testing that rollout can be created") @Description("Testing that rollout can be created")
public void createRollout() throws Exception { public void createRollout() throws Exception {
targetManagement.createTargets(testdataFactory.generateTargets(20, "target", "rollout")); testdataFactory.createTargets(20, "target", "rollout");
final DistributionSet dsA = testdataFactory.createDistributionSet(""); final DistributionSet dsA = testdataFactory.createDistributionSet("");
postRollout("rollout1", 10, dsA.getId(), "id==target*"); postRollout("rollout1", 10, dsA.getId(), "id==target*");
@@ -131,25 +132,18 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
final DistributionSet dsA = testdataFactory.createDistributionSet("ro"); final DistributionSet dsA = testdataFactory.createDistributionSet("ro");
final int amountTargets = 10; final int amountTargets = 10;
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "ro-target", "rollout")); testdataFactory.createTargets(amountTargets, "ro-target", "rollout");
List<RolloutGroup> rolloutGroups = new ArrayList<>(2); final float percentTargetsInGroup1 = 20;
final int percentTargetsInGroup1 = 20; final float percentTargetsInGroup2 = 100;
final int percentTargetsInGroup2 = 100;
RolloutGroup group1 = entityFactory.generateRolloutGroup(); final List<RolloutGroup> rolloutGroups = Lists.newArrayList(
group1.setName("Group1"); entityFactory.rolloutGroup().create().name("Group1").description("Group1desc")
group1.setDescription("Group1desc"); .targetPercentage(percentTargetsInGroup1).build(),
group1.setTargetPercentage(percentTargetsInGroup1); entityFactory.rolloutGroup().create().name("Group2").description("Group2desc")
rolloutGroups.add(group1); .targetPercentage(percentTargetsInGroup2).build());
RolloutGroup group2 = entityFactory.generateRolloutGroup(); final RolloutGroupConditions rolloutGroupConditions = new RolloutGroupConditionBuilder().withDefaults().build();
group2.setName("Group2");
group2.setDescription("Group2desc");
group2.setTargetPercentage(percentTargetsInGroup2);
rolloutGroups.add(group2);
RolloutGroupConditions rolloutGroupConditions = new RolloutGroupConditionBuilder().build();
mvc.perform(post("/rest/v1/rollouts") mvc.perform(post("/rest/v1/rollouts")
.content(JsonBuilder.rollout("rollout2", "desc", null, dsA.getId(), "id==ro-target*", .content(JsonBuilder.rollout("rollout2", "desc", null, dsA.getId(), "id==ro-target*",
@@ -161,41 +155,50 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
@Test @Test
@Description("Testing that no rollout with groups that have illegal percentages can be created") @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 DistributionSet dsA = testdataFactory.createDistributionSet("ro2");
final int amountTargets = 10; final int amountTargets = 10;
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "ro-target", "rollout")); testdataFactory.createTargets(amountTargets, "ro-target", "rollout");
List<RolloutGroup> rolloutGroups = new ArrayList<>(2); final List<RolloutGroup> rolloutGroups = Lists.newArrayList(
entityFactory.rolloutGroup().create().name("Group1").description("Group1desc").targetPercentage(0F)
.build(),
entityFactory.rolloutGroup().create().name("Group2").description("Group2desc").targetPercentage(100F)
.build());
RolloutGroup group1 = entityFactory.generateRolloutGroup(); final RolloutGroupConditions rolloutGroupConditions = new RolloutGroupConditionBuilder().withDefaults().build();
group1.setName("Group1");
group1.setDescription("Group1desc");
group1.setTargetPercentage(0);
rolloutGroups.add(group1);
RolloutGroup group2 = entityFactory.generateRolloutGroup();
group2.setName("Group2");
group2.setDescription("Group2desc");
group2.setTargetPercentage(100);
rolloutGroups.add(group2);
RolloutGroupConditions rolloutGroupConditions = new RolloutGroupConditionBuilder().build();
mvc.perform(post("/rest/v1/rollouts") mvc.perform(post("/rest/v1/rollouts")
.content(JsonBuilder.rollout("rollout4", "desc", null, dsA.getId(), "id==ro-target*", .content(JsonBuilder.rollout("rollout4", "desc", null, dsA.getId(), "id==ro-target*",
rolloutGroupConditions, rolloutGroups)) rolloutGroupConditions, rolloutGroups))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .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"))); .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<RolloutGroup> 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") mvc.perform(post("/rest/v1/rollouts")
.content(JsonBuilder.rollout("rollout4", "desc", null, dsA.getId(), "id==ro-target*", .content(JsonBuilder.rollout("rollout4", "desc", null, dsA.getId(), "id==ro-target*",
rolloutGroupConditions, rolloutGroups)) rolloutGroupConditions, rolloutGroups))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .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"))); .andExpect(jsonPath("$.errorCode", equalTo("hawkbit.server.error.repo.constraintViolation")));
} }
@@ -213,7 +216,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void rolloutPagedListContainsAllRollouts() throws Exception { public void rolloutPagedListContainsAllRollouts() throws Exception {
final DistributionSet dsA = testdataFactory.createDistributionSet(""); final DistributionSet dsA = testdataFactory.createDistributionSet("");
targetManagement.createTargets(testdataFactory.generateTargets(20, "target", "rollout")); testdataFactory.createTargets(20, "target", "rollout");
// setup - create 2 rollouts // setup - create 2 rollouts
postRollout("rollout1", 10, dsA.getId(), "id==target*"); postRollout("rollout1", 10, dsA.getId(), "id==target*");
@@ -240,7 +243,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void rolloutPagedListIsLimitedToQueryParam() throws Exception { public void rolloutPagedListIsLimitedToQueryParam() throws Exception {
final DistributionSet dsA = testdataFactory.createDistributionSet(""); final DistributionSet dsA = testdataFactory.createDistributionSet("");
targetManagement.createTargets(testdataFactory.generateTargets(20, "target", "rollout")); testdataFactory.createTargets(20, "target", "rollout");
// setup - create 2 rollouts // setup - create 2 rollouts
postRollout("rollout1", 10, dsA.getId(), "id==target*"); postRollout("rollout1", 10, dsA.getId(), "id==target*");
@@ -259,7 +262,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void retrieveRolloutGroupsForSpecificRollout() throws Exception { public void retrieveRolloutGroupsForSpecificRollout() throws Exception {
// setup // setup
final int amountTargets = 20; final int amountTargets = 20;
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); testdataFactory.createTargets(amountTargets, "rollout", "rollout");
final DistributionSet dsA = testdataFactory.createDistributionSet(""); final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout' // create rollout including the created targets with prefix 'rollout'
@@ -281,7 +284,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void startingRolloutSwitchesIntoRunningState() throws Exception { public void startingRolloutSwitchesIntoRunningState() throws Exception {
// setup // setup
final int amountTargets = 20; final int amountTargets = 20;
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); testdataFactory.createTargets(amountTargets, "rollout", "rollout");
final DistributionSet dsA = testdataFactory.createDistributionSet(""); final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout' // create rollout including the created targets with prefix 'rollout'
@@ -312,7 +315,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void pausingRolloutSwitchesIntoPausedState() throws Exception { public void pausingRolloutSwitchesIntoPausedState() throws Exception {
// setup // setup
final int amountTargets = 20; final int amountTargets = 20;
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); testdataFactory.createTargets(amountTargets, "rollout", "rollout");
final DistributionSet dsA = testdataFactory.createDistributionSet(""); final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout' // create rollout including the created targets with prefix 'rollout'
@@ -341,7 +344,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void resumingRolloutSwitchesIntoRunningState() throws Exception { public void resumingRolloutSwitchesIntoRunningState() throws Exception {
// setup // setup
final int amountTargets = 20; final int amountTargets = 20;
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); testdataFactory.createTargets(amountTargets, "rollout", "rollout");
final DistributionSet dsA = testdataFactory.createDistributionSet(""); final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout' // create rollout including the created targets with prefix 'rollout'
@@ -374,7 +377,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void startingAlreadyStartedRolloutReturnsBadRequest() throws Exception { public void startingAlreadyStartedRolloutReturnsBadRequest() throws Exception {
// setup // setup
final int amountTargets = 20; final int amountTargets = 20;
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); testdataFactory.createTargets(amountTargets, "rollout", "rollout");
final DistributionSet dsA = testdataFactory.createDistributionSet(""); final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout' // create rollout including the created targets with prefix 'rollout'
@@ -398,7 +401,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void resumingNotStartedRolloutReturnsBadRequest() throws Exception { public void resumingNotStartedRolloutReturnsBadRequest() throws Exception {
// setup // setup
final int amountTargets = 20; final int amountTargets = 20;
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); testdataFactory.createTargets(amountTargets, "rollout", "rollout");
final DistributionSet dsA = testdataFactory.createDistributionSet(""); final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout' // create rollout including the created targets with prefix 'rollout'
@@ -415,7 +418,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void startingRolloutFirstRolloutGroupIsInRunningState() throws Exception { public void startingRolloutFirstRolloutGroupIsInRunningState() throws Exception {
// setup // setup
final int amountTargets = 10; final int amountTargets = 10;
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); testdataFactory.createTargets(amountTargets, "rollout", "rollout");
final DistributionSet dsA = testdataFactory.createDistributionSet(""); final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout' // create rollout including the created targets with prefix 'rollout'
@@ -443,7 +446,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void retrieveSingleRolloutGroup() throws Exception { public void retrieveSingleRolloutGroup() throws Exception {
// setup // setup
final int amountTargets = 10; final int amountTargets = 10;
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); testdataFactory.createTargets(amountTargets, "rollout", "rollout");
final DistributionSet dsA = testdataFactory.createDistributionSet(""); final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout' // create rollout including the created targets with prefix 'rollout'
@@ -466,7 +469,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void retrieveTargetsFromRolloutGroup() throws Exception { public void retrieveTargetsFromRolloutGroup() throws Exception {
// setup // setup
final int amountTargets = 10; final int amountTargets = 10;
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); testdataFactory.createTargets(amountTargets, "rollout", "rollout");
final DistributionSet dsA = testdataFactory.createDistributionSet(""); final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout' // create rollout including the created targets with prefix 'rollout'
@@ -488,8 +491,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void retrieveTargetsFromRolloutGroupWithQuery() throws Exception { public void retrieveTargetsFromRolloutGroupWithQuery() throws Exception {
// setup // setup
final int amountTargets = 10; final int amountTargets = 10;
final List<Target> targets = targetManagement final List<Target> targets = testdataFactory.createTargets(amountTargets, "rollout", "rollout");
.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = testdataFactory.createDistributionSet(""); final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout' // create rollout including the created targets with prefix 'rollout'
@@ -513,7 +515,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void retrieveTargetsFromRolloutGroupAfterRolloutIsStarted() throws Exception { public void retrieveTargetsFromRolloutGroupAfterRolloutIsStarted() throws Exception {
// setup // setup
final int amountTargets = 10; final int amountTargets = 10;
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); testdataFactory.createTargets(amountTargets, "rollout", "rollout");
final DistributionSet dsA = testdataFactory.createDistributionSet(""); final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout' // create rollout including the created targets with prefix 'rollout'
@@ -540,7 +542,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void startingRolloutSwitchesIntoRunningStateAsync() throws Exception { public void startingRolloutSwitchesIntoRunningStateAsync() throws Exception {
final int amountTargets = 1000; final int amountTargets = 1000;
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); testdataFactory.createTargets(amountTargets, "rollout", "rollout");
final DistributionSet dsA = testdataFactory.createDistributionSet(""); final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout' // create rollout including the created targets with prefix 'rollout'
@@ -554,8 +556,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
rolloutManagement.checkStartingRollouts(0); rolloutManagement.checkStartingRollouts(0);
// check if running // check if running
assertThat(doWithTimeout(() -> getRollout(rollout.getId()), result -> success(result), 60_000, 100)) assertThat(doWithTimeout(() -> getRollout(rollout.getId()), this::success, 60_000, 100)).isNotNull();
.isNotNull();
} }
@Test @Test
@@ -566,10 +567,10 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
final int amountTargetsRollout2 = 25; final int amountTargetsRollout2 = 25;
final int amountTargetsRollout3 = 25; final int amountTargetsRollout3 = 25;
final int amountTargetsOther = 25; final int amountTargetsOther = 25;
targetManagement.createTargets(testdataFactory.generateTargets(amountTargetsRollout1, "rollout1", "rollout1")); testdataFactory.createTargets(amountTargetsRollout1, "rollout1", "rollout1");
targetManagement.createTargets(testdataFactory.generateTargets(amountTargetsRollout2, "rollout2", "rollout2")); testdataFactory.createTargets(amountTargetsRollout2, "rollout2", "rollout2");
targetManagement.createTargets(testdataFactory.generateTargets(amountTargetsRollout3, "rollout3", "rollout3")); testdataFactory.createTargets(amountTargetsRollout3, "rollout3", "rollout3");
targetManagement.createTargets(testdataFactory.generateTargets(amountTargetsOther, "other1", "other1")); testdataFactory.createTargets(amountTargetsOther, "other1", "other1");
final DistributionSet dsA = testdataFactory.createDistributionSet(""); final DistributionSet dsA = testdataFactory.createDistributionSet("");
createRollout("rollout1", 5, dsA.getId(), "controllerId==rollout1*"); createRollout("rollout1", 5, dsA.getId(), "controllerId==rollout1*");
@@ -600,7 +601,7 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
public void retrieveRolloutGroupsForSpecificRolloutWithRSQLParam() throws Exception { public void retrieveRolloutGroupsForSpecificRolloutWithRSQLParam() throws Exception {
// setup // setup
final int amountTargets = 20; final int amountTargets = 20;
targetManagement.createTargets(testdataFactory.generateTargets(amountTargets, "rollout", "rollout")); testdataFactory.createTargets(amountTargets, "rollout", "rollout");
final DistributionSet dsA = testdataFactory.createDistributionSet(""); final DistributionSet dsA = testdataFactory.createDistributionSet("");
// create rollout including the created targets with prefix 'rollout' // create rollout including the created targets with prefix 'rollout'
@@ -667,22 +668,20 @@ public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest {
final String targetFilterQuery) throws Exception { final String targetFilterQuery) throws Exception {
mvc.perform(post("/rest/v1/rollouts") mvc.perform(post("/rest/v1/rollouts")
.content(JsonBuilder.rollout(name, "desc", groupSize, distributionSetId, targetFilterQuery, .content(JsonBuilder.rollout(name, "desc", groupSize, distributionSetId, targetFilterQuery,
new RolloutGroupConditionBuilder().build())) new RolloutGroupConditionBuilder().withDefaults().build()))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated()).andReturn(); .andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated()).andReturn();
} }
private Rollout createRollout(final String name, final int amountGroups, final long distributionSetId, private Rollout createRollout(final String name, final int amountGroups, final long distributionSetId,
final String targetFilterQuery) { final String targetFilterQuery) {
Rollout rollout = entityFactory.generateRollout(); final Rollout rollout = rolloutManagement.createRollout(
rollout.setDistributionSet(distributionSetManagement.findDistributionSetById(distributionSetId)); entityFactory.rollout().create().name(name).set(distributionSetId).targetFilterQuery(targetFilterQuery),
rollout.setName(name); amountGroups, new RolloutGroupConditionBuilder().withDefaults()
rollout.setTargetFilterQuery(targetFilterQuery); .successCondition(RolloutGroupSuccessCondition.THRESHOLD, "100").build());
rollout = rolloutManagement.createRollout(rollout, amountGroups, new RolloutGroupConditionBuilder()
.successCondition(RolloutGroupSuccessCondition.THRESHOLD, "100").build());
// Run here, because Scheduler is disabled during tests // Run here, because Scheduler is disabled during tests
rolloutManagement.fillRolloutGroupsWithTargets(rolloutManagement.findRolloutById(rollout.getId())); rolloutManagement.fillRolloutGroupsWithTargets(rollout.getId());
return rolloutManagement.findRolloutById(rollout.getId()); return rolloutManagement.findRolloutById(rollout.getId());
} }

View File

@@ -28,7 +28,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@@ -37,6 +36,7 @@ import org.apache.commons.lang3.RandomStringUtils;
import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact; import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; 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.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
@@ -91,16 +91,8 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
final String updateVendor = "newVendor1"; final String updateVendor = "newVendor1";
final String updateDescription = "newDescription1"; final String updateDescription = "newDescription1";
softwareManagement SoftwareModule sm = softwareManagement.createSoftwareModule(entityFactory.softwareModule().create().type(osType)
.createSoftwareModule(entityFactory.generateSoftwareModule(appType, "agent-hub", "1.0.1", null, "")); .name(knownSWName).version(knownSWVersion).description(knownSWDescription).vendor(knownSWVendor));
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);
assertThat(sm.getName()).as("Wrong name of the software module").isEqualTo(knownSWName); assertThat(sm.getName()).as("Wrong name of the software module").isEqualTo(knownSWName);
@@ -120,13 +112,18 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
.andExpect(jsonPath("$.description", equalTo(updateDescription))) .andExpect(jsonPath("$.description", equalTo(updateDescription)))
.andExpect(jsonPath("$.name", equalTo(knownSWName))).andReturn(); .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 @Test
@Description("Tests the uppload of an artifact binary. The upload is executed and the content checked in the repository for completenes.") @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 { public void uploadArtifact() throws Exception {
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
sm = softwareManagement.createSoftwareModule(sm);
// create test file // create test file
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes(); final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
@@ -191,8 +188,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(0); assertThat(artifactManagement.countArtifactsAll()).isEqualTo(0);
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
sm = softwareManagement.createSoftwareModule(sm);
final MockMultipartFile file = new MockMultipartFile("file", "orig", null, new byte[0]); final MockMultipartFile file = new MockMultipartFile("file", "orig", null, new byte[0]);
@@ -204,8 +200,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
@Test @Test
@Description("Verfies that the system does not accept identical artifacts uploads for the same software module. Expected response: CONFLICT") @Description("Verfies that the system does not accept identical artifacts uploads for the same software module. Expected response: CONFLICT")
public void duplicateUploadArtifact() throws Exception { public void duplicateUploadArtifact() throws Exception {
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
sm = softwareManagement.createSoftwareModule(sm);
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes(); final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
final String md5sum = HashGeneratorUtils.generateMD5(random); final String md5sum = HashGeneratorUtils.generateMD5(random);
@@ -226,8 +221,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
@Test @Test
@Description("verfies that option to upload artifacts with a custom defined by metadata, i.e. not the file name of the binary itself.") @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 { public void uploadArtifactWithCustomName() throws Exception {
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
sm = softwareManagement.createSoftwareModule(sm);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(0); assertThat(artifactManagement.countArtifactsAll()).isEqualTo(0);
// create test file // create test file
@@ -253,8 +247,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
@Test @Test
@Description("Verfies that the system refuses upload of an artifact where the provided hash sums do not match. Expected result: BAD REQUEST") @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 { public void uploadArtifactWithHashCheck() throws Exception {
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
sm = softwareManagement.createSoftwareModule(sm);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(0); assertThat(artifactManagement.countArtifactsAll()).isEqualTo(0);
// create test file // create test file
@@ -297,8 +290,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
@Test @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.") @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 { public void downloadArtifact() throws Exception {
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
sm = softwareManagement.createSoftwareModule(sm);
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes(); final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
@@ -332,8 +324,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
@Description("Verifies the listing of one defined artifact assigned to a given software module. That includes the artifact metadata and download links.") @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 { public void getArtifact() throws Exception {
// prepare data for test // prepare data for test
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
sm = softwareManagement.createSoftwareModule(sm);
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes(); final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), sm.getId(), final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), sm.getId(),
@@ -358,8 +349,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
@Test @Test
@Description("Verifies the listing of all artifacts assigned to a software module. That includes the artifact metadata and download links.") @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 { public void getArtifacts() throws Exception {
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
sm = softwareManagement.createSoftwareModule(sm);
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes(); final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
@@ -399,8 +389,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes(); final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
final MockMultipartFile file = new MockMultipartFile("file", "orig", null, random); final MockMultipartFile file = new MockMultipartFile("file", "orig", null, random);
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
sm = softwareManagement.createSoftwareModule(sm);
// no artifact available // no artifact available
mvc.perform(get("/rest/v1/softwaremodules/{smId}/artifacts/1234567/download", sm.getId())) mvc.perform(get("/rest/v1/softwaremodules/{smId}/artifacts/1234567/download", sm.getId()))
@@ -432,8 +421,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
@Test @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.") @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 { public void invalidRequestsOnSoftwaremodulesResource() throws Exception {
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
sm = softwareManagement.createSoftwareModule(sm);
final List<SoftwareModule> modules = Lists.newArrayList(sm); final List<SoftwareModule> modules = Lists.newArrayList(sm);
@@ -458,8 +446,8 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest()); .andExpect(status().isBadRequest());
final SoftwareModule toLongName = entityFactory.generateSoftwareModule(osType, final SoftwareModule toLongName = entityFactory.softwareModule().create().type(osType)
RandomStringUtils.randomAscii(80), "version 1", null, null); .name(RandomStringUtils.randomAscii(80)).build();
mvc.perform( mvc.perform(
post("/rest/v1/softwaremodules").content(JsonBuilder.softwareModules(Lists.newArrayList(toLongName))) post("/rest/v1/softwaremodules").content(JsonBuilder.softwareModules(Lists.newArrayList(toLongName)))
.contentType(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON))
@@ -525,25 +513,17 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Test retrieval of all software modules the user has access to.") @Description("Test retrieval of all software modules the user has access to.")
public void getSoftwareModules() throws Exception { public void getSoftwareModules() throws Exception {
SoftwareModule os = entityFactory.generateSoftwareModule(osType, "name1", "version1", "description1", final SoftwareModule os = testdataFactory.createSoftwareModuleOs();
"vendor1"); final SoftwareModule app = testdataFactory.createSoftwareModuleApp();
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);
mvc.perform(get("/rest/v1/softwaremodules").accept(MediaType.APPLICATION_JSON)) mvc.perform(get("/rest/v1/softwaremodules").accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].name", contains("name1"))) .andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].name", contains(os.getName())))
.andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].version", contains("version1"))) .andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].version", contains(os.getVersion())))
.andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].description", contains("description1"))) .andExpect(
.andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].vendor", contains("vendor1"))) 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() + ")].type", contains("os")))
.andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].createdBy", contains("uploadTester"))) .andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].createdBy", contains("uploadTester")))
.andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].createdAt", contains(os.getCreatedAt()))) .andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].createdAt", contains(os.getCreatedAt())))
@@ -556,121 +536,83 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
.andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")]._links.metadata.href", .andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")]._links.metadata.href",
contains("http://localhost/rest/v1/softwaremodules/" + os.getId() contains("http://localhost/rest/v1/softwaremodules/" + os.getId()
+ "/metadata?offset=0&limit=50"))) + "/metadata?offset=0&limit=50")))
.andExpect(jsonPath("$.content.[?(@.id==" + jvm.getId() + ")].name", contains("name1"))) .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")].name", contains(app.getName())))
.andExpect(jsonPath("$.content.[?(@.id==" + jvm.getId() + ")].version", contains("version1"))) .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")].version", contains(app.getVersion())))
.andExpect(jsonPath("$.content.[?(@.id==" + jvm.getId() + ")].description", contains("description1"))) .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")].description",
.andExpect(jsonPath("$.content.[?(@.id==" + jvm.getId() + ")].vendor", contains("vendor1"))) contains(app.getDescription())))
.andExpect(jsonPath("$.content.[?(@.id==" + jvm.getId() + ")].type", contains("runtime"))) .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")].vendor", contains(app.getVendor())))
.andExpect(jsonPath("$.content.[?(@.id==" + jvm.getId() + ")].createdBy", contains("uploadTester"))) .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")].type", contains("application")))
.andExpect(jsonPath("$.content.[?(@.id==" + jvm.getId() + ")].createdAt", contains(jvm.getCreatedAt()))) .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")].createdBy", contains("uploadTester")))
.andExpect(jsonPath("$.content.[?(@.id==" + jvm.getId() + ")]._links.type.href", .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")].createdAt", contains(app.getCreatedAt())))
contains("http://localhost/rest/v1/softwaremoduletypes/" + runtimeType.getId()))) .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")]._links.artifacts.href",
.andExpect(jsonPath("$.content.[?(@.id==" + jvm.getId() + ")]._links.self.href", contains("http://localhost/rest/v1/softwaremodules/" + app.getId() + "/artifacts")))
contains("http://localhost/rest/v1/softwaremodules/" + jvm.getId()))) .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")]._links.metadata.href",
.andExpect(jsonPath("$.content.[?(@.id==" + jvm.getId() + ")]._links.artifacts.href", contains("http://localhost/rest/v1/softwaremodules/" + app.getId()
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"))) + "/metadata?offset=0&limit=50")))
.andExpect(jsonPath("$.content.[?(@.id==" + ah.getId() + ")].name", contains("name1"))) .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")]._links.type.href",
.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()
+ "/metadata?offset=0&limit=50")))
.andExpect(jsonPath("$.content.[?(@.id==" + ah.getId() + ")]._links.type.href",
contains("http://localhost/rest/v1/softwaremoduletypes/" + appType.getId()))) contains("http://localhost/rest/v1/softwaremoduletypes/" + appType.getId())))
.andExpect(jsonPath("$.content.[?(@.id==" + ah.getId() + ")]._links.self.href", .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")]._links.self.href",
contains("http://localhost/rest/v1/softwaremodules/" + ah.getId()))); 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 @Test
@Description("Test the various filter parameters, e.g. filter by name or type of the module.") @Description("Test the various filter parameters, e.g. filter by name or type of the module.")
public void getSoftwareModulesWithFilterParameters() throws Exception { public void getSoftwareModulesWithFilterParameters() throws Exception {
SoftwareModule os1 = entityFactory.generateSoftwareModule(osType, "osName1", "1.0.0", "description1", final SoftwareModule os1 = testdataFactory.createSoftwareModuleOs("1");
"vendor1"); final SoftwareModule app1 = testdataFactory.createSoftwareModuleApp("1");
os1 = softwareManagement.createSoftwareModule(os1); testdataFactory.createSoftwareModuleOs("2");
final SoftwareModule app2 = testdataFactory.createSoftwareModuleApp("2");
SoftwareModule jvm1 = entityFactory.generateSoftwareModule(runtimeType, "runtimeName1", "2.0.0", "description1", assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(4);
"vendor1");
jvm1 = softwareManagement.createSoftwareModule(jvm1);
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);
// only by name, only one exists per name // 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()) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.content.[?(@.id==" + os1.getId() + ")].name", contains("osName1"))) .andExpect(jsonPath("$.content.[?(@.id==" + os1.getId() + ")].name", contains(os1.getName())))
.andExpect(jsonPath("$.content.[?(@.id==" + os1.getId() + ")].version", contains("1.0.0"))) .andExpect(jsonPath("$.content.[?(@.id==" + os1.getId() + ")].version", contains(os1.getVersion())))
.andExpect(jsonPath("$.content.[?(@.id==" + os1.getId() + ")].description", contains("description1"))) .andExpect(jsonPath("$.content.[?(@.id==" + os1.getId() + ")].description",
.andExpect(jsonPath("$.content.[?(@.id==" + os1.getId() + ")].vendor", contains("vendor1"))) 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.[?(@.id==" + os1.getId() + ")].type", contains("os")))
.andExpect(jsonPath("$.content", hasSize(1))).andExpect(jsonPath("$.total", equalTo(1))); .andExpect(jsonPath("$.content", hasSize(1))).andExpect(jsonPath("$.total", equalTo(1)));
// by type, 2 software modules per type exists // by type, 2 software modules per type exists
mvc.perform(get("/rest/v1/softwaremodules?q=type==application").accept(MediaType.APPLICATION_JSON)) mvc.perform(get("/rest/v1/softwaremodules?q=type==" + Constants.SMT_DEFAULT_APP_KEY)
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.content.[?(@.id==" + ah1.getId() + ")].name", contains("appName1"))) .andExpect(jsonPath("$.content.[?(@.id==" + app1.getId() + ")].name", contains(app1.getName())))
.andExpect(jsonPath("$.content.[?(@.id==" + ah1.getId() + ")].version", contains("3.0.0"))) .andExpect(jsonPath("$.content.[?(@.id==" + app1.getId() + ")].version", contains(app1.getVersion())))
.andExpect(jsonPath("$.content.[?(@.id==" + ah1.getId() + ")].description", contains("description1"))) .andExpect(jsonPath("$.content.[?(@.id==" + app1.getId() + ")].description",
.andExpect(jsonPath("$.content.[?(@.id==" + ah1.getId() + ")].vendor", contains("vendor1"))) contains(app1.getDescription())))
.andExpect(jsonPath("$.content.[?(@.id==" + ah1.getId() + ")].type", contains("application"))) .andExpect(jsonPath("$.content.[?(@.id==" + app1.getId() + ")].vendor", contains(app1.getVendor())))
.andExpect(jsonPath("$.content.[?(@.id==" + ah2.getId() + ")].name", contains("appName2"))) .andExpect(jsonPath("$.content.[?(@.id==" + app1.getId() + ")].type",
.andExpect(jsonPath("$.content.[?(@.id==" + ah2.getId() + ")].version", contains("3.0.1"))) contains(Constants.SMT_DEFAULT_APP_KEY)))
.andExpect(jsonPath("$.content.[?(@.id==" + ah2.getId() + ")].description", contains("description2"))) .andExpect(jsonPath("$.content.[?(@.id==" + app2.getId() + ")].name", contains(app2.getName())))
.andExpect(jsonPath("$.content.[?(@.id==" + ah2.getId() + ")].vendor", contains("vendor2"))) .andExpect(jsonPath("$.content.[?(@.id==" + app2.getId() + ")].version", contains(app2.getVersion())))
.andExpect(jsonPath("$.content.[?(@.id==" + ah2.getId() + ")].type", contains("application"))) .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))); .andExpect(jsonPath("$.content", hasSize(2))).andExpect(jsonPath("$.total", equalTo(2)));
// by type and version=2.0.0 -> only one result // 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()) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.content.[?(@.id==" + jvm1.getId() + ")].name", contains("runtimeName1"))) .andExpect(jsonPath("$.content.[?(@.id==" + app1.getId() + ")].name", contains(app1.getName())))
.andExpect(jsonPath("$.content.[?(@.id==" + jvm1.getId() + ")].version", contains("2.0.0"))) .andExpect(jsonPath("$.content.[?(@.id==" + app1.getId() + ")].version", contains(app1.getVersion())))
.andExpect(jsonPath("$.content.[?(@.id==" + jvm1.getId() + ")].description", contains("description1"))) .andExpect(jsonPath("$.content.[?(@.id==" + app1.getId() + ")].description",
.andExpect(jsonPath("$.content.[?(@.id==" + jvm1.getId() + ")].vendor", contains("vendor1"))) 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))); .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 @Test
@@ -693,16 +635,16 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Tests GET request on /rest/v1/softwaremodules/{smId}.") @Description("Tests GET request on /rest/v1/softwaremodules/{smId}.")
public void getSoftwareModule() throws Exception { public void getSoftwareModule() throws Exception {
SoftwareModule os = entityFactory.generateSoftwareModule(osType, "name1", "version1", "description1", final SoftwareModule os = testdataFactory.createSoftwareModuleOs();
"vendor1");
os = softwareManagement.createSoftwareModule(os);
mvc.perform(get("/rest/v1/softwaremodules/{smId}", os.getId()).accept(MediaType.APPLICATION_JSON)) mvc.perform(get("/rest/v1/softwaremodules/{smId}", os.getId()).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.name", equalTo("name1"))).andExpect(jsonPath("$.version", equalTo("version1"))) .andExpect(jsonPath("$.name", equalTo(os.getName())))
.andExpect(jsonPath("$.description", equalTo("description1"))) .andExpect(jsonPath("$.version", equalTo(os.getVersion())))
.andExpect(jsonPath("$.vendor", equalTo("vendor1"))).andExpect(jsonPath("$.type", equalTo("os"))) .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("$.createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("$.createdAt", equalTo(os.getCreatedAt()))) .andExpect(jsonPath("$.createdAt", equalTo(os.getCreatedAt())))
.andExpect(jsonPath("$._links.metadata.href", .andExpect(jsonPath("$._links.metadata.href",
@@ -713,65 +655,19 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
.andExpect(jsonPath("$._links.artifacts.href", .andExpect(jsonPath("$._links.artifacts.href",
equalTo("http://localhost/rest/v1/softwaremodules/" + os.getId() + "/artifacts"))); equalTo("http://localhost/rest/v1/softwaremodules/" + os.getId() + "/artifacts")));
SoftwareModule jvm = entityFactory.generateSoftwareModule(runtimeType, "name1", "version1", "description1", assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Softwaremodule size is wrong").hasSize(1);
"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);
} }
@Test @Test
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Verfies that the create request actually results in the creation of the modules in the repository.") @Description("Verfies that the create request actually results in the creation of the modules in the repository.")
public void createSoftwareModules() throws JSONException, Exception { public void createSoftwareModules() throws JSONException, Exception {
final SoftwareModule os = entityFactory.generateSoftwareModule(osType, "name1", "version1", "description1", final SoftwareModule os = entityFactory.softwareModule().create().name("name1").type(osType).version("version1")
"vendor1"); .vendor("vendor1").description("description1").build();
final SoftwareModule jvm = entityFactory.generateSoftwareModule(runtimeType, "name2", "version1", final SoftwareModule ah = entityFactory.softwareModule().create().name("name3").type(appType)
"description1", "vendor1"); .version("version3").vendor("vendor3").description("description3").build();
final SoftwareModule ah = entityFactory.generateSoftwareModule(appType, "name3", "version1", "description1",
"vendor1");
final List<SoftwareModule> modules = new ArrayList<>(); final List<SoftwareModule> modules = Lists.newArrayList(os, ah);
modules.add(os);
modules.add(jvm);
modules.add(ah);
final long current = System.currentTimeMillis(); final long current = System.currentTimeMillis();
@@ -785,25 +681,17 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
.andExpect(jsonPath("[0].description", equalTo("description1"))) .andExpect(jsonPath("[0].description", equalTo("description1")))
.andExpect(jsonPath("[0].vendor", equalTo("vendor1"))).andExpect(jsonPath("[0].type", equalTo("os"))) .andExpect(jsonPath("[0].vendor", equalTo("vendor1"))).andExpect(jsonPath("[0].type", equalTo("os")))
.andExpect(jsonPath("[0].createdBy", equalTo("uploadTester"))) .andExpect(jsonPath("[0].createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("[1].name", equalTo("name2"))) .andExpect(jsonPath("[1].name", equalTo("name3")))
.andExpect(jsonPath("[1].version", equalTo("version1"))) .andExpect(jsonPath("[1].version", equalTo("version3")))
.andExpect(jsonPath("[1].description", equalTo("description1"))) .andExpect(jsonPath("[1].description", equalTo("description3")))
.andExpect(jsonPath("[1].vendor", equalTo("vendor1"))) .andExpect(jsonPath("[1].vendor", equalTo("vendor3")))
.andExpect(jsonPath("[1].type", equalTo("runtime"))) .andExpect(jsonPath("[1].type", equalTo("application")))
.andExpect(jsonPath("[1].createdBy", equalTo("uploadTester"))) .andExpect(jsonPath("[1].createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("[2].name", equalTo("name3"))) .andExpect(jsonPath("[1].createdAt", not(equalTo(0)))).andReturn();
.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();
final SoftwareModule osCreated = softwareManagement.findSoftwareModuleByNameAndVersion("name1", "version1", final SoftwareModule osCreated = softwareManagement.findSoftwareModuleByNameAndVersion("name1", "version1",
osType); osType);
final SoftwareModule jvmCreated = softwareManagement.findSoftwareModuleByNameAndVersion("name2", "version1", final SoftwareModule appCreated = softwareManagement.findSoftwareModuleByNameAndVersion("name3", "version3",
runtimeType);
final SoftwareModule ahCreated = softwareManagement.findSoftwareModuleByNameAndVersion("name3", "version1",
appType); appType);
assertThat( assertThat(
@@ -816,29 +704,19 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
assertThat( assertThat(
JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString()) 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") .as("Response contains links self href")
.isEqualTo("http://localhost/rest/v1/softwaremodules/" + ahCreated.getId()); .isEqualTo("http://localhost/rest/v1/softwaremodules/" + appCreated.getId());
assertThat(JsonPath.compile("[2]_links.artifacts.href").read(mvcResult.getResponse().getContentAsString()) assertThat(JsonPath.compile("[1]_links.artifacts.href").read(mvcResult.getResponse().getContentAsString())
.toString()).as("Response contains invalid artifacts href") .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()) assertThat(softwareManagement.findSoftwareModulesByType(pageReq, osType.getId()).getContent().get(0).getName())
.as("Softwaremoudle name is wrong").isEqualTo(os.getName()); .as("Softwaremoudle name is wrong").isEqualTo(os.getName());
assertThat(softwareManagement.findSoftwareModulesByType(pageReq, osType.getId()).getContent().get(0) assertThat(softwareManagement.findSoftwareModulesByType(pageReq, osType.getId()).getContent().get(0)
.getCreatedBy()).as("Softwaremoudle created by is wrong").isEqualTo("uploadTester"); .getCreatedBy()).as("Softwaremoudle created by is wrong").isEqualTo("uploadTester");
assertThat(softwareManagement.findSoftwareModulesByType(pageReq, osType.getId()).getContent().get(0) assertThat(softwareManagement.findSoftwareModulesByType(pageReq, osType.getId()).getContent().get(0)
.getCreatedAt()).as("Softwaremoudle created at is wrong").isGreaterThanOrEqualTo(current); .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()) assertThat(softwareManagement.findSoftwareModulesByType(pageReq, appType.getId()).getContent().get(0).getName())
.as("Softwaremoudle name is wrong").isEqualTo(ah.getName()); .as("Softwaremoudle name is wrong").isEqualTo(ah.getName());
} }
@@ -847,8 +725,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
@Description("Verifies successfull deletion of software modules that are not in use, i.e. assigned to a DS.") @Description("Verifies successfull deletion of software modules that are not in use, i.e. assigned to a DS.")
public void deleteUnassignedSoftwareModule() throws Exception { public void deleteUnassignedSoftwareModule() throws Exception {
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
sm = softwareManagement.createSoftwareModule(sm);
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes(); final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
@@ -895,8 +772,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
@Description("Tests the deletion of an artifact including verfication that the artifact is actually erased in the repository and removed from the software module.") @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 { public void deleteArtifact() throws Exception {
// Create 1 SM // Create 1 SM
SoftwareModule sm = entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null); final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
sm = softwareManagement.createSoftwareModule(sm);
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes(); final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
@@ -933,8 +809,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
final String knownKey2 = "knownKey1"; final String knownKey2 = "knownKey1";
final String knownValue2 = "knownValue1"; final String knownValue2 = "knownValue1";
final SoftwareModule sm = softwareManagement final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
.createSoftwareModule(entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null));
final JSONArray jsonArray = new JSONArray(); final JSONArray jsonArray = new JSONArray();
jsonArray.put(new JSONObject().put("key", knownKey1).put("value", knownValue1)); jsonArray.put(new JSONObject().put("key", knownKey1).put("value", knownValue1));
@@ -962,10 +837,9 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
final String knownValue = "knownValue"; final String knownValue = "knownValue";
final String updateValue = "valueForUpdate"; final String updateValue = "valueForUpdate";
final SoftwareModule sm = softwareManagement final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
.createSoftwareModule(entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null)); softwareManagement.createSoftwareModuleMetadata(sm.getId(),
softwareManagement entityFactory.generateMetadata(knownKey, knownValue));
.createSoftwareModuleMetadata(entityFactory.generateSoftwareModuleMetadata(sm, knownKey, knownValue));
final JSONObject jsonObject = new JSONObject().put("key", knownKey).put("value", updateValue); final JSONObject jsonObject = new JSONObject().put("key", knownKey).put("value", updateValue);
@@ -986,10 +860,9 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
final String knownKey = "knownKey"; final String knownKey = "knownKey";
final String knownValue = "knownValue"; final String knownValue = "knownValue";
final SoftwareModule sm = softwareManagement final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
.createSoftwareModule(entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null)); softwareManagement.createSoftwareModuleMetadata(sm.getId(),
softwareManagement entityFactory.generateMetadata(knownKey, knownValue));
.createSoftwareModuleMetadata(entityFactory.generateSoftwareModuleMetadata(sm, knownKey, knownValue));
mvc.perform(delete("/rest/v1/softwaremodules/{swId}/metadata/{key}", sm.getId(), knownKey)) mvc.perform(delete("/rest/v1/softwaremodules/{swId}/metadata/{key}", sm.getId(), knownKey))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
@@ -1008,13 +881,11 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
final int totalMetadata = 10; final int totalMetadata = 10;
final String knownKeyPrefix = "knownKey"; final String knownKeyPrefix = "knownKey";
final String knownValuePrefix = "knownValue"; final String knownValuePrefix = "knownValue";
final SoftwareModule sm = softwareManagement final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
.createSoftwareModule(entityFactory.generateSoftwareModule(osType, "name 1", "version 1", null, null));
for (int index = 0; index < totalMetadata; index++) { for (int index = 0; index < totalMetadata; index++) {
softwareManagement.createSoftwareModuleMetadata( softwareManagement.createSoftwareModuleMetadata(sm.getId(),
entityFactory.generateSoftwareModuleMetadata(softwareManagement.findSoftwareModuleById(sm.getId()), entityFactory.generateMetadata(knownKeyPrefix + index, knownValuePrefix + index));
knownKeyPrefix + index, knownValuePrefix + index));
} }
final String rsqlSearchValue1 = "value==knownValue1"; final String rsqlSearchValue1 = "value==knownValue1";
@@ -1029,9 +900,8 @@ public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTest
char character = 'a'; char character = 'a';
for (int index = 0; index < amount; index++) { for (int index = 0; index < amount; index++) {
final String str = String.valueOf(character); final String str = String.valueOf(character);
final SoftwareModule softwareModule = entityFactory.generateSoftwareModule(osType, str, str, str, str); softwareManagement.createSoftwareModule(entityFactory.softwareModule().create().type(osType).name(str)
.description(str).vendor(str).version(str));
softwareManagement.createSoftwareModule(softwareModule);
character++; character++;
} }
} }

View File

@@ -26,7 +26,6 @@ import java.util.List;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; 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.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.test.util.WithUser; import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest; import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest;
@@ -57,10 +56,7 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests.") @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests.")
public void getSoftwareModuleTypes() throws Exception { public void getSoftwareModuleTypes() throws Exception {
SoftwareModuleType testType = softwareManagement.createSoftwareModuleType( final SoftwareModuleType testType = createTestType();
entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5));
testType.setDescription("Desc1234");
testType = softwareManagement.updateSoftwareModuleType(testType);
mvc.perform(get("/rest/v1/softwaremoduletypes").accept(MediaType.APPLICATION_JSON)) mvc.perform(get("/rest/v1/softwaremoduletypes").accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
@@ -95,14 +91,19 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
.andExpect(jsonPath("$.total", equalTo(4))); .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 @Test
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests with sorting by MAXASSIGNMENTS field.") @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests with sorting by MAXASSIGNMENTS field.")
public void getSoftwareModuleTypesSortedByMaxAssignments() throws Exception { public void getSoftwareModuleTypesSortedByMaxAssignments() throws Exception {
SoftwareModuleType testType = softwareManagement.createSoftwareModuleType( final SoftwareModuleType testType = createTestType();
entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5));
testType.setDescription("Desc1234");
testType = softwareManagement.updateSoftwareModuleType(testType);
// descending // descending
mvc.perform(get("/rest/v1/softwaremoduletypes").accept(MediaType.APPLICATION_JSON) mvc.perform(get("/rest/v1/softwaremoduletypes").accept(MediaType.APPLICATION_JSON)
@@ -143,14 +144,15 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
public void createSoftwareModuleTypesInvalidAssignmentBadRequest() throws JSONException, Exception { public void createSoftwareModuleTypesInvalidAssignmentBadRequest() throws JSONException, Exception {
final List<SoftwareModuleType> types = new ArrayList<>(); final List<SoftwareModuleType> 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)) mvc.perform(post("/rest/v1/softwaremoduletypes/").content(JsonBuilder.softwareModuleTypes(types))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
types.clear(); 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)) mvc.perform(post("/rest/v1/softwaremoduletypes/").content(JsonBuilder.softwareModuleTypes(types))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
@@ -162,10 +164,13 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes POST requests.") @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes POST requests.")
public void createSoftwareModuleTypes() throws JSONException, Exception { public void createSoftwareModuleTypes() throws JSONException, Exception {
final List<SoftwareModuleType> types = new ArrayList<>(); final List<SoftwareModuleType> types = Lists.newArrayList(
types.add(entityFactory.generateSoftwareModuleType("test1", "TestName1", "Desc1", 1)); entityFactory.softwareModuleType().create().key("test1").name("TestName1").description("Desc1")
types.add(entityFactory.generateSoftwareModuleType("test2", "TestName2", "Desc2", 2)); .colour("col1").maxAssignments(1).build(),
types.add(entityFactory.generateSoftwareModuleType("test3", "TestName3", "Desc3", 3)); 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 final MvcResult mvcResult = mvc
.perform(post("/rest/v1/softwaremoduletypes/").content(JsonBuilder.softwareModuleTypes(types)) .perform(post("/rest/v1/softwaremoduletypes/").content(JsonBuilder.softwareModuleTypes(types))
@@ -207,10 +212,7 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} GET requests.") @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} GET requests.")
public void getSoftwareModuleType() throws Exception { public void getSoftwareModuleType() throws Exception {
SoftwareModuleType testType = softwareManagement.createSoftwareModuleType( final SoftwareModuleType testType = createTestType();
entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5));
testType.setDescription("Desc1234");
testType = softwareManagement.updateSoftwareModuleType(testType);
mvc.perform(get("/rest/v1/softwaremoduletypes/{smtId}", testType.getId()).accept(MediaType.APPLICATION_JSON)) mvc.perform(get("/rest/v1/softwaremoduletypes/{smtId}", testType.getId()).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
@@ -228,8 +230,7 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} DELETE requests (hard delete scenario).") @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} DELETE requests (hard delete scenario).")
public void deleteSoftwareModuleTypeUnused() throws Exception { public void deleteSoftwareModuleTypeUnused() throws Exception {
final SoftwareModuleType testType = softwareManagement.createSoftwareModuleType( final SoftwareModuleType testType = createTestType();
entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5));
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(4); assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(4);
@@ -243,10 +244,9 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} DELETE requests (soft delete scenario).") @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} DELETE requests (soft delete scenario).")
public void deleteSoftwareModuleTypeUsed() throws Exception { public void deleteSoftwareModuleTypeUsed() throws Exception {
final SoftwareModuleType testType = softwareManagement.createSoftwareModuleType( final SoftwareModuleType testType = createTestType();
entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5));
softwareManagement.createSoftwareModule( softwareManagement.createSoftwareModule(
entityFactory.generateSoftwareModule(testType, "name", "version", "description", "vendor")); entityFactory.softwareModule().create().type(testType).name("name").version("version"));
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(4); assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(4);
@@ -259,8 +259,7 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
@Test @Test
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} PUT requests.") @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} PUT requests.")
public void updateSoftwareModuleTypeOnlyDescriptionAndNameUntouched() throws Exception { public void updateSoftwareModuleTypeOnlyDescriptionAndNameUntouched() throws Exception {
final SoftwareModuleType testType = softwareManagement.createSoftwareModuleType( final SoftwareModuleType testType = createTestType();
entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5));
final String body = new JSONObject().put("id", testType.getId()).put("description", "foobardesc") final String body = new JSONObject().put("id", testType.getId()).put("description", "foobardesc")
.put("name", "nameShouldNotBeChanged").toString(); .put("name", "nameShouldNotBeChanged").toString();
@@ -315,8 +314,7 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
@Test @Test
@Description("Ensures that the server is behaving as expected on invalid requests (wrong media type, wrong ID etc.).") @Description("Ensures that the server is behaving as expected on invalid requests (wrong media type, wrong ID etc.).")
public void invalidRequestsOnSoftwaremoduleTypesResource() throws Exception { public void invalidRequestsOnSoftwaremoduleTypesResource() throws Exception {
final SoftwareModuleType testType = softwareManagement.createSoftwareModuleType( final SoftwareModuleType testType = createTestType();
entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5));
final List<SoftwareModuleType> types = Lists.newArrayList(testType); final List<SoftwareModuleType> types = Lists.newArrayList(testType);
@@ -342,8 +340,8 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest()); .andExpect(status().isBadRequest());
final SoftwareModuleType toLongName = entityFactory.generateSoftwareModuleType("test123", final SoftwareModuleType toLongName = entityFactory.softwareModuleType().create().key("test123")
RandomStringUtils.randomAscii(80), "Desc123", 5); .name(RandomStringUtils.randomAscii(80)).build();
mvc.perform(post("/rest/v1/softwaremoduletypes") mvc.perform(post("/rest/v1/softwaremoduletypes")
.content(JsonBuilder.softwareModuleTypes(Lists.newArrayList(toLongName))) .content(JsonBuilder.softwareModuleTypes(Lists.newArrayList(toLongName)))
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
@@ -366,10 +364,10 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
@Test @Test
@Description("Search erquest of software module types.") @Description("Search erquest of software module types.")
public void searchSoftwareModuleTypeRsql() throws Exception { public void searchSoftwareModuleTypeRsql() throws Exception {
final SoftwareModuleType testType = softwareManagement.createSoftwareModuleType( softwareManagement.createSoftwareModuleType(entityFactory.softwareModuleType().create().key("test123")
entityFactory.generateSoftwareModuleType("test123", "TestName123", "Desc123", 5)); .name("TestName123").description("Desc123").maxAssignments(5));
final SoftwareModuleType testType2 = softwareManagement.createSoftwareModuleType( softwareManagement.createSoftwareModuleType(entityFactory.softwareModuleType().create().key("test1234")
entityFactory.generateSoftwareModuleType("test1234", "TestName1234", "Desc123", 5)); .name("TestName1234").description("Desc1234").maxAssignments(5));
final String rsqlFindLikeDs1OrDs2 = "name==TestName123,name==TestName1234"; final String rsqlFindLikeDs1OrDs2 = "name==TestName123,name==TestName1234";
@@ -384,9 +382,8 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationT
char character = 'a'; char character = 'a';
for (int index = 0; index < amount; index++) { for (int index = 0; index < amount; index++) {
final String str = String.valueOf(character); final String str = String.valueOf(character);
final SoftwareModule softwareModule = entityFactory.generateSoftwareModule(osType, str, str, str, str); softwareManagement.createSoftwareModule(entityFactory.softwareModule().create().type(osType).name(str)
.description(str).vendor(str).version(str));
softwareManagement.createSoftwareModule(softwareModule);
character++; character++;
} }
} }

View File

@@ -128,10 +128,8 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractRestIntegrationTe
final String body = new JSONObject().put("name", filterName2).toString(); final String body = new JSONObject().put("name", filterName2).toString();
// prepare // prepare
TargetFilterQuery tfq = entityFactory.generateTargetFilterQuery(); final TargetFilterQuery tfq = targetFilterQueryManagement.createTargetFilterQuery(
tfq.setName(filterName); entityFactory.targetFilterQuery().create().name(filterName).query(filterQuery));
tfq.setQuery(filterQuery);
tfq = targetFilterQueryManagement.createTargetFilterQuery(tfq);
mvc.perform(put(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + tfq.getId()).content(body) mvc.perform(put(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + tfq.getId()).content(body)
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
@@ -319,11 +317,8 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractRestIntegrationTe
final String dsName = "testDS"; final String dsName = "testDS";
final DistributionSet set = testdataFactory.createDistributionSet(dsName); final DistributionSet set = testdataFactory.createDistributionSet(dsName);
TargetFilterQuery tfq = entityFactory.generateTargetFilterQuery(); final TargetFilterQuery tfq = createSingleTargetFilterQuery(knownName, knownQuery);
tfq.setName(knownName); targetFilterQueryManagement.updateTargetFilterQueryAutoAssignDS(tfq.getId(), set.getId());
tfq.setQuery(knownQuery);
tfq.setAutoAssignDistributionSet(set);
tfq = targetFilterQueryManagement.createTargetFilterQuery(tfq);
assertThat(targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).getAutoAssignDistributionSet()) assertThat(targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).getAutoAssignDistributionSet())
.isEqualTo(set); .isEqualTo(set);
@@ -343,10 +338,8 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractRestIntegrationTe
} }
private TargetFilterQuery createSingleTargetFilterQuery(final String name, final String query) { private TargetFilterQuery createSingleTargetFilterQuery(final String name, final String query) {
final TargetFilterQuery target = entityFactory.generateTargetFilterQuery(); return targetFilterQueryManagement
target.setName(name); .createTargetFilterQuery(entityFactory.targetFilterQuery().create().name(name).query(query));
target.setQuery(query);
return targetFilterQueryManagement.createTargetFilterQuery(target);
} }
} }

View File

@@ -8,7 +8,6 @@
*/ */
package org.eclipse.hawkbit.mgmt.rest.resource; 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.fest.assertions.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.not;
@@ -25,7 +24,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@@ -39,8 +37,6 @@ import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.ActionFields; import org.eclipse.hawkbit.repository.ActionFields;
import org.eclipse.hawkbit.repository.exception.ConstraintViolationException; import org.eclipse.hawkbit.repository.exception.ConstraintViolationException;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; 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;
import org.eclipse.hawkbit.repository.model.Action.ActionType; import org.eclipse.hawkbit.repository.model.Action.ActionType;
import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.Action.Status;
@@ -111,9 +107,8 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
final int limitSize = 2; final int limitSize = 2;
final String knownTargetId = "targetId"; final String knownTargetId = "targetId";
final List<Action> actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId); final List<Action> actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId);
actions.get(0).setStatus(Status.FINISHED); controllerManagament.addUpdateActionStatus(
controllerManagament.addUpdateActionStatus(entityFactory.generateActionStatus(actions.get(0), Status.FINISHED, entityFactory.actionStatus().create(actions.get(0).getId()).status(Status.FINISHED).message("test"));
System.currentTimeMillis(), "testmessage"));
final PageRequest pageRequest = new PageRequest(0, 1000, Direction.ASC, ActionFields.ID.getFieldName()); final PageRequest pageRequest = new PageRequest(0, 1000, Direction.ASC, ActionFields.ID.getFieldName());
final ActionStatus status = deploymentManagement final ActionStatus status = deploymentManagement
@@ -142,7 +137,7 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
public void securityTokenIsNotInResponseIfMissingPermission() throws Exception { public void securityTokenIsNotInResponseIfMissingPermission() throws Exception {
final String knownControllerId = "knownControllerId"; final String knownControllerId = "knownControllerId";
targetManagement.createTarget(entityFactory.generateTarget(knownControllerId)); testdataFactory.createTarget(knownControllerId);
mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}", knownControllerId)) mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}", knownControllerId))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath("securityToken").doesNotExist()); .andExpect(jsonPath("securityToken").doesNotExist());
@@ -155,7 +150,7 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
public void securityTokenIsInResponseWithCorrectPermission() throws Exception { public void securityTokenIsInResponseWithCorrectPermission() throws Exception {
final String knownControllerId = "knownControllerId"; 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)) mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}", knownControllerId))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath("securityToken", equalTo(createTarget.getSecurityToken()))); .andExpect(jsonPath("securityToken", equalTo(createTarget.getSecurityToken())));
@@ -186,11 +181,8 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
} }
private void createTarget(final String controllerId) { private void createTarget(final String controllerId) {
final JpaTarget target = (JpaTarget) entityFactory.generateTarget(controllerId); targetManagement.createTarget(entityFactory.target().create().controllerId(controllerId)
final JpaTargetInfo targetInfo = new JpaTargetInfo(target); .address(IpUtil.createHttpUri("127.0.0.1").toString()));
targetInfo.setAddress(IpUtil.createHttpUri("127.0.0.1").toString());
target.setTargetInfo(targetInfo);
targetManagement.createTarget(target);
} }
@Test @Test
@@ -199,9 +191,9 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
// prepare test // prepare test
final DistributionSet dsA = testdataFactory.createDistributionSet(""); 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 rsqlPendingStatus = "status==pending";
final String rsqlFinishedStatus = "status==finished"; final String rsqlFinishedStatus = "status==finished";
@@ -279,8 +271,8 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
deploymentManagement.cancelAction(tA.getActions().get(0), tA); deploymentManagement.cancelAction(tA.getActions().get(0), tA);
// find the current active action // find the current active action
final List<Action> cancelActions = deploymentManagement.findActionsByTarget(new PageRequest(0, 100), tA) final List<Action> cancelActions = deploymentManagement.findActionsByTarget(pageReq, tA).getContent().stream()
.getContent().stream().filter(action -> action.isCancelingOrCanceled()).collect(Collectors.toList()); .filter(Action::isCancelingOrCanceled).collect(Collectors.toList());
assertThat(cancelActions).hasSize(1); assertThat(cancelActions).hasSize(1);
assertThat(cancelActions.get(0).isCancelingOrCanceled()).isTrue(); assertThat(cancelActions.get(0).isCancelingOrCanceled()).isTrue();
@@ -306,7 +298,7 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
@Description("Ensures that deletion is executed if permitted.") @Description("Ensures that deletion is executed if permitted.")
public void deleteTargetReturnsOK() throws Exception { public void deleteTargetReturnsOK() throws Exception {
final String knownControllerId = "knownControllerIdDelete"; final String knownControllerId = "knownControllerIdDelete";
targetManagement.createTarget(entityFactory.generateTarget(knownControllerId)); testdataFactory.createTarget(knownControllerId);
mvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId)) mvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId))
.andExpect(status().isOk()); .andExpect(status().isOk());
@@ -342,10 +334,8 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
final String body = new JSONObject().put("description", knownNewDescription).toString(); final String body = new JSONObject().put("description", knownNewDescription).toString();
// prepare // prepare
final Target t = entityFactory.generateTarget(knownControllerId); targetManagement.createTarget(entityFactory.target().create().controllerId(knownControllerId)
t.setDescription("old description"); .name(knownNameNotModiy).description("old description"));
t.setName(knownNameNotModiy);
targetManagement.createTarget(t);
mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content(body) mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content(body)
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
@@ -367,9 +357,8 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
final String body = new JSONObject().put("securityToken", knownNewToken).toString(); final String body = new JSONObject().put("securityToken", knownNewToken).toString();
// prepare // prepare
final Target t = entityFactory.generateTarget(knownControllerId); targetManagement
t.setName(knownNameNotModiy); .createTarget(entityFactory.target().create().controllerId(knownControllerId).name(knownNameNotModiy));
targetManagement.createTarget(t);
mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content(body) mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content(body)
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
@@ -391,9 +380,8 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
final String body = new JSONObject().put("address", knownNewAddress).toString(); final String body = new JSONObject().put("address", knownNewAddress).toString();
// prepare // prepare
final Target t = entityFactory.generateTarget(knownControllerId); targetManagement.createTarget(entityFactory.target().create().controllerId(knownControllerId)
t.setName(knownNameNotModiy); .name(knownNameNotModiy).address(knownNewAddress));
targetManagement.createTarget(t);
mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content(body) mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content(body)
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
@@ -578,7 +566,7 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
final String knownName = "someName"; final String knownName = "someName";
createSingleTarget(knownControllerId, knownName); createSingleTarget(knownControllerId, knownName);
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
deploymentManagement.assignDistributionSet(ds.getId(), knownControllerId); assignDistributionSet(ds.getId(), knownControllerId);
// test // test
@@ -674,12 +662,8 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
@Test @Test
@Description("Verfies that a mandatory properties of new targets are validated as not null.") @Description("Verfies that a mandatory properties of new targets are validated as not null.")
public void createTargetWithMissingMandatoryPropertyBadRequest() throws Exception { public void createTargetWithMissingMandatoryPropertyBadRequest() throws Exception {
final Target test1 = entityFactory.generateTarget("id1", "token");
test1.setName(null);
final MvcResult mvcResult = mvc final MvcResult mvcResult = mvc
.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING) .perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING).content("[{\"name\":\"id1\"}]")
.content(JsonBuilder.targets(Lists.newArrayList(test1), true))
.contentType(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()).andReturn(); .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()).andReturn();
@@ -695,13 +679,11 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
@Test @Test
@Description("Verfies that a properties of new targets are validated as in allowed size range.") @Description("Verfies that a properties of new targets are validated as in allowed size range.")
public void createTargetWithInvalidPropertyBadRequest() throws Exception { public void createTargetWithInvalidPropertyBadRequest() throws Exception {
final Target test1 = entityFactory.generateTarget("id1", "token"); final Target test1 = entityFactory.target().create().controllerId("id1").name(RandomStringUtils.randomAscii(80))
test1.setName(RandomStringUtils.randomAscii(80)); .build();
final MvcResult mvcResult = mvc final MvcResult mvcResult = mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING)
.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING) .content(JsonBuilder.targets(Lists.newArrayList(test1), true)).contentType(MediaType.APPLICATION_JSON))
.content(JsonBuilder.targets(Lists.newArrayList(test1), true))
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()).andReturn(); .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()).andReturn();
assertThat(targetManagement.countTargetsAll()).isEqualTo(0); assertThat(targetManagement.countTargetsAll()).isEqualTo(0);
@@ -715,21 +697,14 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
@Test @Test
public void createTargetsListReturnsSuccessful() throws Exception { public void createTargetsListReturnsSuccessful() throws Exception {
final Target test1 = entityFactory.generateTarget("id1", "token"); final Target test1 = entityFactory.target().create().controllerId("id1").name("testname1")
test1.setDescription("testid1"); .securityToken("token").address("amqp://test123/foobar").description("testid1").build();
test1.setName("testname1"); final Target test2 = entityFactory.target().create().controllerId("id2").name("testname2")
test1.getTargetInfo().setAddress("amqp://test123/foobar"); .description("testid2").build();
final Target test2 = entityFactory.generateTarget("id2"); final Target test3 = entityFactory.target().create().controllerId("id3").name("testname3")
test2.setDescription("testid2"); .description("testid3").build();
test2.setName("testname2");
final Target test3 = entityFactory.generateTarget("id3");
test3.setName("testname3");
test3.setDescription("testid3");
final List<Target> targets = new ArrayList<>(); final List<Target> targets = Lists.newArrayList(test1, test2, test3);
targets.add(test1);
targets.add(test2);
targets.add(test3);
final MvcResult mvcResult = mvc final MvcResult mvcResult = mvc
.perform(post("/rest/v1/targets/").content(JsonBuilder.targets(targets, true)) .perform(post("/rest/v1/targets/").content(JsonBuilder.targets(targets, true))
@@ -850,8 +825,7 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
@Test @Test
public void getActionWithEmptyResult() throws Exception { public void getActionWithEmptyResult() throws Exception {
final String knownTargetId = "targetId"; final String knownTargetId = "targetId";
final Target target = entityFactory.generateTarget(knownTargetId); final Target target = testdataFactory.createTarget(knownTargetId);
targetManagement.createTarget(target);
mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/"
+ MgmtRestConstants.TARGET_V1_ACTIONS)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + MgmtRestConstants.TARGET_V1_ACTIONS)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
@@ -1063,22 +1037,19 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
private List<Action> generateTargetWithTwoUpdatesWithOneOverride(final String knownTargetId) private List<Action> generateTargetWithTwoUpdatesWithOneOverride(final String knownTargetId)
throws InterruptedException { throws InterruptedException {
Target target = entityFactory.generateTarget(knownTargetId); final Target target = testdataFactory.createTarget(knownTargetId);
target = targetManagement.createTarget(target); final List<Target> targets = Lists.newArrayList(target);
final List<Target> targets = new ArrayList<>();
targets.add(target);
final Iterator<DistributionSet> sets = testdataFactory.createDistributionSets(2).iterator(); final Iterator<DistributionSet> sets = testdataFactory.createDistributionSets(2).iterator();
final DistributionSet one = sets.next(); final DistributionSet one = sets.next();
final DistributionSet two = sets.next(); final DistributionSet two = sets.next();
// Update // Update
final List<Target> updatedTargets = deploymentManagement.assignDistributionSet(one, targets) final List<Target> updatedTargets = assignDistributionSet(one, targets).getAssignedEntity();
.getAssignedEntity();
// 2nd update // 2nd update
// sleep 10ms to ensure that we can sort by reportedAt // sleep 10ms to ensure that we can sort by reportedAt
Thread.sleep(10); Thread.sleep(10);
deploymentManagement.assignDistributionSet(two, updatedTargets); assignDistributionSet(two, updatedTargets);
// two updates, one cancellation // two updates, one cancellation
final List<Action> actions = deploymentManagement.findActionsByTarget(target); final List<Action> actions = deploymentManagement.findActionsByTarget(target);
@@ -1108,7 +1079,7 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
@Test @Test
public void assignDistributionSetToTarget() throws Exception { public void assignDistributionSetToTarget() throws Exception {
targetManagement.createTarget(entityFactory.generateTarget("fsdfsd")); testdataFactory.createTarget("fsdfsd");
final DistributionSet set = testdataFactory.createDistributionSet("one"); final DistributionSet set = testdataFactory.createDistributionSet("one");
mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS") mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS")
@@ -1121,7 +1092,7 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
@Test @Test
public void assignDistributionSetToTargetWithActionTimeForcedAndTime() throws Exception { 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 DistributionSet set = testdataFactory.createDistributionSet("one");
final long forceTime = System.currentTimeMillis(); final long forceTime = System.currentTimeMillis();
@@ -1148,7 +1119,7 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
.content("{\"id\":" + set.getId() + "}").contentType(MediaType.APPLICATION_JSON)) .content("{\"id\":" + set.getId() + "}").contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
targetManagement.createTarget(entityFactory.generateTarget("fsdfsd")); testdataFactory.createTarget("fsdfsd");
mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS") mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS")
.content("{\"id\":" + set.getId() + "}").contentType(MediaType.APPLICATION_JSON)) .content("{\"id\":" + set.getId() + "}").contentType(MediaType.APPLICATION_JSON))
@@ -1238,8 +1209,7 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
final Map<String, String> knownControllerAttrs = new HashMap<>(); final Map<String, String> knownControllerAttrs = new HashMap<>();
knownControllerAttrs.put("a", "1"); knownControllerAttrs.put("a", "1");
knownControllerAttrs.put("b", "2"); knownControllerAttrs.put("b", "2");
final Target target = entityFactory.generateTarget(knownTargetId); final Target target = testdataFactory.createTarget(knownTargetId);
targetManagement.createTarget(target);
controllerManagament.updateControllerAttributes(knownTargetId, knownControllerAttrs); controllerManagament.updateControllerAttributes(knownTargetId, knownControllerAttrs);
// test query target over rest resource // test query target over rest resource
@@ -1252,8 +1222,7 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
public void getControllerEmptyAttributesReturnsNoContent() throws Exception { public void getControllerEmptyAttributesReturnsNoContent() throws Exception {
// create target with attributes // create target with attributes
final String knownTargetId = "targetIdWithAttributes"; final String knownTargetId = "targetIdWithAttributes";
final Target target = entityFactory.generateTarget(knownTargetId); final Target target = testdataFactory.createTarget(knownTargetId);
targetManagement.createTarget(target);
// test query target over rest resource // test query target over rest resource
mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/attributes")) mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/attributes"))
@@ -1286,10 +1255,8 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
} }
private Target createSingleTarget(final String controllerId, final String name) { private Target createSingleTarget(final String controllerId, final String name) {
final Target target = entityFactory.generateTarget(controllerId); targetManagement.createTarget(entityFactory.target().create().controllerId(controllerId).name(name)
target.setName(name); .description(TARGET_DESCRIPTION_TEST));
target.setDescription(TARGET_DESCRIPTION_TEST);
targetManagement.createTarget(target);
return controllerManagament.updateLastTargetQuery(controllerId, null); return controllerManagament.updateLastTargetQuery(controllerId, null);
} }
@@ -1304,10 +1271,7 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
char character = 'a'; char character = 'a';
for (int index = 0; index < amount; index++) { for (int index = 0; index < amount; index++) {
final String str = String.valueOf(character); final String str = String.valueOf(character);
final Target target = entityFactory.generateTarget(str); targetManagement.createTarget(entityFactory.target().create().controllerId(str).name(str).description(str));
target.setName(str);
target.setDescription(str);
targetManagement.createTarget(target);
controllerManagament.updateLastTargetQuery(str, null); controllerManagament.updateLastTargetQuery(str, null);
character++; character++;
} }
@@ -1318,10 +1282,8 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
* *
*/ */
private void feedbackToByInSync(final Long actionId) { private void feedbackToByInSync(final Long actionId) {
final Action action = deploymentManagement.findAction(actionId); controllerManagement
.addUpdateActionStatus(entityFactory.actionStatus().create(actionId).status(Status.FINISHED));
final ActionStatus actionStatus = entityFactory.generateActionStatus(action, Status.FINISHED, 0L);
controllerManagement.addUpdateActionStatus(actionStatus);
} }
/** /**
@@ -1332,10 +1294,9 @@ public class MgmtTargetResourceTest extends AbstractRestIntegrationTest {
private Target createTargetAndStartAction() { private Target createTargetAndStartAction() {
// prepare test // prepare test
final DistributionSet dsA = testdataFactory.createDistributionSet(""); final DistributionSet dsA = testdataFactory.createDistributionSet("");
final Target tA = targetManagement final Target tA = testdataFactory.createTarget("target-id-A");
.createTarget(testdataFactory.generateTarget("target-id-A", "first description"));
// assign a distribution set so we get an active update action // assign a distribution set so we get an active update action
deploymentManagement.assignDistributionSet(dsA, newArrayList(tA)); assignDistributionSet(dsA, Lists.newArrayList(tA));
// verify active action // verify active action
final Slice<Action> actionsByTarget = deploymentManagement.findActionsByTarget(new PageRequest(0, 100), tA); final Slice<Action> actionsByTarget = deploymentManagement.findActionsByTarget(new PageRequest(0, 100), tA);
assertThat(actionsByTarget.getContent()).hasSize(1); assertThat(actionsByTarget.getContent()).hasSize(1);

View File

@@ -7,6 +7,7 @@
# http://www.eclipse.org/legal/epl-v10.html # http://www.eclipse.org/legal/epl-v10.html
# #
#logging.level.org.eclipse.hawkbit.rest.util.MockMvcResultPrinter=DEBUG
logging.level.=INFO logging.level.=INFO
logging.level.org.eclipse.persistence=ERROR logging.level.org.eclipse.persistence=ERROR

View File

@@ -64,30 +64,6 @@ public interface ArtifactManagement {
Artifact createArtifact(@NotNull InputStream inputStream, @NotNull Long moduleId, final String filename, Artifact createArtifact(@NotNull InputStream inputStream, @NotNull Long moduleId, final String filename,
final boolean overrideExisting); final boolean overrideExisting);
/**
* Persists artifact binary as provided by given InputStream. assign the
* artifact in addition to given {@link SoftwareModule}.
*
* @param inputStream
* to read from for artifact binary
* @param moduleId
* to assign the new artifact to
* @param filename
* of the artifact
* @param overrideExisting
* to <code>true</code> if the artifact binary can be overridden
* if it already exists
* @param contentType
* the contentType of the file
*
* @return uploaded {@link 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 * Persists artifact binary as provided by given InputStream. assign the
* artifact in addition to given {@link SoftwareModule}. * artifact in addition to given {@link SoftwareModule}.
@@ -103,7 +79,7 @@ public interface ArtifactManagement {
* @param providedMd5Sum * @param providedMd5Sum
* optional md5 checksum to check the new file against * optional md5 checksum to check the new file against
* @param overrideExisting * @param overrideExisting
* to <code>true</code> if the artifact binary can be overdiden * to <code>true</code> if the artifact binary can be overridden
* if it already exists * if it already exists
* @param contentType * @param contentType
* the contentType of the file * the contentType of the file

View File

@@ -9,13 +9,13 @@
package org.eclipse.hawkbit.repository; package org.eclipse.hawkbit.repository;
import java.net.URI; import java.net.URI;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; 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.event.remote.DownloadProgressEvent;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
@@ -44,16 +44,22 @@ public interface ControllerManagement {
* Adds an {@link ActionStatus} for a cancel {@link Action} including * Adds an {@link ActionStatus} for a cancel {@link Action} including
* potential state changes for the target and the {@link Action} itself. * potential state changes for the target and the {@link Action} itself.
* *
* @param actionStatus * @param create
* to be added * to be added
* @return the persisted {@link Action} * @return the updated {@link Action}
* *
* @throws EntityAlreadyExistsException * @throws EntityAlreadyExistsException
* if a given entity already exists * 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) @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 * 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} * Simple addition of a new {@link ActionStatus} entry to the {@link Action}
* . No state changes. * . No state changes.
* *
* @param statusMessage * @param create
* to add to the action * 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) @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 * Adds an {@link ActionStatus} entry for an update {@link Action} including
* potential state changes for the target and the {@link Action} itself. * potential state changes for the target and the {@link Action} itself.
* *
* @param actionStatus * @param create
* to be added * to be added
* @return the updated {@link Action} * @return the updated {@link Action}
* *
@@ -96,20 +108,12 @@ public interface ControllerManagement {
* @throws TooManyStatusEntriesException * @throws TooManyStatusEntriesException
* if more than the allowed number of status entries are * if more than the allowed number of status entries are
* inserted * inserted
* @throws TooManyStatusEntriesException
* if more than the allowed number of status entries are
* inserted
*/ */
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
Action addUpdateActionStatus(@NotNull ActionStatus actionStatus); Action addUpdateActionStatus(@NotNull ActionStatusCreate create);
/**
* Retrieves all {@link Action}s which are active and assigned to a
* {@link Target}.
*
* @param target
* the target to retrieve the actions from
* @return a list of actions assigned to given target which are active
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
List<Action> findActiveActionByTarget(@NotNull Target target);
/** /**
* Retrieves oldest {@link Action} that is active and assigned to a * Retrieves oldest {@link Action} that is active and assigned to a

View File

@@ -44,26 +44,6 @@ import org.springframework.security.access.prepost.PreAuthorize;
*/ */
public interface DeploymentManagement { public interface DeploymentManagement {
/**
* method assigns the {@link DistributionSet} to all {@link Target}s.
*
* @param pset
* {@link DistributionSet} which is assigned to the
* {@link Target}s
* @param targets
* the {@link Target}s which should obtain the
* {@link DistributionSet}
*
* @return the changed targets
*
* @throw IncompleteDistributionSetException if mandatory
* {@link SoftwareModuleType} are not assigned as define by the
* {@link DistributionSetType}. *
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET)
DistributionSetAssignmentResult assignDistributionSet(@NotNull DistributionSet pset,
@NotEmpty List<Target> targets);
/** /**
* method assigns the {@link DistributionSet} to all {@link Target}s by * method assigns the {@link DistributionSet} to all {@link Target}s by
* their IDs with a specific {@link ActionType} and {@code forcetime}. * their IDs with a specific {@link ActionType} and {@code forcetime}.
@@ -75,17 +55,20 @@ public interface DeploymentManagement {
* @param forcedTimestamp * @param forcedTimestamp
* the time when the action should be forced, only necessary for * the time when the action should be forced, only necessary for
* {@link ActionType#TIMEFORCED} * {@link ActionType#TIMEFORCED}
* @param targetIDs * @param controllerIDs
* the IDs of the target to assign the distribution set * the IDs of the target to assign the distribution set
* @return the assignment result * @return the assignment result
* *
* @throw IncompleteDistributionSetException if mandatory * @throw IncompleteDistributionSetException if mandatory
* {@link SoftwareModuleType} are not assigned as define by the * {@link SoftwareModuleType} are not assigned as define by the
* {@link DistributionSetType}. * {@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) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET)
DistributionSetAssignmentResult assignDistributionSet(@NotNull final Long dsID, final ActionType actionType, DistributionSetAssignmentResult assignDistributionSet(@NotNull Long dsID, @NotNull ActionType actionType,
final long forcedTimestamp, @NotEmpty final String... targetIDs); long forcedTimestamp, @NotEmpty Collection<String> controllerIDs);
/** /**
* method assigns the {@link DistributionSet} to all {@link Target}s by * method assigns the {@link DistributionSet} to all {@link Target}s by
@@ -100,6 +83,9 @@ public interface DeploymentManagement {
* @throw IncompleteDistributionSetException if mandatory * @throw IncompleteDistributionSetException if mandatory
* {@link SoftwareModuleType} are not assigned as define by the * {@link SoftwareModuleType} are not assigned as define by the
* {@link DistributionSetType}. * {@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) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET)
DistributionSetAssignmentResult assignDistributionSet(@NotNull Long dsID, DistributionSetAssignmentResult assignDistributionSet(@NotNull Long dsID,
@@ -120,11 +106,13 @@ public interface DeploymentManagement {
* @throw IncompleteDistributionSetException if mandatory * @throw IncompleteDistributionSetException if mandatory
* {@link SoftwareModuleType} are not assigned as define by the * {@link SoftwareModuleType} are not assigned as define by the
* {@link DistributionSetType}. * {@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) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET)
DistributionSetAssignmentResult assignDistributionSet(@NotNull Long dsID, DistributionSetAssignmentResult assignDistributionSet(@NotNull Long dsID,
@NotEmpty Collection<TargetWithActionType> targets, @NotEmpty Collection<TargetWithActionType> targets, String actionMessage);
String actionMessage);
/** /**
* method assigns the {@link DistributionSet} to all {@link Target}s by * method assigns the {@link DistributionSet} to all {@link Target}s by
@@ -143,34 +131,14 @@ public interface DeploymentManagement {
* @throw IncompleteDistributionSetException if mandatory * @throw IncompleteDistributionSetException if mandatory
* {@link SoftwareModuleType} are not assigned as define by the * {@link SoftwareModuleType} are not assigned as define by the
* {@link DistributionSetType}. * {@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) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET)
DistributionSetAssignmentResult assignDistributionSet(@NotNull Long dsID, DistributionSetAssignmentResult assignDistributionSet(@NotNull Long dsID,
@NotEmpty Collection<TargetWithActionType> targets, Rollout rollout, RolloutGroup rolloutGroup); @NotEmpty Collection<TargetWithActionType> targets, Rollout rollout, RolloutGroup rolloutGroup);
/**
* method assigns the {@link DistributionSet} to all {@link Target}s by
* their IDs.
*
* @param dsID
* {@link DistributionSet} which is assigned to the
* {@link Target}s
* @param targetIDs
* IDs of the {@link Target}s which should obtain the
* {@link DistributionSet}
*
* @return the changed targets
*
* @throws EntityNotFoundException
* if {@link DistributionSet} does not exist.
*
* @throw IncompleteDistributionSetException if mandatory
* {@link SoftwareModuleType} are not assigned as define by the
* {@link DistributionSetType}.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET)
DistributionSetAssignmentResult assignDistributionSet(@NotNull Long dsID, @NotEmpty String... targetIDs);
/** /**
* Cancels given {@link Action} for given {@link Target}. The method will * Cancels given {@link Action} for given {@link Target}. The method will
* immediately add a {@link Status#CANCELED} status to the action. However, * immediately add a {@link Status#CANCELED} status to the action. However,
@@ -275,7 +243,7 @@ public interface DeploymentManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
List<Action> findActionsByRolloutAndStatus(@NotNull Rollout rollout, @NotNull Action.Status actionStatus); List<Action> findActionsByRolloutAndStatus(@NotNull Rollout rollout, @NotNull Action.Status actionStatus);
/** /**
* Retrieves all {@link Action}s of a specific target. * Retrieves all {@link Action}s of a specific target.
* *
@@ -407,19 +375,6 @@ public interface DeploymentManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Action findActionWithDetails(@NotNull Long actionId); Action findActionWithDetails(@NotNull Long actionId);
/**
* Retrieves all active {@link Action}s of a specific target ordered by
* action ID.
*
* @param pageable
* the pagination parameter
* @param target
* the target associated with the actions
* @return a paged list of actions associated with the given target
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<Action> findActiveActionsByTarget(@NotNull Pageable pageable, @NotNull Target target);
/** /**
* Retrieves all active {@link Action}s of a specific target ordered by * Retrieves all active {@link Action}s of a specific target ordered by
* action ID. * action ID.
@@ -431,19 +386,6 @@ public interface DeploymentManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
List<Action> findActiveActionsByTarget(@NotNull Target target); List<Action> findActiveActionsByTarget(@NotNull Target target);
/**
* Retrieves all inactive {@link Action}s of a specific target ordered by
* action ID.
*
* @param pageable
* the pagination parameter
* @param target
* the target associated with the actions
* @return a paged list of actions associated with the given target
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<Action> findInActiveActionsByTarget(@NotNull Pageable pageable, @NotNull Target target);
/** /**
* Retrieves all inactive {@link Action}s of a specific target ordered by * Retrieves all inactive {@link Action}s of a specific target ordered by
* action ID. * action ID.

View File

@@ -10,17 +10,21 @@ package org.eclipse.hawkbit.repository;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Set;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; 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.DistributionSetCreationFailedMissingMandatoryModuleException;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.EntityReadOnlyException; import org.eclipse.hawkbit.repository.exception.EntityReadOnlyException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException; import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException; 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.Action;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetFilter; import org.eclipse.hawkbit.repository.model.DistributionSetFilter;
@@ -29,10 +33,12 @@ import org.eclipse.hawkbit.repository.model.DistributionSetMetadata;
import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult; import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult;
import org.eclipse.hawkbit.repository.model.DistributionSetType; 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.SoftwareModule;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.model.Tag; import org.eclipse.hawkbit.repository.model.Tag;
import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetInfo;
import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
@@ -47,14 +53,27 @@ public interface DistributionSetManagement {
/** /**
* Assigns {@link SoftwareModule} to existing {@link DistributionSet}. * Assigns {@link SoftwareModule} to existing {@link DistributionSet}.
* *
* @param ds * @param setId
* to assign and update * to assign and update
* @param softwareModules * @param moduleIds
* to get assigned * to get assigned
* @return the updated {@link DistributionSet}. * @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) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSet assignSoftwareModules(@NotNull DistributionSet ds, Set<SoftwareModule> softwareModules); DistributionSet assignSoftwareModules(@NotNull Long setId, @NotEmpty Collection<Long> moduleIds);
/** /**
* Assign a {@link DistributionSetTag} assignment to given * Assign a {@link DistributionSetTag} assignment to given
@@ -99,84 +118,92 @@ public interface DistributionSetManagement {
/** /**
* Creates a new {@link DistributionSet}. * Creates a new {@link DistributionSet}.
* *
* @param dSet * @param create
* {@link DistributionSet} to be created * {@link DistributionSet} to be created
* @return the new persisted {@link DistributionSet} * @return the new persisted {@link DistributionSet}
* *
* @throws EntityAlreadyExistsException * @throws EntityNotFoundException
* if a given entity already exists * if a provided linked entity does not exists
* ({@link DistributionSet#getModules()} or
* {@link DistributionSet#getType()})
* @throws DistributionSetCreationFailedMissingMandatoryModuleException * @throws DistributionSetCreationFailedMissingMandatoryModuleException
* is {@link DistributionSet} does not contain mandatory * is {@link DistributionSet} does not contain mandatory
* {@link SoftwareModule}s. * {@link SoftwareModule}s.
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) @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. * creates a list of distribution set meta data entries.
* *
* @param dsId
* if the {@link DistributionSet} the metadata has to be created
* for
* @param metadata * @param metadata
* the meta data entries to create or update * the meta data entries to create or update
* @return the updated or created distribution set meta data entries * @return the updated or created distribution set meta data entries
*
* @throws EntityNotFoundException
* if given set does not exist
* @throws EntityAlreadyExistsException * @throws EntityAlreadyExistsException
* in case one of the meta data entry already exists for the * in case one of the meta data entry already exists for the
* specific key * specific key
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
List<DistributionSetMetadata> createDistributionSetMetadata(@NotEmpty Collection<DistributionSetMetadata> metadata); List<DistributionSetMetadata> createDistributionSetMetadata(@NotNull Long dsId,
@NotEmpty Collection<MetaData> metadata);
/**
* creates or updates a single distribution set meta data entry.
*
* @param metadata
* the meta data entry to create or update
* @return the updated or created distribution set meta data entry
* @throws EntityAlreadyExistsException
* in case the meta data entry already exists for the specific
* key
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetMetadata createDistributionSetMetadata(@NotNull DistributionSetMetadata metadata);
/** /**
* Creates multiple {@link DistributionSet}s. * Creates multiple {@link DistributionSet}s.
* *
* @param distributionSets * @param creates
* to be created * to be created
* @return the new {@link DistributionSet}s * @return the new {@link DistributionSet}s
* @throws EntityAlreadyExistsException * @throws EntityNotFoundException
* if a given entity already exists * if a provided linked entity does not exists
* ({@link DistributionSet#getModules()} or
* {@link DistributionSet#getType()})
* @throws DistributionSetCreationFailedMissingMandatoryModuleException * @throws DistributionSetCreationFailedMissingMandatoryModuleException
* is {@link DistributionSet} does not contain mandatory * is {@link DistributionSet} does not contain mandatory
* {@link SoftwareModule}s. * {@link SoftwareModule}s.
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
List<DistributionSet> createDistributionSets(@NotNull Collection<DistributionSet> distributionSets); List<DistributionSet> createDistributionSets(@NotNull Collection<DistributionSetCreate> creates);
/** /**
* Creates new {@link DistributionSetType}. * Creates new {@link DistributionSetType}.
* *
* @param type * @param create
* to 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) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
DistributionSetType createDistributionSetType(@NotNull DistributionSetType type); DistributionSetType createDistributionSetType(@NotNull DistributionSetTypeCreate create);
/** /**
* Creates multiple {@link DistributionSetType}s. * Creates multiple {@link DistributionSetType}s.
* *
* @param types * @param creates
* to 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) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
List<DistributionSetType> createDistributionSetTypes(@NotNull Collection<DistributionSetType> types); List<DistributionSetType> createDistributionSetTypes(@NotNull Collection<DistributionSetTypeCreate> creates);
/** /**
* <p> * <p>
* {@link DistributionSet} can be deleted/erased from the repository if they * {@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}.
* </p> * </p>
* *
* <p> * <p>
@@ -193,8 +220,8 @@ public interface DistributionSetManagement {
/** /**
* Deleted {@link DistributionSet}s by their IDs. That is either a soft * Deleted {@link DistributionSet}s by their IDs. That is either a soft
* delete of the entities have been linked to an {@link UpdateAction} before * delete of the entities have been linked to an {@link Action} before or a
* or a hard delete if not. * hard delete if not.
* *
* @param distributionSetIDs * @param distributionSetIDs
* to be deleted * to be deleted
@@ -205,13 +232,16 @@ public interface DistributionSetManagement {
/** /**
* deletes a distribution set meta data entry. * deletes a distribution set meta data entry.
* *
* @param distributionSet * @param dsId
* where meta data has to be deleted * where meta data has to be deleted
* @param key * @param key
* of the meta data element * of the meta data element
*
* @throws EntityNotFoundException
* if given set does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @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. * 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. * Find {@link DistributionSet} based on given ID without details, e.g.
* {@link DistributionSet#getAgentHub()}. * {@link DistributionSet#getModules()}.
* *
* @param distid * @param distid
* to look for. * to look for.
@@ -245,7 +275,7 @@ public interface DistributionSetManagement {
/** /**
* Find {@link DistributionSet} based on given ID including (lazy loaded) * 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 * Note: for performance reasons it is recommended to use
* {@link #findDistributionSetById(Long)} if details are not necessary. * {@link #findDistributionSetById(Long)} if details are not necessary.
@@ -319,9 +349,6 @@ public interface DistributionSetManagement {
* Retrieves {@link DistributionSet} List for overview purposes (no * Retrieves {@link DistributionSet} List for overview purposes (no
* {@link SoftwareModule}s and {@link DistributionSetTag}s). * {@link SoftwareModule}s and {@link DistributionSetTag}s).
* *
* Please use {@link #findDistributionSetListWithDetails(Iterable)} if
* details are required.
*
* @param dist * @param dist
* List of {@link DistributionSet} IDs to be found * List of {@link DistributionSet} IDs to be found
* @return the found {@link DistributionSet}s * @return the found {@link DistributionSet}s
@@ -343,9 +370,6 @@ public interface DistributionSetManagement {
* to <code>true</code> for returning only completed distribution * to <code>true</code> for returning only completed distribution
* sets or <code>false</code> for only incomplete ones nor * sets or <code>false</code> for only incomplete ones nor
* <code>null</code> to return both. * <code>null</code> to return both.
* @param complete
* set to if <code>false</code> incomplete DS should also be
* shown.
* *
* *
* @return all found {@link DistributionSet}s * @return all found {@link DistributionSet}s
@@ -363,9 +387,9 @@ public interface DistributionSetManagement {
* the pagination parameter * the pagination parameter
* @param deleted * @param deleted
* if TRUE, {@link DistributionSet}s marked as deleted are * if TRUE, {@link DistributionSet}s marked as deleted are
* returned. If FALSE, on {@link DistributionSet}s with * returned. If FALSE, on {@link DistributionSet}s not marked as
* {@link DistributionSet#isDeleted()} == FALSE are returned. * deleted are returned. <code>null</code> if both are to be
* <code>null</code> if both are to be returned * returned
* @return all found {@link DistributionSet}s * @return all found {@link DistributionSet}s
* *
* @throws RSQLParameterUnsupportedFieldException * @throws RSQLParameterUnsupportedFieldException
@@ -383,7 +407,7 @@ public interface DistributionSetManagement {
* following order: * following order:
* <p> * <p>
* 1) {@link DistributionSet}s which have the given {@link Target} as * 1) {@link DistributionSet}s which have the given {@link Target} as
* {@link TargetStatus#getInstalledDistributionSet()} * {@link TargetInfo#getInstalledDistributionSet()}
* <p> * <p>
* 2) {@link DistributionSet}s which have the given {@link Target} as * 2) {@link DistributionSet}s which have the given {@link Target} as
* {@link Target#getAssignedDistributionSet()} * {@link Target#getAssignedDistributionSet()}
@@ -397,7 +421,7 @@ public interface DistributionSetManagement {
* has details of filters to be applied * has details of filters to be applied
* @param assignedOrInstalled * @param assignedOrInstalled
* the controllerID of the Target to be ordered by * the controllerID of the Target to be ordered by
* @return * @return {@link DistributionSet}s
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSet> findDistributionSetsAllOrderedByLinkTarget(@NotNull Pageable pageable, Page<DistributionSet> findDistributionSetsAllOrderedByLinkTarget(@NotNull Pageable pageable,
@@ -471,8 +495,8 @@ public interface DistributionSetManagement {
/** /**
* finds a single distribution set meta data by its id. * finds a single distribution set meta data by its id.
* *
* @param distributionSet * @param setId
* where meta data has to rind * of the {@link DistributionSet}
* @param key * @param key
* of the meta data element * of the meta data element
* @return the found DistributionSetMetadata or {@code null} if not exits * @return the found DistributionSetMetadata or {@code null} if not exits
@@ -480,7 +504,7 @@ public interface DistributionSetManagement {
* in case the meta data does not exists for the given key * in case the meta data does not exists for the given key
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @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 * Checks if a {@link DistributionSet} is currently in use by a target in
@@ -495,7 +519,7 @@ public interface DistributionSetManagement {
boolean isDistributionSetInUse(@NotNull DistributionSet distributionSet); boolean isDistributionSetInUse(@NotNull DistributionSet distributionSet);
/** /**
* {@link Entity} based method call for * entity based method call for
* {@link #toggleTagAssignment(Collection, String)}. * {@link #toggleTagAssignment(Collection, String)}.
* *
* @param sets * @param sets
@@ -540,14 +564,21 @@ public interface DistributionSetManagement {
* Unassigns a {@link SoftwareModule} form an existing * Unassigns a {@link SoftwareModule} form an existing
* {@link DistributionSet}. * {@link DistributionSet}.
* *
* @param ds * @param setId
* to get unassigned form * to get unassigned form
* @param softwareModule * @param moduleId
* to get unassigned * to be unassigned
* @return the updated {@link DistributionSet}. * @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.
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSet unassignSoftwareModule(@NotNull DistributionSet ds, @NotNull SoftwareModule softwareModule); DistributionSet unassignSoftwareModule(@NotNull Long setId, @NotNull Long moduleId);
/** /**
* Unassign a {@link DistributionSetTag} assignment to given * Unassign a {@link DistributionSetTag} assignment to given
@@ -565,43 +596,118 @@ public interface DistributionSetManagement {
/** /**
* Updates existing {@link DistributionSet}. * Updates existing {@link DistributionSet}.
* *
* @param ds * @param update
* to update * to update
* @return the saved {@link Entity}. *
* @throws NullPointerException * @return the saved entity.
* of {@link DistributionSet#getId()} is <code>null</code> *
* @throw DataDependencyViolationException in case of illegal update * @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) @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. * updates a distribution set meta data value if corresponding entry exists.
* *
* @param metadata * @param dsId
* the meta data entry to be updated * {@link DistributionSet} of the meta data entry to be updated
* @param md
* meta data entry to be updated
* @return the updated meta data entry * @return the updated meta data entry
*
* @throws EntityNotFoundException * @throws EntityNotFoundException
* in case the meta data entry does not exists and cannot be * in case the meta data entry does not exists and cannot be
* updated * updated
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @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 * Updates existing {@link DistributionSetType}. Resets assigned
* is not possible to change the {@link DistributionSetTypeElement}s while * {@link SoftwareModuleType}s as well and sets as provided.
* the DS type is already in use.
* *
* @param dsType * @param update
* to 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 * @throws EntityReadOnlyException
* if use tries to change the {@link DistributionSetTypeElement} * if the {@link DistributionSetType} is already in use by a
* s while the DS type is already in use. * {@link DistributionSet} and user tries to change list of
* {@link SoftwareModuleType}s
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetType updateDistributionSetType(@NotNull DistributionSetType dsType); 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<Long> 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 the {@link DistributionSetType} while it is already in use
* by a {@link DistributionSet}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetType assignMandatorySoftwareModuleTypes(@NotNull Long dsTypeId,
@NotEmpty Collection<Long> softwareModuleTypes);
} }

View File

@@ -8,28 +8,20 @@
*/ */
package org.eclipse.hawkbit.repository; package org.eclipse.hawkbit.repository;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.builder.ActionStatusBuilder;
import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.builder.DistributionSetBuilder;
import org.eclipse.hawkbit.repository.model.ActionStatus; import org.eclipse.hawkbit.repository.builder.DistributionSetTypeBuilder;
import org.eclipse.hawkbit.repository.model.Artifact; 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.BaseEntity;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.MetaData;
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.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.NotEmpty;
/** /**
@@ -40,346 +32,65 @@ import org.hibernate.validator.constraints.NotEmpty;
public interface EntityFactory { public interface EntityFactory {
/** /**
* Generates an empty {@link Action} without persisting it. * @return {@link ActionStatusBuilder} object
*
* @return {@link Action} object
*/ */
Action generateAction(); ActionStatusBuilder actionStatus();
/** /**
* Generates an empty {@link ActionStatus} object without persisting it. * @return {@link DistributionSetBuilder} object
*
* @return {@link ActionStatus} object
*/ */
ActionStatus generateActionStatus(); DistributionSetBuilder distributionSet();
/** /**
* Generates an {@link ActionStatus} object without persisting it. * Generates an {@link MetaData} element 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<String> messages);
/**
* Generates an {@link ActionStatus} object without persisting it.
*
* @param action
* the {@link ActionStatus} belongs to.
* @param status
* as reflected by this {@link ActionStatus}.
* @param occurredAt
* time in {@link TimeUnit#MILLISECONDS} GMT when the status
* change happened.
* @param message
* optional comment
*
* @return {@link ActionStatus} object
*/
ActionStatus generateActionStatus(@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<SoftwareModule> moduleList);
/**
* Generates an empty {@link DistributionSetMetadata} element without
* persisting it.
*
* @return {@link DistributionSetMetadata} object
*/
DistributionSetMetadata generateDistributionSetMetadata();
/**
* Generates an {@link DistributionSetMetadata} element without persisting
* it.
*
* @param distributionSet
* {@link DistributionSetMetadata#getDistributionSet()}
* @param key * @param key
* {@link DistributionSetMetadata#getKey()} * {@link MetaData#getKey()}
* @param value * @param value
* {@link DistributionSetMetadata#getValue()} * {@link MetaData#getValue()}
* *
* @return {@link DistributionSetMetadata} object * @return {@link MetaData} object
*/ */
DistributionSetMetadata generateDistributionSetMetadata(@NotNull DistributionSet distributionSet, MetaData generateMetadata(@NotEmpty String key, @NotNull String value);
@NotNull String key, String value);
/** /**
* Generates an empty {@link DistributionSetTag} without persisting it. * @return {@link TagBuilder} object
*
* @return {@link DistributionSetTag} object
*/ */
DistributionSetTag generateDistributionSetTag(); TagBuilder tag();
/** /**
* Generates a {@link DistributionSetTag} without persisting it. * @return {@link RolloutGroupBuilder} object
*
* @param name
* of the tag
* @return {@link DistributionSetTag} object
*/ */
DistributionSetTag generateDistributionSetTag(@NotNull String name); RolloutGroupBuilder rolloutGroup();
/** /**
* Generates a {@link DistributionSetTag} without persisting it. * @return {@link DistributionSetTypeBuilder} object
*
* @param name
* of the tag
* @param description
* of the tag
* @param colour
* of the tag
* @return {@link DistributionSetTag} object
*/ */
DistributionSetTag generateDistributionSetTag(@NotNull String name, String description, String colour); DistributionSetTypeBuilder distributionSetType();
/** /**
* Generates an empty {@link DistributionSetType} without persisting it. * @return {@link RolloutBuilder} object
*
* @return {@link DistributionSetType} object
*/ */
DistributionSetType generateDistributionSetType(); RolloutBuilder rollout();
/** /**
* Generates a {@link DistributionSetType} without persisting it. * @return {@link SoftwareModuleBuilder} object
*
* @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); SoftwareModuleBuilder softwareModule();
/** /**
* Generates an empty {@link Rollout} without persisting it. * @return {@link SoftwareModuleTypeBuilder} object
*
* @return {@link Rollout} object
*/ */
Rollout generateRollout(); SoftwareModuleTypeBuilder softwareModuleType();
/** /**
* Generates an empty {@link RolloutGroup} without persisting it. * @return {@link TargetBuilder} object
*
* @return {@link RolloutGroup} object
*/ */
RolloutGroup generateRolloutGroup(); TargetBuilder target();
/** /**
* Generates an empty {@link SoftwareModule} without persisting it. * @return {@link TargetFilterQueryBuilder} object
*
* @return {@link SoftwareModule} object
*/ */
SoftwareModule generateSoftwareModule(); TargetFilterQueryBuilder targetFilterQuery();
/**
* 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()}
* @param value
* {@link SoftwareModuleMetadata#getValue()}
*
* @return {@link SoftwareModuleMetadata} object
*/
SoftwareModuleMetadata generateSoftwareModuleMetadata(@NotNull SoftwareModule softwareModule, @NotNull String key,
String value);
/**
* Generates an empty {@link SoftwareModuleType} without persisting it.
*
* @return {@link SoftwareModuleType} object
*/
SoftwareModuleType generateSoftwareModuleType();
/**
* Generates a {@link SoftwareModuleType} without persisting it.
*
* @param key
* {@link SoftwareModuleType#getKey()}
* @param name
* {@link SoftwareModuleType#getName()}
* @param description
* {@link SoftwareModuleType#getDescription()}
* @param maxAssignments
* {@link SoftwareModuleType#getMaxAssignments()}
*
* @return {@link SoftwareModuleType} object
*/
SoftwareModuleType generateSoftwareModuleType(@NotNull String key, @NotNull String name, String description,
int maxAssignments);
/**
* Generates an empty {@link Target} without persisting it.
* {@link Target#getSecurityToken()} is generated.
*
* @param controllerID
* of the {@link Target}
*
* @return {@link Target} object
*/
Target generateTarget(@NotEmpty String controllerID);
/**
* 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 <code>null</code>.
*
* @return {@link Target} object
*/
Target generateTarget(@NotEmpty String controllerID, String securityToken);
/**
* Generates an empty {@link TargetFilterQuery} without persisting it.
*
* @return {@link TargetFilterQuery} object
*/
TargetFilterQuery generateTargetFilterQuery();
/**
* Generates an {@link TargetFilterQuery} without persisting it.
*
* @param name
* name for the filter
* @param query
* query of the filter
* @return {@link TargetFilterQuery} object
*/
TargetFilterQuery generateTargetFilterQuery(String name, String query);
/**
* 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
*/
TargetFilterQuery generateTargetFilterQuery(String name, String query, DistributionSet autoAssignDS);
/**
* 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
*/
Artifact generateArtifact();
} }

View File

@@ -83,10 +83,7 @@ public final class OffsetBasedPageRequest extends PageRequest {
return false; return false;
} }
final OffsetBasedPageRequest other = (OffsetBasedPageRequest) obj; final OffsetBasedPageRequest other = (OffsetBasedPageRequest) obj;
if (offset != other.offset) { return offset == other.offset;
return false;
}
return true;
} }
} }

View File

@@ -8,12 +8,20 @@
*/ */
package org.eclipse.hawkbit.repository; package org.eclipse.hawkbit.repository;
import java.util.List;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; 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.RSQLParameterSyntaxException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException; import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException;
import org.eclipse.hawkbit.repository.exception.RolloutIllegalStateException; 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;
import org.eclipse.hawkbit.repository.model.Rollout.RolloutStatus; import org.eclipse.hawkbit.repository.model.Rollout.RolloutStatus;
import org.eclipse.hawkbit.repository.model.RolloutGroup; import org.eclipse.hawkbit.repository.model.RolloutGroup;
@@ -25,8 +33,6 @@ import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice; import org.springframework.data.domain.Slice;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import java.util.List;
/** /**
* RolloutManagement to control rollouts e.g. like creating, starting, resuming * RolloutManagement to control rollouts e.g. like creating, starting, resuming
* and pausing rollouts. This service secures all the functionality based on the * 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 * to {@link RolloutStatus#READY} so it can be started with
* {@link #startRollout(Rollout)}. * {@link #startRollout(Rollout)}.
* *
* @param rollout * @param create
* the rollout entity to create * the rollout entity to create
* @param amountGroup * @param amountGroup
* the amount of groups to split the rollout into * the amount of groups to split the rollout into
@@ -132,11 +138,13 @@ public interface RolloutManagement {
* applied for each {@link RolloutGroup} * applied for each {@link RolloutGroup}
* @return the persisted rollout. * @return the persisted rollout.
* *
* @throws IllegalArgumentException * @throws EntityNotFoundException
* in case the given groupSize is zero or lower. * if given {@link DistributionSet} does not exist
* @throws ConstraintViolationException
* if rollout or group parameters are invalid
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE) @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 * Persists a new rollout entity. The filter within the
@@ -164,11 +172,14 @@ public interface RolloutManagement {
* RolloutGroup itself * RolloutGroup itself
* @return the persisted rollout. * @return the persisted rollout.
* *
* @throws IllegalArgumentException * @throws EntityNotFoundException
* in case the given groupSize is zero or lower. * if given {@link DistributionSet} does not exist
* @throws ConstraintViolationException
* if rollout or group parameters are invalid
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE)
Rollout createRollout(@NotNull Rollout rollout, @NotNull List<RolloutGroup> groups, RolloutGroupConditions conditions); Rollout createRollout(@NotNull RolloutCreate rollout, @NotNull List<RolloutGroupCreate> groups,
RolloutGroupConditions conditions);
/** /**
* Can be called on a Rollout in {@link RolloutStatus#CREATING} to * Can be called on a Rollout in {@link RolloutStatus#CREATING} to
@@ -184,8 +195,8 @@ public interface RolloutManagement {
* @param rollout * @param rollout
* the rollout * the rollout
*/ */
void fillRolloutGroupsWithTargets(final Rollout rollout); @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE)
void fillRolloutGroupsWithTargets(@NotNull Long rollout);
/** /**
* Retrieves all rollouts. * Retrieves all rollouts.
@@ -344,12 +355,16 @@ public interface RolloutManagement {
/** /**
* Update rollout details. * Update rollout details.
* *
* @param rollout * @param update
* rollout to be updated * rollout to be updated
* @param name
* to update or <code>null</code>
* @param description
* to update or <code>null</code>
* *
* @return Rollout updated rollout * @return Rollout updated rollout
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE)
Rollout updateRollout(@NotNull Rollout rollout); Rollout updateRollout(@NotNull RolloutUpdate update);
} }

View File

@@ -14,12 +14,17 @@ import java.util.List;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; 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.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException; import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException; import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException;
import org.eclipse.hawkbit.repository.model.AssignedSoftwareModule; import org.eclipse.hawkbit.repository.model.AssignedSoftwareModule;
import org.eclipse.hawkbit.repository.model.DistributionSet; 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.SoftwareModule;
import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
@@ -67,29 +72,31 @@ public interface SoftwareManagement {
/** /**
* Create {@link SoftwareModule}s in the repository. * Create {@link SoftwareModule}s in the repository.
* *
* @param swModules * @param creates
* {@link SoftwareModule}s to create * {@link SoftwareModule}s to create
* @return SoftwareModule * @return SoftwareModule
* @throws EntityAlreadyExistsException * @throws EntityAlreadyExistsException
* if a given entity already exists * if a given entity already exists
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
List<SoftwareModule> createSoftwareModule(@NotNull Collection<SoftwareModule> swModules); List<SoftwareModule> createSoftwareModule(@NotNull Collection<SoftwareModuleCreate> creates);
/** /**
* *
* @param swModule * @param create
* SoftwareModule to create * SoftwareModule to create
* @return SoftwareModule * @return SoftwareModule
* @throws EntityAlreadyExistsException * @throws EntityAlreadyExistsException
* if a given entity already exists * if a given entity already exists
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) @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. * creates a list of software module meta data entries.
* *
* @param moduleId
* the metadata belongs to
* @param metadata * @param metadata
* the meta data entries to create or update * the meta data entries to create or update
* @return the updated or created software module meta data entries * @return the updated or created software module meta data entries
@@ -98,11 +105,14 @@ public interface SoftwareManagement {
* specific key * specific key
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
List<SoftwareModuleMetadata> createSoftwareModuleMetadata(@NotNull Collection<SoftwareModuleMetadata> metadata); List<SoftwareModuleMetadata> createSoftwareModuleMetadata(@NotNull Long moduleId,
@NotNull Collection<MetaData> metadata);
/** /**
* creates or updates a single software module meta data entry. * creates or updates a single software module meta data entry.
* *
* @param moduleId
* the metadata belongs to
* @param metadata * @param metadata
* the meta data entry to create or update * the meta data entry to create or update
* @return the updated or created software module meta data entry * @return the updated or created software module meta data entry
@@ -111,27 +121,27 @@ public interface SoftwareManagement {
* key * key
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
SoftwareModuleMetadata createSoftwareModuleMetadata(@NotNull SoftwareModuleMetadata metadata); SoftwareModuleMetadata createSoftwareModuleMetadata(@NotNull Long moduleId, @NotNull MetaData metadata);
/** /**
* Creates multiple {@link SoftwareModuleType}s. * Creates multiple {@link SoftwareModuleType}s.
* *
* @param types * @param creates
* to create * to create
* @return created Entity * @return created Entity
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
List<SoftwareModuleType> createSoftwareModuleType(@NotNull Collection<SoftwareModuleType> types); List<SoftwareModuleType> createSoftwareModuleType(@NotNull Collection<SoftwareModuleTypeCreate> creates);
/** /**
* Creates new {@link SoftwareModuleType}. * Creates new {@link SoftwareModuleType}.
* *
* @param type * @param create
* to create * to create
* @return created Entity * @return created Entity
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
SoftwareModuleType createSoftwareModuleType(@NotNull SoftwareModuleType type); SoftwareModuleType createSoftwareModuleType(@NotNull SoftwareModuleTypeCreate create);
/** /**
* Deletes the given {@link SoftwareModule} Entity. * Deletes the given {@link SoftwareModule} Entity.
@@ -198,6 +208,17 @@ public interface SoftwareManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Slice<SoftwareModule> findSoftwareModuleByFilters(@NotNull Pageable pageable, String searchText, Long typeId); Slice<SoftwareModule> 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<SoftwareModuleType> findSoftwareModuleTypesById(@NotEmpty Collection<Long> ids);
/** /**
* Finds {@link SoftwareModule} by given id. * Finds {@link SoftwareModule} by given id.
* *
@@ -412,46 +433,57 @@ public interface SoftwareManagement {
* {@link SoftwareModule#getDescription()} * {@link SoftwareModule#getDescription()}
* {@link SoftwareModule#getVendor()}. * {@link SoftwareModule#getVendor()}.
* *
* @param sm * @param moduleId
* to update * to update
* @param description
* to update or <code>null</code>
* @param vendor
* to update or <code>null</code>
*
* @throws EntityNotFoundException
* if given module does not exist
* *
* @return the saved Entity. * @return the saved Entity.
*
* @throws NullPointerException
* of {@link SoftwareModule#getId()} is <code>null</code>
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @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. * updates a distribution set meta data value if corresponding entry exists.
* *
* @param moduleId
* the metadata belongs to
* @param metadata * @param metadata
* the meta data entry to be updated * the meta data entry to be updated
*
*
* @return the updated meta data entry * @return the updated meta data entry
* @throws EntityNotFoundException * @throws EntityNotFoundException
* in case the meta data entry does not exists and cannot be * in case the meta data entry does not exists and cannot be
* updated * updated
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @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 * Updates existing {@link SoftwareModuleType}.
* {@link SoftwareModuleType#getDescription()} and
* {@link SoftwareModuleType#getColour()}.
* *
* @param sm * @param update
* to update * to update
*
* @return updated Entity * @return updated Entity
*
* @throws EntityNotFoundException
* in case the {@link SoftwareModuleType} does not exists and
* cannot be updated
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @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. * Finds all meta data by the given software module id.
* *
* @param softwareModuleId * @param moduleId
* the software module id to retrieve the meta data from * the software module id to retrieve the meta data from
* *
* *

View File

@@ -85,14 +85,14 @@ public interface SystemManagement {
TenantMetaData getTenantMetadata(@NotNull String tenant); 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 * to update
* @return updated {@link TenantMetaData} entity * @return updated {@link TenantMetaData} entity
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_TENANT_CONFIGURATION) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_TENANT_CONFIGURATION)
TenantMetaData updateTenantMetadata(@NotNull TenantMetaData metaData); TenantMetaData updateTenantMetadata(@NotNull Long defaultDsType);
/** /**
* Returns {@link TenantMetaData} of given tenant ID. * Returns {@link TenantMetaData} of given tenant ID.

View File

@@ -14,7 +14,10 @@ import java.util.List;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; 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.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException; import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException; import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
@@ -44,7 +47,7 @@ public interface TagManagement {
/** /**
* Creates a {@link DistributionSet}. * Creates a {@link DistributionSet}.
* *
* @param distributionSetTag * @param create
* to be created. * to be created.
* @return the new {@link DistributionSet} * @return the new {@link DistributionSet}
* @throws EntityAlreadyExistsException * @throws EntityAlreadyExistsException
@@ -52,24 +55,24 @@ public interface TagManagement {
* *
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
DistributionSetTag createDistributionSetTag(@NotNull DistributionSetTag distributionSetTag); DistributionSetTag createDistributionSetTag(@NotNull TagCreate create);
/** /**
* Creates multiple {@link DistributionSetTag}s. * Creates multiple {@link DistributionSetTag}s.
* *
* @param distributionSetTags * @param creates
* to be created * to be created
* @return the new {@link DistributionSetTag} * @return the new {@link DistributionSetTag}
* @throws EntityAlreadyExistsException * @throws EntityAlreadyExistsException
* if a given entity already exists * if a given entity already exists
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
List<DistributionSetTag> createDistributionSetTags(@NotNull Collection<DistributionSetTag> distributionSetTags); List<DistributionSetTag> createDistributionSetTags(@NotNull Collection<TagCreate> creates);
/** /**
* Creates a new {@link TargetTag}. * Creates a new {@link TargetTag}.
* *
* @param targetTag * @param create
* to be created * to be created
* *
* @return the new created {@link TargetTag} * @return the new created {@link TargetTag}
@@ -78,12 +81,12 @@ public interface TagManagement {
* if given object already exists * if given object already exists
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET)
TargetTag createTargetTag(@NotNull TargetTag targetTag); TargetTag createTargetTag(@NotNull TagCreate create);
/** /**
* created multiple {@link TargetTag}s. * created multiple {@link TargetTag}s.
* *
* @param targetTags * @param creates
* to be created * to be created
* @return the new created {@link TargetTag}s * @return the new created {@link TargetTag}s
* *
@@ -91,7 +94,7 @@ public interface TagManagement {
* if given object has already an ID. * if given object has already an ID.
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET)
List<TargetTag> createTargetTags(@NotNull Collection<TargetTag> targetTags); List<TargetTag> createTargetTags(@NotNull Collection<TagCreate> creates);
/** /**
* Deletes {@link DistributionSetTag} by given * Deletes {@link DistributionSetTag} by given
@@ -226,23 +229,30 @@ public interface TagManagement {
/** /**
* Updates an existing {@link DistributionSetTag}. * Updates an existing {@link DistributionSetTag}.
* *
* @param distributionSetTag * @param update
* to be updated * to be updated
*
* @return the updated {@link DistributionSet} * @return the updated {@link DistributionSet}
* @throws NullPointerException *
* of {@link DistributionSetTag#getName()} is <code>null</code> * @throws EntityNotFoundException
* in case the {@link DistributionSetTag} does not exists and
* cannot be updated
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetTag updateDistributionSetTag(@NotNull DistributionSetTag distributionSetTag); DistributionSetTag updateDistributionSetTag(@NotNull TagUpdate update);
/** /**
* updates the {@link TargetTag}. * updates the {@link TargetTag}.
* *
* @param targetTag * @param update
* the {@link TargetTag} with updated values * the {@link TargetTag} with updated values
* @return the updated {@link TargetTag} * @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) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET)
TargetTag updateTargetTag(@NotNull TargetTag targetTag); TargetTag updateTargetTag(@NotNull TagUpdate update);
} }

View File

@@ -11,6 +11,9 @@ package org.eclipse.hawkbit.repository;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; 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.RSQLParameterSyntaxException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException; import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
@@ -28,11 +31,12 @@ public interface TargetFilterQueryManagement {
/** /**
* creating new {@link TargetFilterQuery}. * creating new {@link TargetFilterQuery}.
* *
* @param customTargetFilter * @param create
* to create
* @return the created {@link TargetFilterQuery} * @return the created {@link TargetFilterQuery}
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET)
TargetFilterQuery createTargetFilterQuery(@NotNull TargetFilterQuery customTargetFilter); TargetFilterQuery createTargetFilterQuery(@NotNull TargetFilterQueryCreate create);
/** /**
* Delete target filter query. * Delete target filter query.
@@ -73,6 +77,7 @@ public interface TargetFilterQueryManagement {
/** /**
* Counts all target filter queries * Counts all target filter queries
*
* @return the number of all target filter queries * @return the number of all target filter queries
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
@@ -135,7 +140,8 @@ public interface TargetFilterQueryManagement {
DistributionSet distributionSet, String rsqlParam); 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} * @return the page with the found {@link TargetFilterQuery}
@@ -169,10 +175,32 @@ public interface TargetFilterQueryManagement {
/** /**
* updates the {@link TargetFilterQuery}. * updates the {@link TargetFilterQuery}.
* *
* @param targetFilterQuery * @param update
* to be updated * to be updated
*
* @return the updated {@link TargetFilterQuery} * @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) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET)
TargetFilterQuery updateTargetFilterQuery(@NotNull TargetFilterQuery targetFilterQuery); TargetFilterQuery updateTargetFilterQuery(TargetFilterQueryUpdate update);
/**
* updates the {@link TargetFilterQuery#getAutoAssignDistributionSet()}.
*
* @param queryId
* to be updated
* @param dsId
* to be updated or <code>null</code>
* @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 updateTargetFilterQueryAutoAssignDS(Long queryId, Long dsId);
} }

View File

@@ -8,14 +8,16 @@
*/ */
package org.eclipse.hawkbit.repository; package org.eclipse.hawkbit.repository;
import java.net.URI;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; 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.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException; import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException;
import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException; import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
@@ -136,37 +138,14 @@ public interface TargetManagement {
/** /**
* creating a new {@link Target}. * creating a new {@link Target}.
* *
* @param target * @param create
* to be created * to be created
* @return the created {@link Target} * @return the created {@link Target}
* *
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET + SpringEvalExpressions.HAS_AUTH_OR @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER) + SpringEvalExpressions.IS_CONTROLLER)
Target createTarget(@NotNull Target target); Target createTarget(@NotNull TargetCreate create);
/**
* creating new {@link Target}s including poll status data. useful
* especially in plug and play scenarios.
*
* @param target
* to be created *
* @param status
* of the target
* @param lastTargetQuery
* if a plug and play case
* @param address
* if a plug and play case
*
* @throws EntityAlreadyExistsException
* if {@link Target} with given {@link Target#getControllerId()}
* already exists.
*
* @return created {@link Target}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER)
Target createTarget(@NotNull Target target, @NotNull TargetUpdateStatus status, Long lastTargetQuery, URI address);
/** /**
* creates multiple {@link Target}s. If some of the given {@link Target}s * creates multiple {@link Target}s. If some of the given {@link Target}s
@@ -174,7 +153,7 @@ public interface TargetManagement {
* thrown. {@link Target}s contain all objects of the parameter targets, * thrown. {@link Target}s contain all objects of the parameter targets,
* including duplicates. * including duplicates.
* *
* @param targets * @param creates
* to be created. * to be created.
* @return the created {@link Target}s * @return the created {@link Target}s
* *
@@ -182,7 +161,7 @@ public interface TargetManagement {
* of one of the given targets already exist. * of one of the given targets already exist.
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET)
List<Target> createTargets(@NotNull Collection<Target> targets); List<Target> createTargets(@NotNull Collection<TargetCreate> creates);
/** /**
* Deletes all targets with the given IDs. * Deletes all targets with the given IDs.
@@ -439,8 +418,8 @@ public interface TargetManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Slice<Target> findTargetByFilters(@NotNull Pageable pageable, Collection<TargetUpdateStatus> status, Slice<Target> findTargetByFilters(@NotNull Pageable pageable, Collection<TargetUpdateStatus> status,
Boolean overdueState, String searchText, Long installedOrAssignedDistributionSetId, Boolean selectTargetWithNoTag, Boolean overdueState, String searchText, Long installedOrAssignedDistributionSetId,
String... tagNames); Boolean selectTargetWithNoTag, String... tagNames);
/** /**
* retrieves {@link Target}s by the installed {@link DistributionSet}without * retrieves {@link Target}s by the installed {@link DistributionSet}without
@@ -651,23 +630,16 @@ public interface TargetManagement {
/** /**
* updates the {@link Target}. * updates the {@link Target}.
* *
* @param target * @param update
* to be updated * to be updated
*
* @return the updated {@link Target} * @return the updated {@link Target}
*
* @throws EntityNotFoundException
* if given target does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET + SpringEvalExpressions.HAS_AUTH_OR @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER) + SpringEvalExpressions.IS_CONTROLLER)
Target updateTarget(@NotNull Target target); Target updateTarget(TargetUpdate update);
/**
* updates multiple {@link Target}s.
*
* @param targets
* to be updated
* @return the updated {@link Target}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER)
List<Target> updateTargets(@NotNull Collection<Target> targets);
} }

View File

@@ -0,0 +1,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);
}

View File

@@ -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<String> 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();
}

View File

@@ -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();
}

View File

@@ -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<Long> 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();
}

View File

@@ -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();
}

View File

@@ -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<Long> 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<Long> 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();
}

View File

@@ -0,0 +1,49 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
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<Long> mandatory);
/**
* @param optional
* for {@link DistributionSetType#getOptionalModuleTypes()}
* @return updated builder instance
*/
DistributionSetTypeUpdate optional(Collection<Long> optional);
}

View File

@@ -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);
}

View File

@@ -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();
}

View File

@@ -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();
}

View File

@@ -0,0 +1,25 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository.builder;
import org.eclipse.hawkbit.repository.model.Rollout;
/**
* Builder for {@link Rollout}.
*
*/
@FunctionalInterface
public interface RolloutGroupBuilder {
/**
* @return builder instance
*/
RolloutGroupCreate create();
}

View File

@@ -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();
}

View File

@@ -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);
}

View File

@@ -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();
}

View File

@@ -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();
}

View File

@@ -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();
}

View File

@@ -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();
}

View File

@@ -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);
}

View File

@@ -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);
}

View File

@@ -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();
}

View File

@@ -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();
}

View File

@@ -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);
}

View File

@@ -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();
}

View File

@@ -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&nbsp;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();
}

View File

@@ -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();
}

View File

@@ -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();
}

View File

@@ -0,0 +1,34 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository.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);
}

View File

@@ -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&nbsp;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);
}

View File

@@ -12,7 +12,9 @@ import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.Target;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -54,7 +56,20 @@ public class TargetAssignDistributionSetEvent extends RemoteTenantAwareEvent {
} }
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) { final String controllerId, final String applicationId) {
super(actionId, tenant, applicationId); super(actionId, tenant, applicationId);
this.actionId = actionId; this.actionId = actionId;

View File

@@ -8,8 +8,8 @@
*/ */
package org.eclipse.hawkbit.repository.exception; package org.eclipse.hawkbit.repository.exception;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.exception.AbstractServerRtException; import org.eclipse.hawkbit.exception.AbstractServerRtException;
import org.eclipse.hawkbit.exception.SpServerError;
/** /**
* Thrown if artifact deletion failed. * Thrown if artifact deletion failed.

View File

@@ -8,8 +8,8 @@
*/ */
package org.eclipse.hawkbit.repository.exception; package org.eclipse.hawkbit.repository.exception;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.exception.AbstractServerRtException; import org.eclipse.hawkbit.exception.AbstractServerRtException;
import org.eclipse.hawkbit.exception.SpServerError;
/** /**
* *

View File

@@ -8,8 +8,8 @@
*/ */
package org.eclipse.hawkbit.repository.exception; package org.eclipse.hawkbit.repository.exception;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.exception.AbstractServerRtException; import org.eclipse.hawkbit.exception.AbstractServerRtException;
import org.eclipse.hawkbit.exception.SpServerError;
/** /**
* Thrown if cancelation of actions is performened where the action is not * Thrown if cancelation of actions is performened where the action is not

View File

@@ -8,8 +8,8 @@
*/ */
package org.eclipse.hawkbit.repository.exception; package org.eclipse.hawkbit.repository.exception;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.exception.AbstractServerRtException; import org.eclipse.hawkbit.exception.AbstractServerRtException;
import org.eclipse.hawkbit.exception.SpServerError;
/** /**
* {@link ConcurrentModificationException} is thrown when a given entity in's * {@link ConcurrentModificationException} is thrown when a given entity in's

View File

@@ -8,8 +8,8 @@
*/ */
package org.eclipse.hawkbit.repository.exception; package org.eclipse.hawkbit.repository.exception;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.exception.AbstractServerRtException; import org.eclipse.hawkbit.exception.AbstractServerRtException;
import org.eclipse.hawkbit.exception.SpServerError;
/** /**
* Thrown if DS creation failed. * Thrown if DS creation failed.

View File

@@ -8,8 +8,8 @@
*/ */
package org.eclipse.hawkbit.repository.exception; package org.eclipse.hawkbit.repository.exception;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.exception.AbstractServerRtException; 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.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.DistributionSetType;

View File

@@ -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);
}
}

View File

@@ -8,8 +8,8 @@
*/ */
package org.eclipse.hawkbit.repository.exception; package org.eclipse.hawkbit.repository.exception;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.exception.AbstractServerRtException; import org.eclipse.hawkbit.exception.AbstractServerRtException;
import org.eclipse.hawkbit.exception.SpServerError;
/** /**
* the {@link EntityNotFoundException} is thrown when a entity is tried find but * the {@link EntityNotFoundException} is thrown when a entity is tried find but

View File

@@ -8,8 +8,8 @@
*/ */
package org.eclipse.hawkbit.repository.exception; package org.eclipse.hawkbit.repository.exception;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.exception.AbstractServerRtException; import org.eclipse.hawkbit.exception.AbstractServerRtException;
import org.eclipse.hawkbit.exception.SpServerError;
/** /**
* the {@link EntityReadOnlyException} is thrown when a entity is in read only * the {@link EntityReadOnlyException} is thrown when a entity is in read only

View File

@@ -8,8 +8,8 @@
*/ */
package org.eclipse.hawkbit.repository.exception; package org.eclipse.hawkbit.repository.exception;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.exception.AbstractServerRtException; 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 * Thrown when force quitting an actions is not allowed. e.g. the action is not

View File

@@ -8,8 +8,8 @@
*/ */
package org.eclipse.hawkbit.repository.exception; package org.eclipse.hawkbit.repository.exception;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.exception.AbstractServerRtException; import org.eclipse.hawkbit.exception.AbstractServerRtException;
import org.eclipse.hawkbit.exception.SpServerError;
/** /**
* *

View File

@@ -8,8 +8,8 @@
*/ */
package org.eclipse.hawkbit.repository.exception; package org.eclipse.hawkbit.repository.exception;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.exception.AbstractServerRtException; 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 * Thrown if a distribution set is assigned to a a target that is incomplete

View File

@@ -8,8 +8,8 @@
*/ */
package org.eclipse.hawkbit.repository.exception; package org.eclipse.hawkbit.repository.exception;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.exception.AbstractServerRtException; import org.eclipse.hawkbit.exception.AbstractServerRtException;
import org.eclipse.hawkbit.exception.SpServerError;
/** /**
* Exception which is thrown in case the current security context object does * Exception which is thrown in case the current security context object does

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