Remove unlimited collections from the repository API (#496)

* Started to get rid of unlimited collections

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Align API usage.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* fix compile issues.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fix tests.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Remove comments

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Performance optimizations.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Remove dead code.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Allign method names

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Wait until the action update event is processed

Conflicts:
	hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AmqpMessageHandlerServiceIntegrationTest.java

Signed-off-by: SirWayne <dennis.melzer@bosch-si.com>

* Started new tag APIs

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Quotas into central interface. Tag tests added. Event names fixed.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Simplified consumer run for every tenant.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* remove unused fields.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Alligned beans.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Deprecated client methods for old resources.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fix new foreach method.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fix transaction for foreach.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Extended DS creating to handle larger volumes. Fix on Readme.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fixed simulator bug and cleaned up tests.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fix in sorting.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Remove configuration processor.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fix wrong usage of sanitize.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Missing brackets.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fix README API compatability.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fix misinterpretation of pessimistic locking exceptions.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fix stability sentence.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Code cleanup.

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>

* Fixed page calculation

Signed-off-by: kaizimmerm <kai.zimmermann@bosch-si.com>
This commit is contained in:
Kai Zimmermann
2017-05-09 16:40:49 +02:00
committed by GitHub
parent aca87464bd
commit c18e9f515e
199 changed files with 3502 additions and 1607 deletions

View File

@@ -100,4 +100,7 @@ $ java -jar ./examples/hawkbit-example-mgmt-simulator/target/hawkbit-example-mgm
hawkBit is currently in '0.X' semantic version. That is due to the need that there is still content in hawkBit that is in need for refactoring. That includes the maven module structure, Spring Boot Properties, Spring Boot auto configuration as well as internal Java APIs (e.g. the [repository API](https://github.com/eclipse/hawkbit/issues/197) ). hawkBit is currently in '0.X' semantic version. That is due to the need that there is still content in hawkBit that is in need for refactoring. That includes the maven module structure, Spring Boot Properties, Spring Boot auto configuration as well as internal Java APIs (e.g. the [repository API](https://github.com/eclipse/hawkbit/issues/197) ).
However, the external APIs (i.e. [Management API](https://github.com/eclipse/hawkbit/tree/master/hawkbit-mgmt-api), [DDI API](https://github.com/eclipse/hawkbit/tree/master/hawkbit-ddi-api), [DDI Artifact Download API](https://github.com/eclipse/hawkbit/tree/master/hawkbit-ddi-dl-api) and [DMF API](https://github.com/eclipse/hawkbit/tree/master/hawkbit-dmf/hawkbit-dmf-api) are on major version 'v1' and will be kept stable. However, the device facing [DDI API](https://github.com/eclipse/hawkbit/tree/master/hawkbit-ddi-api) is on major version 'v1' and will be kept stable.
Server facing and [DMF API](https://github.com/eclipse/hawkbit/tree/master/hawkbit-dmf/hawkbit-dmf-api) are [Management API](https://github.com/eclipse/hawkbit/tree/master/hawkbit-mgmt-api) are on v1 as well. However, we cannot fully guarantee the same stability during hawkBit's 0.X development but we will try as best we can.

View File

@@ -27,8 +27,10 @@ This can be configured/disabled by spring boot properties
## hawkBit APIs ## hawkBit APIs
The simulator supports `DDI` as well as the `DMF` integration APIs. The simulator supports `DDI` as well as the `DMF` integration APIs.
In case there is no AMQP message broker (like rabbitMQ) running, you can disable the AMQP support for the device simulator, so the simulator is not trying to connect to an amqp message broker.
Configuration property `hawkbit.device.simulator.amqp.enabled=true` In case there is no AMQP message broker (like rabbitMQ) running, you can disable the AMQP support for the device simulator, so the simulator is not trying to connect to an amqp message broker.
Configuration property `hawkbit.device.simulator.amqp.enabled=false`
## Usage ## Usage

View File

@@ -8,6 +8,7 @@
*/ */
package org.eclipse.hawkbit.mgmt.client.scenarios; package org.eclipse.hawkbit.mgmt.client.scenarios;
import java.math.BigDecimal;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.util.List; import java.util.List;
import java.util.Random; import java.util.Random;
@@ -316,31 +317,38 @@ public class ConfigurableScenario {
private void createDistributionSets(final Scenario scenario) { private void createDistributionSets(final Scenario scenario) {
LOGGER.info("Creating {} distribution sets", scenario.getDistributionSets()); LOGGER.info("Creating {} distribution sets", scenario.getDistributionSets());
final BigDecimal pages = new BigDecimal(scenario.getDistributionSets())
.divide(new BigDecimal(PAGE_SIZE), BigDecimal.ROUND_UP).max(new BigDecimal(1));
IntStream.range(0, pages.intValue()).parallel().forEach(i -> createDistributionSetPage(scenario, i));
LOGGER.info("Creating {} distribution sets -> Done", scenario.getDistributionSets());
}
private void createDistributionSetPage(final Scenario scenario, final int page) {
final List<MgmtDistributionSet> sets = distributionSetResource final List<MgmtDistributionSet> sets = distributionSetResource
.createDistributionSets(new DistributionSetBuilder().name(scenario.getDsName()).type("os_app") .createDistributionSets(new DistributionSetBuilder().name(scenario.getDsName()).type("os_app")
.version("1.0.").buildAsList(scenario.getDistributionSets())) .version("1.0.").buildAsList(calculateOffset(page),
(page + 1) * PAGE_SIZE > scenario.getDistributionSets()
? (scenario.getDistributionSets() - calculateOffset(page)) : PAGE_SIZE))
.getBody(); .getBody();
assignSoftwareModulesTo(scenario, sets); assignSoftwareModulesTo(scenario, sets);
tagDistributionSets(scenario, sets); tagDistributionSets(page, sets);
LOGGER.info("Creating {} distribution sets -> Done", scenario.getDistributionSets());
} }
private void tagDistributionSets(final Scenario scenario, final List<MgmtDistributionSet> sets) { private void tagDistributionSets(final int page, final List<MgmtDistributionSet> sets) {
for (int i = 0; i < scenario.getDsTags(); i++) { final MgmtTag tag = distributionSetTagResource
final MgmtTag tag = distributionSetTagResource .createDistributionSetTags(
.createDistributionSetTags( new TagBuilder().name("Page " + page).description("DS tag for DS page" + page).build())
new TagBuilder().name("DS Tag" + i).description("DS tag for DS " + i).build()) .getBody().get(0);
.getBody().get(0);
distributionSetTagResource.assignDistributionSets(tag.getTagId(), distributionSetTagResource.assignDistributionSets(tag.getTagId(),
sets.stream().map( sets.stream()
set -> new MgmtAssignedDistributionSetRequestBody().setDistributionSetId(set.getDsId())) .map(set -> new MgmtAssignedDistributionSetRequestBody().setDistributionSetId(set.getDsId()))
.collect(Collectors.toList())); .collect(Collectors.toList()));
}
} }
private void assignSoftwareModulesTo(final Scenario scenario, final List<MgmtDistributionSet> sets) { private void assignSoftwareModulesTo(final Scenario scenario, final List<MgmtDistributionSet> sets) {
@@ -379,8 +387,10 @@ public class ConfigurableScenario {
private void createTargets(final Scenario scenario, final List<Long> deviceGroupTags) { private void createTargets(final Scenario scenario, final List<Long> deviceGroupTags) {
LOGGER.info("Creating {} targets", scenario.getTargets()); LOGGER.info("Creating {} targets", scenario.getTargets());
IntStream.range(0, scenario.getTargets() / PAGE_SIZE).parallel() final BigDecimal pages = new BigDecimal(scenario.getTargets())
.forEach(i -> createTargetPage(scenario, i, deviceGroupTags)); .divide(new BigDecimal(PAGE_SIZE), BigDecimal.ROUND_UP).max(new BigDecimal(1));
IntStream.range(0, pages.intValue()).parallel().forEach(i -> createTargetPage(scenario, i, deviceGroupTags));
LOGGER.info("Creating {} targets -> Done", scenario.getTargets()); LOGGER.info("Creating {} targets -> Done", scenario.getTargets());
} }

View File

@@ -14,6 +14,11 @@ package org.eclipse.hawkbit.repository;
* *
*/ */
public enum TagFields implements FieldNameProvider { public enum TagFields implements FieldNameProvider {
/**
* The id field.
*/
ID("id"),
/** /**
* The name field. * The name field.
*/ */

View File

@@ -34,7 +34,6 @@ public enum TargetFilterQueryFields implements FieldNameProvider {
*/ */
AUTOASSIGNDISTRIBUTIONSET("autoAssignDistributionSet", "name", "version"); AUTOASSIGNDISTRIBUTIONSET("autoAssignDistributionSet", "name", "version");
private final String fieldName; private final String fieldName;
private List<String> subEntityAttributes; private List<String> subEntityAttributes;
private boolean mapField; private boolean mapField;

View File

@@ -161,7 +161,7 @@ public class DdiArtifactDownloadTest extends AbstractDDiApiIntegrationTest {
public void downloadArtifactThroughFileName() throws Exception { public void downloadArtifactThroughFileName() throws Exception {
downLoadProgress = 1; downLoadProgress = 1;
shippedBytes = 0; shippedBytes = 0;
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).hasSize(0);
// create target // create target
final Target target = testdataFactory.createTarget(); final Target target = testdataFactory.createTarget();

View File

@@ -126,13 +126,14 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
// Retrieved is reported // Retrieved is reported
List<Action> activeActionsByTarget = deploymentManagement List<Action> activeActionsByTarget = deploymentManagement
.findActiveActionsByTarget(savedTarget.getControllerId()); .findActiveActionsByTarget(PAGE, savedTarget.getControllerId()).getContent();
assertThat(activeActionsByTarget).hasSize(1); assertThat(activeActionsByTarget).hasSize(1);
assertThat(activeActionsByTarget.get(0).getStatus()).isEqualTo(Status.RUNNING); assertThat(activeActionsByTarget.get(0).getStatus()).isEqualTo(Status.RUNNING);
final Action cancelAction = deploymentManagement.cancelAction(updateAction.getId()); final Action cancelAction = deploymentManagement.cancelAction(updateAction.getId());
activeActionsByTarget = deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId()); activeActionsByTarget = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())
.getContent();
// the canceled action should still be active! // the canceled action should still be active!
assertThat(cancelAction.isActive()).isTrue(); assertThat(cancelAction.isActive()).isTrue();
@@ -174,7 +175,8 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.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());
activeActionsByTarget = deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId()); activeActionsByTarget = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())
.getContent();
assertThat(activeActionsByTarget).hasSize(0); assertThat(activeActionsByTarget).hasSize(0);
final Action canceledAction = deploymentManagement.findAction(cancelAction.getId()).get(); final Action canceledAction = deploymentManagement.findAction(cancelAction.getId()).get();
assertThat(canceledAction.isActive()).isFalse(); assertThat(canceledAction.isActive()).isFalse();
@@ -241,14 +243,14 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
final Action cancelAction = deploymentManagement.cancelAction(updateAction.getId()); final Action cancelAction = deploymentManagement.cancelAction(updateAction.getId());
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1);
mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
+ cancelAction.getId() + "/feedback", 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(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(3); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(3);
mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
@@ -256,7 +258,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.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(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(4); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(4);
mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
@@ -265,30 +267,30 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.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(5); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(5);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1);
// cancellation canceled -> should remove the action from active // cancellation canceled -> should remove the action from active
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1);
mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
+ cancelAction.getId() + "/feedback", 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(deploymentManagement.countActionStatusAll()).isEqualTo(6); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(6);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1);
// cancellation rejected -> action still active until controller close // cancellation rejected -> action still active until controller close
// it // it
// with finished or // with finished or
// error // error
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1);
mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
+ cancelAction.getId() + "/feedback", 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(deploymentManagement.countActionStatusAll()).isEqualTo(7); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(7);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1);
// update closed -> should remove the action from active // update closed -> should remove the action from active
mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/deploymentBase/" mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/deploymentBase/"
@@ -297,7 +299,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.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(8); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(8);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(0); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(0);
} }
@Test @Test
@@ -325,12 +327,12 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(3); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(3);
// 3 update actions, 0 cancel actions // 3 update actions, 0 cancel actions
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(3); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(3);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(3); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(3);
final Action cancelAction = deploymentManagement.cancelAction(updateAction.getId()); final Action cancelAction = deploymentManagement.cancelAction(updateAction.getId());
final Action cancelAction2 = deploymentManagement.cancelAction(updateAction2.getId()); final Action cancelAction2 = deploymentManagement.cancelAction(updateAction2.getId());
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(3); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(3);
assertThat(deploymentManagement.countActionsByTarget(savedTarget.getControllerId())).isEqualTo(3); assertThat(deploymentManagement.countActionsByTarget(savedTarget.getControllerId())).isEqualTo(3);
mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
+ cancelAction.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)) + cancelAction.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON))
@@ -357,7 +359,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(7); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(7);
// 1 update actions, 1 cancel actions // 1 update actions, 1 cancel actions
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(2); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(2);
assertThat(deploymentManagement.countActionsByTarget(savedTarget.getControllerId())).isEqualTo(3); assertThat(deploymentManagement.countActionsByTarget(savedTarget.getControllerId())).isEqualTo(3);
mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
+ cancelAction2.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)) + cancelAction2.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON))
@@ -391,12 +393,12 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(10); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(10);
// 1 update actions, 0 cancel actions // 1 update actions, 0 cancel actions
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1);
final Action cancelAction3 = deploymentManagement.cancelAction(updateAction3.getId()); final Action cancelAction3 = deploymentManagement.cancelAction(updateAction3.getId());
// action is in cancelling state // action is in cancelling state
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1);
assertThat(deploymentManagement.countActionsByTarget(savedTarget.getControllerId())).isEqualTo(3); assertThat(deploymentManagement.countActionsByTarget(savedTarget.getControllerId())).isEqualTo(3);
assertThat(deploymentManagement.getAssignedDistributionSet(TestdataFactory.DEFAULT_CONTROLLER_ID).get()) assertThat(deploymentManagement.getAssignedDistributionSet(TestdataFactory.DEFAULT_CONTROLLER_ID).get())
.isEqualTo(ds3); .isEqualTo(ds3);
@@ -418,7 +420,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(13); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(13);
// final status // final status
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(0); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(0);
assertThat(deploymentManagement.countActionsByTarget(savedTarget.getControllerId())).isEqualTo(3); assertThat(deploymentManagement.countActionsByTarget(savedTarget.getControllerId())).isEqualTo(3);
} }

View File

@@ -119,24 +119,26 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
final Target savedTarget = testdataFactory.createTarget("4712"); final Target savedTarget = testdataFactory.createTarget("4712");
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).isEmpty(); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).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, Lists.newArrayList(savedTarget.getControllerId())) RepositoryModelConstants.NO_FORCE_TIME, Lists.newArrayList(savedTarget.getControllerId()))
.getAssignedEntity(); .getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1);
final Action action = deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId()).get(0); final Action action = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())
.getContent().get(0);
assertThat(deploymentManagement.countActionsAll()).isEqualTo(1); assertThat(deploymentManagement.countActionsAll()).isEqualTo(1);
saved = assignDistributionSet(ds2, saved).getAssignedEntity(); saved = assignDistributionSet(ds2, saved).getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(2); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(2);
assertThat(deploymentManagement.countActionsAll()).isEqualTo(2); assertThat(deploymentManagement.countActionsAll()).isEqualTo(2);
final Action uaction = deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId()).get(0); final Action uaction = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())
.getContent().get(0);
assertThat(uaction.getDistributionSet()).isEqualTo(ds); assertThat(uaction.getDistributionSet()).isEqualTo(ds);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(2); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(2);
// Run test // Run test
long current = System.currentTimeMillis(); long current = System.currentTimeMillis();
@@ -234,7 +236,8 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
Lists.newArrayList(target.getControllerId())); Lists.newArrayList(target.getControllerId()));
final Action action = deploymentManagement final Action action = deploymentManagement
.findActiveActionsByTarget(result.getAssignedEntity().get(0).getControllerId()).get(0); .findActiveActionsByTarget(PAGE, result.getAssignedEntity().get(0).getControllerId()).getContent()
.get(0);
MvcResult mvcResult = mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant())) MvcResult mvcResult = mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
@@ -278,24 +281,26 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
final Target savedTarget = testdataFactory.createTarget("4712"); final Target savedTarget = testdataFactory.createTarget("4712");
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).isEmpty(); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).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, Lists.newArrayList(savedTarget.getControllerId())) RepositoryModelConstants.NO_FORCE_TIME, Lists.newArrayList(savedTarget.getControllerId()))
.getAssignedEntity(); .getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1);
final Action action = deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId()).get(0); final Action action = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())
.getContent().get(0);
assertThat(deploymentManagement.countActionsAll()).isEqualTo(1); assertThat(deploymentManagement.countActionsAll()).isEqualTo(1);
saved = assignDistributionSet(ds2, saved).getAssignedEntity(); saved = assignDistributionSet(ds2, saved).getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(2); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(2);
assertThat(deploymentManagement.countActionsAll()).isEqualTo(2); assertThat(deploymentManagement.countActionsAll()).isEqualTo(2);
final Action uaction = deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId()).get(0); final Action uaction = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())
.getContent().get(0);
assertThat(uaction.getDistributionSet()).isEqualTo(ds); assertThat(uaction.getDistributionSet()).isEqualTo(ds);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(2); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(2);
// Run test // Run test
@@ -391,23 +396,25 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
final Target savedTarget = testdataFactory.createTarget("4712"); final Target savedTarget = testdataFactory.createTarget("4712");
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).isEmpty(); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).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(), Lists.newArrayList(savedTarget.getControllerId())).getAssignedEntity(); System.currentTimeMillis(), Lists.newArrayList(savedTarget.getControllerId())).getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(1);
final Action action = deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId()).get(0); final Action action = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())
.getContent().get(0);
assertThat(deploymentManagement.countActionsAll()).isEqualTo(1); assertThat(deploymentManagement.countActionsAll()).isEqualTo(1);
saved = assignDistributionSet(ds2, saved).getAssignedEntity(); saved = assignDistributionSet(ds2, saved).getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(2); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(2);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2);
final Action uaction = deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId()).get(0); final Action uaction = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())
.getContent().get(0);
assertThat(uaction.getDistributionSet()).isEqualTo(ds); assertThat(uaction.getDistributionSet()).isEqualTo(ds);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(2); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(2);
// Run test // Run test
@@ -538,7 +545,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
assignDistributionSet(ds.getId(), "4712"); assignDistributionSet(ds.getId(), "4712");
final Action action = deploymentManagement.findActionsByTarget(target.getControllerId(), pageReq).getContent() final Action action = deploymentManagement.findActionsByTarget(target.getControllerId(), PAGE).getContent()
.get(0); .get(0);
final String feedback = JsonBuilder.deploymentActionFeedback(action.getId().toString(), "proceeding"); final String feedback = JsonBuilder.deploymentActionFeedback(action.getId().toString(), "proceeding");
@@ -579,7 +586,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
Target myT = targetManagement.findTargetByControllerID("4712").get(); Target myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(3); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(3);
assertThat(deploymentManagement.getAssignedDistributionSet(myT.getControllerId()).get()).isEqualTo(ds3); assertThat(deploymentManagement.getAssignedDistributionSet(myT.getControllerId()).get()).isEqualTo(ds3);
assertThat(deploymentManagement.getInstalledDistributionSet(myT.getControllerId())).isNotPresent(); assertThat(deploymentManagement.getInstalledDistributionSet(myT.getControllerId())).isNotPresent();
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.UNKNOWN)) assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.UNKNOWN))
@@ -594,7 +601,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
myT = targetManagement.findTargetByControllerID("4712").get(); myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(2); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(2);
assertThat(deploymentManagement.getAssignedDistributionSet(myT.getControllerId()).get()).isEqualTo(ds3); assertThat(deploymentManagement.getAssignedDistributionSet(myT.getControllerId()).get()).isEqualTo(ds3);
assertThat(deploymentManagement.getInstalledDistributionSet(myT.getControllerId()).get()).isEqualTo(ds1); assertThat(deploymentManagement.getInstalledDistributionSet(myT.getControllerId()).get()).isEqualTo(ds1);
@@ -612,7 +619,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
myT = targetManagement.findTargetByControllerID("4712").get(); myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(1);
assertThat(deploymentManagement.getAssignedDistributionSet(myT.getControllerId()).get()).isEqualTo(ds3); assertThat(deploymentManagement.getAssignedDistributionSet(myT.getControllerId()).get()).isEqualTo(ds3);
assertThat(deploymentManagement.getInstalledDistributionSet(myT.getControllerId()).get()).isEqualTo(ds2); assertThat(deploymentManagement.getInstalledDistributionSet(myT.getControllerId()).get()).isEqualTo(ds2);
actionStatusMessages = deploymentManagement.findActionStatusAll(new PageRequest(0, 100, Direction.DESC, "id")) actionStatusMessages = deploymentManagement.findActionStatusAll(new PageRequest(0, 100, Direction.DESC, "id"))
@@ -628,7 +635,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
myT = targetManagement.findTargetByControllerID("4712").get(); myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC); assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC);
assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(0); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(0);
assertThat(deploymentManagement.getAssignedDistributionSet(myT.getControllerId()).get()).isEqualTo(ds3); assertThat(deploymentManagement.getAssignedDistributionSet(myT.getControllerId()).get()).isEqualTo(ds3);
assertThat(deploymentManagement.getInstalledDistributionSet(myT.getControllerId()).get()).isEqualTo(ds3); assertThat(deploymentManagement.getInstalledDistributionSet(myT.getControllerId()).get()).isEqualTo(ds3);
actionStatusMessages = deploymentManagement.findActionStatusAll(new PageRequest(0, 100, Direction.DESC, "id")) actionStatusMessages = deploymentManagement.findActionStatusAll(new PageRequest(0, 100, Direction.DESC, "id"))
@@ -650,7 +657,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
assertThat(targetManagement.findTargetByControllerID("4712").get().getUpdateStatus()) assertThat(targetManagement.findTargetByControllerID("4712").get().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.UNKNOWN); .isEqualTo(TargetUpdateStatus.UNKNOWN);
assignDistributionSet(ds, toAssign); assignDistributionSet(ds, toAssign);
final Action action = deploymentManagement.findActionsByDistributionSet(pageReq, ds.getId()).getContent() final Action action = deploymentManagement.findActionsByDistributionSet(PAGE, ds.getId()).getContent()
.get(0); .get(0);
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
@@ -668,7 +675,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.hasSize(1); .hasSize(1);
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC)) assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC))
.hasSize(0); .hasSize(0);
assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(0); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(0);
assertThat(deploymentManagement.countActionsByTarget(myT.getControllerId())).isEqualTo(1); assertThat(deploymentManagement.countActionsByTarget(myT.getControllerId())).isEqualTo(1);
final Iterable<ActionStatus> actionStatusMessages = deploymentManagement final Iterable<ActionStatus> actionStatusMessages = deploymentManagement
.findActionStatusAll(new PageRequest(0, 100, Direction.DESC, "id")).getContent(); .findActionStatusAll(new PageRequest(0, 100, Direction.DESC, "id")).getContent();
@@ -678,7 +685,8 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
// redo // redo
ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId()).get(); ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId()).get();
assignDistributionSet(ds, Lists.newArrayList(targetManagement.findTargetByControllerID("4712").get())); assignDistributionSet(ds, Lists.newArrayList(targetManagement.findTargetByControllerID("4712").get()));
final Action action2 = deploymentManagement.findActiveActionsByTarget(myT.getControllerId()).get(0); final Action action2 = deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())
.getContent().get(0);
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action2.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action2.getId() + "/feedback",
tenantAware.getCurrentTenant()) tenantAware.getCurrentTenant())
@@ -694,12 +702,12 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.hasSize(0); .hasSize(0);
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC)) assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC))
.hasSize(1); .hasSize(1);
assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(0); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(0);
assertThat(deploymentManagement.findInActiveActionsByTarget(myT.getControllerId())).hasSize(2); assertThat(deploymentManagement.findInActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(2);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(4); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(4);
assertThat(deploymentManagement.findActionStatusByAction(pageReq, action.getId()).getContent()).haveAtLeast(1, assertThat(deploymentManagement.findActionStatusByAction(PAGE, action.getId()).getContent()).haveAtLeast(1,
new ActionStatusCondition(Status.ERROR)); new ActionStatusCondition(Status.ERROR));
assertThat(deploymentManagement.findActionStatusByAction(pageReq, action2.getId()).getContent()).haveAtLeast(1, assertThat(deploymentManagement.findActionStatusByAction(PAGE, action2.getId()).getContent()).haveAtLeast(1,
new ActionStatusCondition(Status.FINISHED)); new ActionStatusCondition(Status.FINISHED));
} }
@@ -716,13 +724,13 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
Target myT = targetManagement.findTargetByControllerID("4712").get(); Target myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.UNKNOWN); assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.UNKNOWN);
assignDistributionSet(ds, toAssign); assignDistributionSet(ds, toAssign);
final Action action = deploymentManagement.findActionsByDistributionSet(pageReq, ds.getId()).getContent() final Action action = deploymentManagement.findActionsByDistributionSet(PAGE, ds.getId()).getContent()
.get(0); .get(0);
myT = targetManagement.findTargetByControllerID("4712").get(); myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(targetManagement.findTargetByInstalledDistributionSet(ds.getId(), pageReq)).hasSize(0); assertThat(targetManagement.findTargetByInstalledDistributionSet(ds.getId(), PAGE)).hasSize(0);
assertThat(targetManagement.findTargetByAssignedDistributionSet(ds.getId(), pageReq)).hasSize(1); assertThat(targetManagement.findTargetByAssignedDistributionSet(ds.getId(), PAGE)).hasSize(1);
// Now valid Feedback // Now valid Feedback
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
@@ -741,9 +749,9 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.hasSize(0); .hasSize(0);
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC)) assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC))
.hasSize(0); .hasSize(0);
assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(1);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(5); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(5);
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(5, assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(5,
new ActionStatusCondition(Status.RUNNING)); new ActionStatusCondition(Status.RUNNING));
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
@@ -759,9 +767,9 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.hasSize(0); .hasSize(0);
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC)) assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC))
.hasSize(0); .hasSize(0);
assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(1);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(6); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(6);
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(5, assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(5,
new ActionStatusCondition(Status.RUNNING)); new ActionStatusCondition(Status.RUNNING));
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
@@ -777,9 +785,9 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.hasSize(0); .hasSize(0);
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC)) assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC))
.hasSize(0); .hasSize(0);
assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(1);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(7); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(7);
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(6, assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(6,
new ActionStatusCondition(Status.RUNNING)); new ActionStatusCondition(Status.RUNNING));
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
@@ -789,7 +797,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
myT = targetManagement.findTargetByControllerID("4712").get(); myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(1);
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.PENDING)) assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.PENDING))
.hasSize(1); .hasSize(1);
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.ERROR)) assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.ERROR))
@@ -798,9 +806,9 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.hasSize(0); .hasSize(0);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(8); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(8);
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(7, assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(7,
new ActionStatusCondition(Status.RUNNING)); new ActionStatusCondition(Status.RUNNING));
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(1, assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(1,
new ActionStatusCondition(Status.CANCELED)); new ActionStatusCondition(Status.CANCELED));
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
@@ -810,13 +818,13 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
myT = targetManagement.findTargetByControllerID("4712").get(); myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(1);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(9); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(9);
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(6, assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(6,
new ActionStatusCondition(Status.RUNNING)); new ActionStatusCondition(Status.RUNNING));
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(1, assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(1,
new ActionStatusCondition(Status.WARNING)); new ActionStatusCondition(Status.WARNING));
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(1, assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(1,
new ActionStatusCondition(Status.CANCELED)); new ActionStatusCondition(Status.CANCELED));
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
@@ -826,24 +834,24 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
myT = targetManagement.findTargetByControllerID("4712").get(); myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC); assertThat(myT.getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC);
assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(0); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, myT.getControllerId())).hasSize(0);
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.ERROR)) assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.ERROR))
.hasSize(0); .hasSize(0);
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC)) assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC))
.hasSize(1); .hasSize(1);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(10); assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(10);
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(7, assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(7,
new ActionStatusCondition(Status.RUNNING)); new ActionStatusCondition(Status.RUNNING));
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(1, assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(1,
new ActionStatusCondition(Status.WARNING)); new ActionStatusCondition(Status.WARNING));
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(1, assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(1,
new ActionStatusCondition(Status.CANCELED)); new ActionStatusCondition(Status.CANCELED));
assertThat(deploymentManagement.findActionStatusAll(pageReq).getContent()).haveAtLeast(1, assertThat(deploymentManagement.findActionStatusAll(PAGE).getContent()).haveAtLeast(1,
new ActionStatusCondition(Status.FINISHED)); new ActionStatusCondition(Status.FINISHED));
assertThat(targetManagement.findTargetByInstalledDistributionSet(ds.getId(), pageReq)).hasSize(1); assertThat(targetManagement.findTargetByInstalledDistributionSet(ds.getId(), PAGE)).hasSize(1);
assertThat(targetManagement.findTargetByAssignedDistributionSet(ds.getId(), pageReq)).hasSize(1); assertThat(targetManagement.findTargetByAssignedDistributionSet(ds.getId(), PAGE)).hasSize(1);
} }
@Test @Test
@@ -873,8 +881,8 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
savedTarget = assignDistributionSet(savedSet, toAssign).getAssignedEntity().iterator().next(); savedTarget = assignDistributionSet(savedSet, toAssign).getAssignedEntity().iterator().next();
assignDistributionSet(savedSet2, toAssign2); assignDistributionSet(savedSet2, toAssign2);
final Action updateAction = deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId()) final Action updateAction = deploymentManagement
.get(0); .findActiveActionsByTarget(PAGE, savedTarget.getControllerId()).getContent().get(0);
// action exists but is not assigned to this target // action exists but is not assigned to this target
mvc.perform(post("/{tenant}/controller/v1/4713/deploymentBase/" + updateAction.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/4713/deploymentBase/" + updateAction.getId() + "/feedback",
@@ -907,7 +915,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
assignDistributionSet(ds.getId(), "1080"); assignDistributionSet(ds.getId(), "1080");
final Action action = deploymentManagement.findActionsByTarget(target.getControllerId(), pageReq).getContent() final Action action = deploymentManagement.findActionsByTarget(target.getControllerId(), PAGE).getContent()
.get(0); .get(0);
mvc.perform(post("/{tenant}/controller/v1/1080/deploymentBase/" + action.getId() + "/feedback", mvc.perform(post("/{tenant}/controller/v1/1080/deploymentBase/" + action.getId() + "/feedback",
@@ -929,7 +937,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
assignDistributionSet(ds.getId(), "1080"); assignDistributionSet(ds.getId(), "1080");
final Action action = deploymentManagement.findActionsByTarget(target.getControllerId(), pageReq).getContent() final Action action = deploymentManagement.findActionsByTarget(target.getControllerId(), PAGE).getContent()
.get(0); .get(0);
final String missingResultInFeedback = JsonBuilder.missingResultInFeedback(action.getId().toString(), "closed", final String missingResultInFeedback = JsonBuilder.missingResultInFeedback(action.getId().toString(), "closed",
"test"); "test");
@@ -953,7 +961,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
final DistributionSet ds = testdataFactory.createDistributionSet(""); final DistributionSet ds = testdataFactory.createDistributionSet("");
assignDistributionSet(ds.getId(), "1080"); assignDistributionSet(ds.getId(), "1080");
final Action action = deploymentManagement.findActionsByTarget(target.getControllerId(), pageReq).getContent() final Action action = deploymentManagement.findActionsByTarget(target.getControllerId(), PAGE).getContent()
.get(0); .get(0);
final String missingFinishedResultInFeedback = JsonBuilder final String missingFinishedResultInFeedback = JsonBuilder
.missingFinishedResultInFeedback(action.getId().toString(), "closed", "test"); .missingFinishedResultInFeedback(action.getId().toString(), "closed", "test");

View File

@@ -198,7 +198,8 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
assignDistributionSet(ds.getId(), "4711"); assignDistributionSet(ds.getId(), "4711");
final Action updateAction = deploymentManagement.findActiveActionsByTarget(target.getControllerId()).get(0); final Action updateAction = deploymentManagement.findActiveActionsByTarget(PAGE, target.getControllerId())
.getContent().get(0);
final String etagWithFirstUpdate = mvc final String etagWithFirstUpdate = mvc
.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant()) .perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant())
.header("If-None-Match", etag).accept(MediaType.APPLICATION_JSON)) .header("If-None-Match", etag).accept(MediaType.APPLICATION_JSON))
@@ -231,7 +232,8 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
assignDistributionSet(ds2.getId(), "4711"); assignDistributionSet(ds2.getId(), "4711");
final Action updateAction2 = deploymentManagement.findActiveActionsByTarget(target.getControllerId()).get(0); final Action updateAction2 = deploymentManagement.findActiveActionsByTarget(PAGE, target.getControllerId())
.getContent().get(0);
mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant()) mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant())
.header("If-None-Match", etagWithFirstUpdate).accept(MediaType.APPLICATION_JSON)) .header("If-None-Match", etagWithFirstUpdate).accept(MediaType.APPLICATION_JSON))
@@ -329,7 +331,8 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
Target savedTarget = testdataFactory.createTarget("911"); Target savedTarget = testdataFactory.createTarget("911");
savedTarget = assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getAssignedEntity().iterator() savedTarget = assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getAssignedEntity().iterator()
.next(); .next();
final Action savedAction = deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId()).get(0); final Action savedAction = deploymentManagement
.findActiveActionsByTarget(PAGE, savedTarget.getControllerId()).getContent().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())
.content(JsonBuilder.deploymentActionFeedback(savedAction.getId().toString(), "proceeding")) .content(JsonBuilder.deploymentActionFeedback(savedAction.getId().toString(), "proceeding"))

View File

@@ -150,9 +150,10 @@ public class DosFilterTest extends AbstractDDiApiIntegrationTest {
final List<Target> toAssign = Lists.newArrayList(target); final List<Target> toAssign = Lists.newArrayList(target);
final Iterable<Target> saved = assignDistributionSet(ds, toAssign).getAssignedEntity(); final Iterable<Target> saved = assignDistributionSet(ds, toAssign).getAssignedEntity();
assertThat(deploymentManagement.findActiveActionsByTarget(target.getControllerId())).hasSize(1); assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, target.getControllerId())).hasSize(1);
final Action uaction = deploymentManagement.findActiveActionsByTarget(target.getControllerId()).get(0); final Action uaction = deploymentManagement.findActiveActionsByTarget(PAGE, target.getControllerId())
.getContent().get(0);
return uaction.getId(); return uaction.getId();
} }

View File

@@ -0,0 +1,627 @@
/**
* 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.integration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.dmf.amqp.api.EventTopic;
import org.eclipse.hawkbit.dmf.amqp.api.MessageHeaderKey;
import org.eclipse.hawkbit.dmf.amqp.api.MessageType;
import org.eclipse.hawkbit.dmf.json.model.ActionStatus;
import org.eclipse.hawkbit.dmf.json.model.ActionUpdateStatus;
import org.eclipse.hawkbit.dmf.json.model.AttributeUpdate;
import org.eclipse.hawkbit.repository.event.remote.TargetAssignDistributionSetEvent;
import org.eclipse.hawkbit.repository.event.remote.TargetPollEvent;
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.CancelTargetAssignmentEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetUpdatedEvent;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetAssignmentResult;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
@Features("Component Tests - Device Management Federation API")
@Stories("Amqp Message Handler Service")
public class AmqpMessageHandlerServiceIntegrationTest extends AmqpServiceIntegrationTest {
@Test
@Description("Tests register target")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 2),
@Expect(type = TargetPollEvent.class, count = 3) })
public void registerTargets() {
registerAndAssertTargetWithExistingTenant(REGISTER_TARGET, 1);
final String target2 = "Target2";
registerAndAssertTargetWithExistingTenant(target2, 2);
final Long pollingTimeTarget2 = controllerManagement.findByControllerId(target2).get().getLastTargetQuery();
registerSameTargetAndAssertBasedOnLastPolling(target2, 2, TargetUpdateStatus.REGISTERED, pollingTimeTarget2);
Mockito.verifyZeroInteractions(getDeadletterListener());
}
@Test
@Description("Tests register invalid target withy empty controller id. Tests register invalid target with null controller id")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void registerEmptyTarget() {
createAndSendTarget("", TENANT_EXIST);
assertAllTargetsCount(0);
verifyDeadLetterMessages(1);
}
@Test
@Description("Tests register invalid target with whitspace controller id. Tests register invalid target with null controller id")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void registerWhitespaceTarget() {
createAndSendTarget("Invalid Invalid", TENANT_EXIST);
assertAllTargetsCount(0);
verifyDeadLetterMessages(1);
}
@Test
@Description("Tests register invalid target with null controller id. Tests register invalid target with null controller id")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void registerInvalidNullTargets() {
createAndSendTarget(null, TENANT_EXIST);
assertAllTargetsCount(0);
verifyDeadLetterMessages(1);
}
@Test
@Description("Tests not allowed content-type in message. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void wrongContentType() {
final Message createTargetMessage = createTargetMessage(REGISTER_TARGET, TENANT_EXIST);
createTargetMessage.getMessageProperties().setContentType("WrongContentType");
getDmfClient().send(createTargetMessage);
verifyDeadLetterMessages(1);
assertAllTargetsCount(0);
}
@Test
@Description("Tests null reply to property in message header. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void missingReplyToProperty() {
final Message createTargetMessage = createTargetMessage(REGISTER_TARGET, TENANT_EXIST);
createTargetMessage.getMessageProperties().setReplyTo(null);
getDmfClient().send(createTargetMessage);
verifyDeadLetterMessages(1);
assertAllTargetsCount(0);
}
@Test
@Description("Tests missing reply to property in message header. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void emptyReplyToProperty() {
final Message createTargetMessage = createTargetMessage(REGISTER_TARGET, TENANT_EXIST);
createTargetMessage.getMessageProperties().setReplyTo("");
getDmfClient().send(createTargetMessage);
verifyDeadLetterMessages(1);
assertAllTargetsCount(0);
}
@Test
@Description("Tests missing thing id property in message. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void missingThingIdProperty() {
final Message createTargetMessage = createTargetMessage(null, TENANT_EXIST);
createTargetMessage.getMessageProperties().getHeaders().remove(MessageHeaderKey.THING_ID);
getDmfClient().send(createTargetMessage);
verifyDeadLetterMessages(1);
assertAllTargetsCount(0);
}
@Test
@Description("Tests null thing id property in message. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void nullThingIdProperty() {
final Message createTargetMessage = createTargetMessage(null, TENANT_EXIST);
getDmfClient().send(createTargetMessage);
verifyDeadLetterMessages(1);
assertAllTargetsCount(0);
}
@Test
@Description("Tests missing tenant message header. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void missingTenantHeader() {
final Message createTargetMessage = createTargetMessage(REGISTER_TARGET, TENANT_EXIST);
createTargetMessage.getMessageProperties().getHeaders().remove(MessageHeaderKey.TENANT);
getDmfClient().send(createTargetMessage);
verifyDeadLetterMessages(1);
assertAllTargetsCount(0);
}
@Test
@Description("Tests null tenant message header. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void nullTenantHeader() {
final Message createTargetMessage = createTargetMessage(REGISTER_TARGET, null);
getDmfClient().send(createTargetMessage);
verifyDeadLetterMessages(1);
assertAllTargetsCount(0);
}
@Test
@Description("Tests empty tenant message header. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void emptyTenantHeader() {
final Message createTargetMessage = createTargetMessage(REGISTER_TARGET, "");
getDmfClient().send(createTargetMessage);
verifyDeadLetterMessages(1);
assertAllTargetsCount(0);
}
@Test
@Description("Tests tenant not exist. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void tenantNotExist() {
final Message createTargetMessage = createTargetMessage(REGISTER_TARGET, "TenantNotExist");
getDmfClient().send(createTargetMessage);
verifyDeadLetterMessages(1);
assertThat(systemManagement.findTenants(pageReq)).hasSize(1);
}
@Test
@Description("Tests missing type message header. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void missingTypeHeader() {
final Message createTargetMessage = createTargetMessage(null, TENANT_EXIST);
createTargetMessage.getMessageProperties().getHeaders().remove(MessageHeaderKey.TYPE);
getDmfClient().send(createTargetMessage);
verifyDeadLetterMessages(1);
assertAllTargetsCount(0);
}
@Test
@Description("Tests null type message header. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void nullTypeHeader() {
final Message createTargetMessage = createTargetMessage(null, TENANT_EXIST);
createTargetMessage.getMessageProperties().getHeaders().put(MessageHeaderKey.TYPE, null);
getDmfClient().send(createTargetMessage);
verifyDeadLetterMessages(1);
assertAllTargetsCount(0);
}
@Test
@Description("Tests empty type message header. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void emptyTypeHeader() {
final Message createTargetMessage = createTargetMessage(null, TENANT_EXIST);
createTargetMessage.getMessageProperties().getHeaders().put(MessageHeaderKey.TYPE, "");
getDmfClient().send(createTargetMessage);
verifyDeadLetterMessages(1);
assertAllTargetsCount(0);
}
@Test
@Description("Tests invalid type message header. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void invalidTypeHeader() {
final Message createTargetMessage = createTargetMessage(null, TENANT_EXIST);
createTargetMessage.getMessageProperties().getHeaders().put(MessageHeaderKey.TYPE, "NotExist");
getDmfClient().send(createTargetMessage);
verifyDeadLetterMessages(1);
assertAllTargetsCount(0);
}
@Test
@Description("Tests null topic message header. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void nullTopicHeader() {
final Message eventMessage = createEventMessage(TENANT_EXIST, EventTopic.UPDATE_ACTION_STATUS, "");
eventMessage.getMessageProperties().getHeaders().put(MessageHeaderKey.TOPIC, null);
getDmfClient().send(eventMessage);
verifyDeadLetterMessages(1);
}
@Test
@Description("Tests null topic message header. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void emptyTopicHeader() {
final Message eventMessage = createEventMessage(TENANT_EXIST, EventTopic.UPDATE_ACTION_STATUS, "");
eventMessage.getMessageProperties().getHeaders().put(MessageHeaderKey.TOPIC, "");
getDmfClient().send(eventMessage);
verifyDeadLetterMessages(1);
}
@Test
@Description("Tests null topic message header. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void invalidTopicHeader() {
final Message eventMessage = createEventMessage(TENANT_EXIST, EventTopic.UPDATE_ACTION_STATUS, "");
eventMessage.getMessageProperties().getHeaders().put(MessageHeaderKey.TOPIC, "NotExist");
getDmfClient().send(eventMessage);
verifyDeadLetterMessages(1);
}
@Test
@Description("Tests missing topic message header. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void missingTopicHeader() {
final Message eventMessage = createEventMessage(TENANT_EXIST, EventTopic.UPDATE_ACTION_STATUS, "");
eventMessage.getMessageProperties().getHeaders().remove(MessageHeaderKey.TOPIC);
getDmfClient().send(eventMessage);
verifyDeadLetterMessages(1);
}
@Test
@Description("Tests invalid null message content. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void updateActionStatusWithNullContent() {
final Message eventMessage = createEventMessage(TENANT_EXIST, EventTopic.UPDATE_ACTION_STATUS, null);
getDmfClient().send(eventMessage);
verifyDeadLetterMessages(1);
}
@Test
@Description("Tests invalid empty message content. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void updateActionStatusWithEmptyContent() {
final Message eventMessage = createEventMessage(TENANT_EXIST, EventTopic.UPDATE_ACTION_STATUS, "");
getDmfClient().send(eventMessage);
verifyDeadLetterMessages(1);
}
@Test
@Description("Tests invalid json message content. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void updateActionStatusWithInvalidJsonContent() {
final Message eventMessage = createEventMessage(TENANT_EXIST, EventTopic.UPDATE_ACTION_STATUS,
"Invalid Content");
getDmfClient().send(eventMessage);
verifyDeadLetterMessages(1);
}
@Test
@Description("Tests invalid topic message header. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void updateActionStatusWithInvalidActionId() {
final ActionUpdateStatus actionUpdateStatus = new ActionUpdateStatus(1L, ActionStatus.RUNNING);
final Message eventMessage = createEventMessage(TENANT_EXIST, EventTopic.UPDATE_ACTION_STATUS,
actionUpdateStatus);
getDmfClient().send(eventMessage);
verifyDeadLetterMessages(1);
}
@Test
@Description("Tests register target and cancel a assignment")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 1),
@Expect(type = ActionUpdatedEvent.class, count = 1), @Expect(type = ActionCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 2), @Expect(type = TargetPollEvent.class, count = 1) })
public void finishActionStatus() {
registerTargetAndSendAndAssertUpdateActionStatus(ActionStatus.FINISHED, Status.FINISHED);
}
@Test
@Description("Register a target and send a update action status (running). Verfiy if the updated action status is correct.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 1),
@Expect(type = ActionUpdatedEvent.class, count = 0), @Expect(type = ActionCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 1), @Expect(type = TargetPollEvent.class, count = 1) })
public void runningActionStatus() {
registerTargetAndSendAndAssertUpdateActionStatus(ActionStatus.RUNNING, Status.RUNNING);
}
@Test
@Description("Register a target and send a update action status (download). Verfiy if the updated action status is correct.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 1),
@Expect(type = ActionCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 1), @Expect(type = TargetPollEvent.class, count = 1) })
public void downloadActionStatus() {
registerTargetAndSendAndAssertUpdateActionStatus(ActionStatus.DOWNLOAD, Status.DOWNLOAD);
}
@Test
@Description("Register a target and send a update action status (error). Verfiy if the updated action status is correct.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 1),
@Expect(type = ActionUpdatedEvent.class, count = 1), @Expect(type = ActionCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 2), @Expect(type = TargetPollEvent.class, count = 1) })
public void errorActionStatus() {
registerTargetAndSendAndAssertUpdateActionStatus(ActionStatus.ERROR, Status.ERROR);
}
@Test
@Description("Register a target and send a update action status (warning). Verfiy if the updated action status is correct.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 1),
@Expect(type = ActionCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 1), @Expect(type = TargetPollEvent.class, count = 1) })
public void warningActionStatus() {
registerTargetAndSendAndAssertUpdateActionStatus(ActionStatus.WARNING, Status.WARNING);
}
@Test
@Description("Register a target and send a update action status (retrieved). Verfiy if the updated action status is correct.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 1),
@Expect(type = ActionCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 1), @Expect(type = TargetPollEvent.class, count = 1) })
public void retrievedActionStatus() {
registerTargetAndSendAndAssertUpdateActionStatus(ActionStatus.RETRIEVED, Status.RETRIEVED);
}
@Test
@Description("Register a target and send a invalid update action status (cancel). This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 1),
@Expect(type = ActionCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 1), @Expect(type = TargetPollEvent.class, count = 1) })
public void cancelNotAllowActionStatus() {
registerTargetAndSendActionStatus(ActionStatus.CANCELED);
verifyDeadLetterMessages(1);
}
@Test
@Description("Verfiy receiving a download and install message if a deployment is done before the target has polled the first time.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 1),
@Expect(type = ActionCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 1), @Expect(type = TargetPollEvent.class, count = 1) })
public void receiveDownLoadAndInstallMessageAfterAssignment() {
// setup
controllerManagement.findOrRegisterTargetIfItDoesNotexist(REGISTER_TARGET, null);
final DistributionSet distributionSet = testdataFactory.createDistributionSet(UUID.randomUUID().toString());
assignDistributionSet(distributionSet.getId(), REGISTER_TARGET);
// test
registerAndAssertTargetWithExistingTenant(REGISTER_TARGET, 1, TargetUpdateStatus.PENDING, "bumlux");
// verify
assertDownloadAndInstallMessage(distributionSet.getModules());
Mockito.verifyZeroInteractions(getDeadletterListener());
}
@Test
@Description("Verfiy receiving a cancel update message if a deployment is canceled before the target has polled the first time.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 1),
@Expect(type = ActionCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = CancelTargetAssignmentEvent.class, count = 1),
@Expect(type = ActionUpdatedEvent.class, count = 1), @Expect(type = TargetUpdatedEvent.class, count = 1),
@Expect(type = TargetPollEvent.class, count = 1) })
public void receiveCancelUpdateMessageAfterAssignmentWasCanceled() {
// Setup
controllerManagement.findOrRegisterTargetIfItDoesNotexist(REGISTER_TARGET, null);
final DistributionSet distributionSet = testdataFactory.createDistributionSet(UUID.randomUUID().toString());
final DistributionSetAssignmentResult distributionSetAssignmentResult = assignDistributionSet(
distributionSet.getId(), REGISTER_TARGET);
deploymentManagement.cancelAction(distributionSetAssignmentResult.getActions().get(0));
// test
registerAndAssertTargetWithExistingTenant(REGISTER_TARGET, 1, TargetUpdateStatus.PENDING, "bumlux");
// verify
assertCancelActionMessage(distributionSetAssignmentResult.getActions().get(0));
Mockito.verifyZeroInteractions(getDeadletterListener());
}
@Test
@Description("Register a target and send a invalid update action status (canceled). The current status (pending) is not a canceling state. This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 1),
@Expect(type = ActionUpdatedEvent.class, count = 1), @Expect(type = ActionCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = CancelTargetAssignmentEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 1), @Expect(type = TargetPollEvent.class, count = 1) })
public void actionNotExists() {
final Long actionId = registerTargetAndCancelActionId();
final Long actionNotExist = actionId + 1;
sendActionUpdateStatus(new ActionUpdateStatus(actionNotExist, ActionStatus.CANCELED));
verifyDeadLetterMessages(1);
}
@Test
@Description("Register a target and send a invalid update action status (cancel_rejected). This message should forwarded to the deadletter queue")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 1),
@Expect(type = ActionCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 1), @Expect(type = TargetPollEvent.class, count = 1) })
public void canceledRejectedNotAllowActionStatus() {
registerTargetAndSendActionStatus(ActionStatus.CANCEL_REJECTED);
verifyDeadLetterMessages(1);
}
@Test
@Description("Register a target and send a valid update action status (cancel_rejected). Verfiy if the updated action status is correct.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 1),
@Expect(type = CancelTargetAssignmentEvent.class, count = 1),
@Expect(type = ActionUpdatedEvent.class, count = 1), @Expect(type = ActionCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 1), @Expect(type = TargetPollEvent.class, count = 1) })
public void canceledRejectedActionStatus() {
final Long actionId = registerTargetAndCancelActionId();
sendActionUpdateStatus(new ActionUpdateStatus(actionId, ActionStatus.CANCEL_REJECTED));
assertAction(actionId, Status.RUNNING, Status.CANCELING, Status.CANCEL_REJECTED);
}
@Test
@Description("Verify that sending an update controller attribute message to an existing target works.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 1), @Expect(type = TargetPollEvent.class, count = 1) })
public void updateAttributes() {
// setup
final String target = "ControllerAttributeTestTarget";
registerAndAssertTargetWithExistingTenant(target, 1);
final AttributeUpdate controllerAttribute = new AttributeUpdate();
controllerAttribute.getAttributes().put("test1", "testA");
controllerAttribute.getAttributes().put("test2", "testB");
// test
sendUpdateAttributeMessage(target, TENANT_EXIST, controllerAttribute);
// validate
assertUpdateAttributes(target, controllerAttribute.getAttributes());
}
@Test
@Description("Verify that sending an update controller attribute message with no thingid header to an existing target does not work.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 0), @Expect(type = TargetPollEvent.class, count = 1) })
public void updateAttributesWithNoThingId() {
// setup
final String target = "ControllerAttributeTestTarget";
registerAndAssertTargetWithExistingTenant(target, 1);
final AttributeUpdate controllerAttribute = new AttributeUpdate();
controllerAttribute.getAttributes().put("test1", "testA");
controllerAttribute.getAttributes().put("test2", "testB");
final Message createUpdateAttributesMessage = createUpdateAttributesMessage(null, TENANT_EXIST,
controllerAttribute);
createUpdateAttributesMessage.getMessageProperties().getHeaders().remove(MessageHeaderKey.THING_ID);
// test
getDmfClient().send(createUpdateAttributesMessage);
// verify
verifyDeadLetterMessages(1);
final AttributeUpdate controllerAttributeEmpty = new AttributeUpdate();
assertUpdateAttributes(target, controllerAttributeEmpty.getAttributes());
}
@Test
@Description("Verify that sending an update controller attribute message with invalid body to an existing target does not work.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 0), @Expect(type = TargetPollEvent.class, count = 1) })
public void updateAttributesWithWrongBody() {
// setup
final String target = "ControllerAttributeTestTarget";
registerAndAssertTargetWithExistingTenant(target, 1);
final AttributeUpdate controllerAttribute = new AttributeUpdate();
controllerAttribute.getAttributes().put("test1", "testA");
controllerAttribute.getAttributes().put("test2", "testB");
final Message createUpdateAttributesMessageWrongBody = createUpdateAttributesMessageWrongBody(target,
TENANT_EXIST);
// test
getDmfClient().send(createUpdateAttributesMessageWrongBody);
// verify
verifyDeadLetterMessages(1);
}
private Long registerTargetAndSendActionStatus(final ActionStatus sendActionStatus) {
final DistributionSetAssignmentResult assignmentResult = registerTargetAndAssignDistributionSet();
final Long actionId = assignmentResult.getActions().get(0);
sendActionUpdateStatus(new ActionUpdateStatus(actionId, sendActionStatus));
return actionId;
}
private void sendActionUpdateStatus(final ActionUpdateStatus actionStatus) {
final Message eventMessage = createEventMessage(TENANT_EXIST, EventTopic.UPDATE_ACTION_STATUS, actionStatus);
getDmfClient().send(eventMessage);
}
private void registerTargetAndSendAndAssertUpdateActionStatus(final ActionStatus sendActionStatus,
final Status expectedActionStatus) {
final Long actionId = registerTargetAndSendActionStatus(sendActionStatus);
assertAction(actionId, Status.RUNNING, expectedActionStatus);
}
private void assertAction(final Long actionId, final Status... expectedActionStates) {
createConditionFactory().await().until(() -> {
try {
securityRule.runAsPrivileged(() -> {
final List<Status> status = deploymentManagement.findActionStatusByAction(pageReq, actionId)
.getContent().stream().map(actionStatus -> actionStatus.getStatus())
.collect(Collectors.toList());
assertThat(status).containsOnly(expectedActionStates);
return null;
});
} catch (final Exception e) {
fail(e.getMessage());
}
});
}
private Message createEventMessage(final String tenant, final EventTopic eventTopic, final Object payload) {
final MessageProperties messageProperties = createMessagePropertiesWithTenant(tenant);
messageProperties.getHeaders().put(MessageHeaderKey.TYPE, MessageType.EVENT.toString());
messageProperties.getHeaders().put(MessageHeaderKey.TOPIC, eventTopic.toString());
return createMessage(payload, messageProperties);
}
private void sendUpdateAttributeMessage(final String target, final String tenant,
final AttributeUpdate attributeUpdate) {
final Message updateMessage = createUpdateAttributesMessage(target, tenant, attributeUpdate);
getDmfClient().send(updateMessage);
}
}

View File

@@ -67,14 +67,6 @@
<artifactId>slf4j-api</artifactId> <artifactId>slf4j-api</artifactId>
</dependency> </dependency>
<!-- Optional -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- Test --> <!-- Test -->
<dependency> <dependency>
<groupId>org.eclipse.hawkbit</groupId> <groupId>org.eclipse.hawkbit</groupId>

View File

@@ -12,7 +12,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.fail;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.UUID; import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -32,7 +31,6 @@ import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetCreated
import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleCreatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleCreatedEvent;
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.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.DistributionSetAssignmentResult; import org.eclipse.hawkbit.repository.model.DistributionSetAssignmentResult;
@@ -202,7 +200,7 @@ public class AmqpMessageHandlerServiceIntegrationTest extends AmqpServiceIntegra
getDmfClient().send(createTargetMessage); getDmfClient().send(createTargetMessage);
verifyOneDeadLetterMessage(); verifyOneDeadLetterMessage();
assertThat(systemManagement.findTenants()).hasSize(1); assertThat(systemManagement.findTenants(PAGE)).hasSize(1);
} }
@Test @Test
@@ -606,9 +604,10 @@ public class AmqpMessageHandlerServiceIntegrationTest extends AmqpServiceIntegra
createConditionFactory().await().until(() -> { createConditionFactory().await().until(() -> {
try { try {
securityRule.runAsPrivileged(() -> { securityRule.runAsPrivileged(() -> {
final Optional<Action> findActionWithDetails = controllerManagement.findActionWithDetails(actionId); final List<Status> status = deploymentManagement.findActionStatusByAction(PAGE, actionId)
assertThat(findActionWithDetails).isPresent(); .getContent().stream().map(actionStatus -> actionStatus.getStatus())
assertThat(convertStatusList(findActionWithDetails.get())).containsOnly(expectedActionStates); .collect(Collectors.toList());
assertThat(status).containsOnly(expectedActionStates);
return null; return null;
}); });
} catch (final Exception e) { } catch (final Exception e) {
@@ -617,11 +616,6 @@ public class AmqpMessageHandlerServiceIntegrationTest extends AmqpServiceIntegra
}); });
} }
private List<Status> convertStatusList(Action action) {
return action.getActionStatus().stream().map(actionStatus -> actionStatus.getStatus())
.collect(Collectors.toList());
}
private Message createEventMessage(final String tenant, final EventTopic eventTopic, final Object payload) { private Message createEventMessage(final String tenant, final EventTopic eventTopic, final Object payload) {
final MessageProperties messageProperties = createMessagePropertiesWithTenant(tenant); final MessageProperties messageProperties = createMessagePropertiesWithTenant(tenant);
messageProperties.getHeaders().put(MessageHeaderKey.TYPE, MessageType.EVENT.toString()); messageProperties.getHeaders().put(MessageHeaderKey.TYPE, MessageType.EVENT.toString());

View File

@@ -8,14 +8,14 @@
*/ */
package org.eclipse.hawkbit.mgmt.json.model.rollout; package org.eclipse.hawkbit.mgmt.json.model.rollout;
import java.util.List;
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtActionType; import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtActionType;
import org.eclipse.hawkbit.mgmt.json.model.rolloutgroup.MgmtRolloutGroup;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonInclude.Include;
import org.eclipse.hawkbit.mgmt.json.model.rolloutgroup.MgmtRolloutGroup;
import java.util.List;
/** /**
* Model for request containing a rollout body e.g. in a POST request of * Model for request containing a rollout body e.g. in a POST request of

View File

@@ -8,9 +8,10 @@
*/ */
package org.eclipse.hawkbit.mgmt.json.model.rolloutgroup; package org.eclipse.hawkbit.mgmt.json.model.rolloutgroup;
import org.eclipse.hawkbit.mgmt.json.model.rollout.AbstractMgmtRolloutConditionsEntity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import org.eclipse.hawkbit.mgmt.json.model.rollout.AbstractMgmtRolloutConditionsEntity;
/** /**
* Model for defining the Attributes of a Rollout Group * Model for defining the Attributes of a Rollout Group

View File

@@ -122,10 +122,46 @@ public interface MgmtDistributionSetTagRestApi {
* *
* @param distributionsetTagId * @param distributionsetTagId
* the ID of the distribution set tag * the ID of the distribution set tag
* @param pagingOffsetParam
* the offset of list of target tags for pagination, might not be
* present in the rest request then default value will be applied
* @param pagingLimitParam
* the limit of the paged request, might not be present in the
* rest request then default value will be applied
* @param sortParam
* the sorting parameter in the request URL, syntax
* {@code field:direction, field:direction}
* @param rsqlParam
* the search parameter in the request URL, syntax
* {@code q=name==abc}
* *
* @return the list of assigned distribution sets. * @return the list of assigned distribution sets.
*/ */
@RequestMapping(method = RequestMethod.GET, value = MgmtRestConstants.DISTRIBUTIONSET_REQUEST_MAPPING, produces = { @RequestMapping(method = RequestMethod.GET, value = MgmtRestConstants.DISTRIBUTIONSET_TAG_DISTRIBUTIONSETS_REQUEST_MAPPING, produces = {
MediaTypes.HAL_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE })
ResponseEntity<PagedList<MgmtDistributionSet>> getAssignedDistributionSets(
@PathVariable("distributionsetTagId") final Long distributionsetTagId,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam);
/**
* Handles the GET request of retrieving all assigned distribution sets by
* the given tag id.
*
* @param distributionsetTagId
* the ID of the distribution set tag
*
* @return the list of assigned distribution sets.
*
* @deprecated please use
* {@link #getAssignedDistributionSets(Long, int, int, String, String)}
* instead as this variant does not include paging and as result
* returns only a limited list of distributionsets
*/
@Deprecated
@RequestMapping(method = RequestMethod.GET, value = MgmtRestConstants.DEPRECATED_DISTRIBUTIONSET_TAG_DISTRIBUTIONSETS_REQUEST_MAPPING, produces = {
MediaTypes.HAL_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE }) MediaTypes.HAL_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE })
ResponseEntity<List<MgmtDistributionSet>> getAssignedDistributionSets( ResponseEntity<List<MgmtDistributionSet>> getAssignedDistributionSets(
@PathVariable("distributionsetTagId") final Long distributionsetTagId); @PathVariable("distributionsetTagId") final Long distributionsetTagId);
@@ -142,12 +178,34 @@ public interface MgmtDistributionSetTagRestApi {
* @return the list of assigned distribution sets and unassigned * @return the list of assigned distribution sets and unassigned
* distribution sets. * distribution sets.
*/ */
@RequestMapping(method = RequestMethod.POST, value = MgmtRestConstants.DISTRIBUTIONSET_REQUEST_MAPPING @RequestMapping(method = RequestMethod.POST, value = MgmtRestConstants.DISTRIBUTIONSET_TAG_DISTRIBUTIONSETS_REQUEST_MAPPING
+ "/toggleTagAssignment") + "/toggleTagAssignment")
ResponseEntity<MgmtDistributionSetTagAssigmentResult> toggleTagAssignment( ResponseEntity<MgmtDistributionSetTagAssigmentResult> toggleTagAssignment(
@PathVariable("distributionsetTagId") final Long distributionsetTagId, @PathVariable("distributionsetTagId") final Long distributionsetTagId,
final List<MgmtAssignedDistributionSetRequestBody> assignedDSRequestBodies); final List<MgmtAssignedDistributionSetRequestBody> assignedDSRequestBodies);
/**
* Handles the POST request to toggle the assignment of distribution sets by
* the given tag id.
*
* @param distributionsetTagId
* the ID of the distribution set tag to retrieve
* @param assignedDSRequestBodies
* list of distribution set ids to be toggled
*
* @return the list of assigned distribution sets and unassigned
* distribution sets.
*
* @deprecated please use
* {@link MgmtDistributionSetTagRestApi#toggleTagAssignment}
*/
@Deprecated
@RequestMapping(method = RequestMethod.POST, value = MgmtRestConstants.DEPRECATED_DISTRIBUTIONSET_TAG_DISTRIBUTIONSETS_REQUEST_MAPPING
+ "/toggleTagAssignment")
ResponseEntity<MgmtDistributionSetTagAssigmentResult> toggleTagAssignmentUnpaged(
@PathVariable("distributionsetTagId") final Long distributionsetTagId,
final List<MgmtAssignedDistributionSetRequestBody> assignedDSRequestBodies);
/** /**
* Handles the POST request to assign distribution sets to the given tag id. * Handles the POST request to assign distribution sets to the given tag id.
* *
@@ -158,7 +216,7 @@ public interface MgmtDistributionSetTagRestApi {
* *
* @return the list of assigned distribution set. * @return the list of assigned distribution set.
*/ */
@RequestMapping(method = RequestMethod.POST, value = MgmtRestConstants.DISTRIBUTIONSET_REQUEST_MAPPING, consumes = { @RequestMapping(method = RequestMethod.POST, value = MgmtRestConstants.DISTRIBUTIONSET_TAG_DISTRIBUTIONSETS_REQUEST_MAPPING, consumes = {
MediaTypes.HAL_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE }, produces = { MediaTypes.HAL_JSON_VALUE, MediaTypes.HAL_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE }, produces = { MediaTypes.HAL_JSON_VALUE,
MediaType.APPLICATION_JSON_VALUE }) MediaType.APPLICATION_JSON_VALUE })
ResponseEntity<List<MgmtDistributionSet>> assignDistributionSets( ResponseEntity<List<MgmtDistributionSet>> assignDistributionSets(
@@ -166,16 +224,25 @@ public interface MgmtDistributionSetTagRestApi {
final List<MgmtAssignedDistributionSetRequestBody> assignedDSRequestBodies); final List<MgmtAssignedDistributionSetRequestBody> assignedDSRequestBodies);
/** /**
* Handles the DELETE request to unassign all distribution set from the * Handles the POST request to assign distribution sets to the given tag id.
* given tag id.
* *
* @param distributionsetTagId * @param distributionsetTagId
* the ID of the distribution set tag to retrieve * the ID of the distribution set tag to retrieve
* @return http status code * @param assignedDSRequestBodies
* list of distribution sets ids to be assigned
*
* @return the list of assigned distribution set.
*
* @deprecated please use
* {@link MgmtDistributionSetTagRestApi#assignDistributionSets}
*/ */
@RequestMapping(method = RequestMethod.DELETE, value = MgmtRestConstants.DISTRIBUTIONSET_REQUEST_MAPPING) @Deprecated
ResponseEntity<Void> unassignDistributionSets( @RequestMapping(method = RequestMethod.POST, value = MgmtRestConstants.DEPRECATED_DISTRIBUTIONSET_TAG_DISTRIBUTIONSETS_REQUEST_MAPPING, consumes = {
@PathVariable("distributionsetTagId") final Long distributionsetTagId); MediaTypes.HAL_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE }, produces = { MediaTypes.HAL_JSON_VALUE,
MediaType.APPLICATION_JSON_VALUE })
ResponseEntity<List<MgmtDistributionSet>> assignDistributionSetsUnpaged(
@PathVariable("distributionsetTagId") final Long distributionsetTagId,
final List<MgmtAssignedDistributionSetRequestBody> assignedDSRequestBodies);
/** /**
* Handles the DELETE request to unassign one distribution set from the * Handles the DELETE request to unassign one distribution set from the
@@ -187,8 +254,28 @@ public interface MgmtDistributionSetTagRestApi {
* the ID of the distribution set to unassign * the ID of the distribution set to unassign
* @return http status code * @return http status code
*/ */
@RequestMapping(method = RequestMethod.DELETE, value = MgmtRestConstants.DISTRIBUTIONSET_REQUEST_MAPPING @RequestMapping(method = RequestMethod.DELETE, value = MgmtRestConstants.DISTRIBUTIONSET_TAG_DISTRIBUTIONSETS_REQUEST_MAPPING
+ "/{distributionsetId}") + "/{distributionsetId}")
ResponseEntity<Void> unassignDistributionSet(@PathVariable("distributionsetTagId") final Long distributionsetTagId, ResponseEntity<Void> unassignDistributionSet(@PathVariable("distributionsetTagId") final Long distributionsetTagId,
@PathVariable("distributionsetId") final Long distributionsetId); @PathVariable("distributionsetId") final Long distributionsetId);
/**
* Handles the DELETE request to unassign one distribution set from the
* given tag id.
*
* @param distributionsetTagId
* the ID of the distribution set tag
* @param distributionsetId
* the ID of the distribution set to unassign
* @return http status code
*
* @deprecated please use
* {@link MgmtDistributionSetTagRestApi#unassignDistributionSet}
*/
@Deprecated
@RequestMapping(method = RequestMethod.DELETE, value = MgmtRestConstants.DEPRECATED_DISTRIBUTIONSET_TAG_DISTRIBUTIONSETS_REQUEST_MAPPING
+ "/{distributionsetId}")
ResponseEntity<Void> unassignDistributionSetUnpaged(
@PathVariable("distributionsetTagId") final Long distributionsetTagId,
@PathVariable("distributionsetId") final Long distributionsetId);
} }

View File

@@ -24,19 +24,20 @@ public final class MgmtRestConstants {
*/ */
public static final String BASE_V1_REQUEST_MAPPING = "/rest/v1"; public static final String BASE_V1_REQUEST_MAPPING = "/rest/v1";
/**
* String representation of
* {@link #REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE}.
*/
public static final String REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT = "50";
/** /**
* The default limit parameter in case the limit parameter is not present in * The default limit parameter in case the limit parameter is not present in
* the request. * the request.
* *
* @see #REQUEST_PARAMETER_PAGING_LIMIT * @see #REQUEST_PARAMETER_PAGING_LIMIT
*/ */
public static final int REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE = 50; public static final int REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE = Integer
.parseInt(REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT);
/**
* String representation of
* {@link #REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE}.
*/
public static final String REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT = "50";
/** /**
* The software module URL mapping rest resource. * The software module URL mapping rest resource.
@@ -93,10 +94,20 @@ public final class MgmtRestConstants {
* The tag URL mapping rest resource. * The tag URL mapping rest resource.
*/ */
public static final String TARGET_TAG_V1_REQUEST_MAPPING = BASE_V1_REQUEST_MAPPING + "/targettags"; public static final String TARGET_TAG_V1_REQUEST_MAPPING = BASE_V1_REQUEST_MAPPING + "/targettags";
/**
* The tag URL mapping rest resource.
*
* @deprecated {@link #TARGET_TAG_TARGETS_REQUEST_MAPPING} is preferred as
* this resource on GET supports paging
*/
@Deprecated
public static final String DEPRECATAED_TARGET_TAG_TARGETS_REQUEST_MAPPING = "/{targetTagId}/targets";
/** /**
* The tag URL mapping rest resource. * The tag URL mapping rest resource.
*/ */
public static final String TARGET_TAG_TARGETS_REQUEST_MAPPING = "/{targetTagId}/targets"; public static final String TARGET_TAG_TARGETS_REQUEST_MAPPING = "/{targetTagId}/assigned";
/** /**
* The tag URL mapping rest resource. * The tag URL mapping rest resource.
@@ -109,10 +120,19 @@ public final class MgmtRestConstants {
*/ */
public static final String TARGET_FILTER_V1_REQUEST_MAPPING = BASE_V1_REQUEST_MAPPING + "/targetfilters"; public static final String TARGET_FILTER_V1_REQUEST_MAPPING = BASE_V1_REQUEST_MAPPING + "/targetfilters";
/**
* The deprecated tag URL mapping rest resource.
*
* @deprecated {@link #DISTRIBUTIONSET_TAG_DISTRIBUTIONSETS_REQUEST_MAPPING}
* is preferred as this resource on GET supports paging
*/
@Deprecated
public static final String DEPRECATED_DISTRIBUTIONSET_TAG_DISTRIBUTIONSETS_REQUEST_MAPPING = "/{distributionsetTagId}/distributionsets";
/** /**
* The tag URL mapping rest resource. * The tag URL mapping rest resource.
*/ */
public static final String DISTRIBUTIONSET_REQUEST_MAPPING = "/{distributionsetTagId}/distributionsets"; public static final String DISTRIBUTIONSET_TAG_DISTRIBUTIONSETS_REQUEST_MAPPING = "/{distributionsetTagId}/assigned";
/** /**
* The default offset parameter in case the offset parameter is not present * The default offset parameter in case the offset parameter is not present
@@ -122,6 +142,15 @@ public final class MgmtRestConstants {
*/ */
public static final String REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET = "0"; public static final String REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET = "0";
/**
* The default offset parameter in case the offset parameter is not present
* in the request.
*
* @see #REQUEST_PARAMETER_PAGING_OFFSET
*/
public static final int REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE = Integer
.parseInt(REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET);
/** /**
* Limit http parameter for the limitation of returned values for a paged * Limit http parameter for the limitation of returned values for a paged
* request. * request.

View File

@@ -98,7 +98,7 @@ public interface MgmtTargetTagRestApi {
@RequestMapping(method = RequestMethod.PUT, value = "/{targetTagId}", consumes = { MediaTypes.HAL_JSON_VALUE, @RequestMapping(method = RequestMethod.PUT, value = "/{targetTagId}", consumes = { MediaTypes.HAL_JSON_VALUE,
MediaType.APPLICATION_JSON_VALUE }, produces = { MediaTypes.HAL_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE }, produces = { MediaTypes.HAL_JSON_VALUE,
MediaType.APPLICATION_JSON_VALUE }) MediaType.APPLICATION_JSON_VALUE })
ResponseEntity<MgmtTag> updateTagretTag(@PathVariable("targetTagId") final Long targetTagId, ResponseEntity<MgmtTag> updateTargetTag(@PathVariable("targetTagId") final Long targetTagId,
final MgmtTagRequestBodyPut restTargetTagRest); final MgmtTagRequestBodyPut restTargetTagRest);
/** /**
@@ -120,10 +120,45 @@ public interface MgmtTargetTagRestApi {
* the ID of the target tag to retrieve * the ID of the target tag to retrieve
* *
* @return the list of assigned targets. * @return the list of assigned targets.
*
* @deprecated please use
* {@link #getAssignedTargets(Long, int, int, String, String)}
* instead as this variant does not include paging and as result
* returns only a limited list of targets
*/
@Deprecated
@RequestMapping(method = RequestMethod.GET, value = MgmtRestConstants.DEPRECATAED_TARGET_TAG_TARGETS_REQUEST_MAPPING, produces = {
MediaTypes.HAL_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE })
ResponseEntity<List<MgmtTarget>> getAssignedTargets(@PathVariable("targetTagId") final Long targetTagId);
/**
* Handles the GET request of retrieving all assigned targets by the given
* tag id.
*
* @param targetTagId
* the ID of the target tag to retrieve
* @param pagingOffsetParam
* the offset of list of target tags for pagination, might not be
* present in the rest request then default value will be applied
* @param pagingLimitParam
* the limit of the paged request, might not be present in the
* rest request then default value will be applied
* @param sortParam
* the sorting parameter in the request URL, syntax
* {@code field:direction, field:direction}
* @param rsqlParam
* the search parameter in the request URL, syntax
* {@code q=name==abc}
*
* @return the list of assigned targets.
*/ */
@RequestMapping(method = RequestMethod.GET, value = MgmtRestConstants.TARGET_TAG_TARGETS_REQUEST_MAPPING, produces = { @RequestMapping(method = RequestMethod.GET, value = MgmtRestConstants.TARGET_TAG_TARGETS_REQUEST_MAPPING, produces = {
MediaTypes.HAL_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE }) MediaTypes.HAL_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE })
ResponseEntity<List<MgmtTarget>> getAssignedTargets(@PathVariable("targetTagId") final Long targetTagId); ResponseEntity<PagedList<MgmtTarget>> getAssignedTargets(@PathVariable("targetTagId") final Long targetTagId,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam);
/** /**
* Handles the POST request to toggle the assignment of targets by the given * Handles the POST request to toggle the assignment of targets by the given
@@ -144,6 +179,27 @@ public interface MgmtTargetTagRestApi {
@PathVariable("targetTagId") final Long targetTagId, @PathVariable("targetTagId") final Long targetTagId,
final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies); final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies);
/**
* Handles the POST request to toggle the assignment of targets by the given
* tag id.
*
* @param targetTagId
* the ID of the target tag to retrieve
* @param assignedTargetRequestBodies
* list of controller ids to be toggled
*
* @return the list of assigned targets and unassigned targets.
* @deprecated please use {@link MgmtTargetTagRestApi#toggleTagAssignment}
*/
@Deprecated
@RequestMapping(method = RequestMethod.POST, value = MgmtRestConstants.DEPRECATAED_TARGET_TAG_TARGETS_REQUEST_MAPPING
+ "/toggleTagAssignment", consumes = { MediaTypes.HAL_JSON_VALUE,
MediaType.APPLICATION_JSON_VALUE }, produces = { MediaTypes.HAL_JSON_VALUE,
MediaType.APPLICATION_JSON_VALUE })
ResponseEntity<MgmtTargetTagAssigmentResult> toggleTagAssignmentUnpaged(
@PathVariable("targetTagId") final Long targetTagId,
final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies);
/** /**
* Handles the POST request to assign targets to the given tag id. * Handles the POST request to assign targets to the given tag id.
* *
@@ -161,14 +217,23 @@ public interface MgmtTargetTagRestApi {
final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies); final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies);
/** /**
* Handles the DELETE request to unassign all targets from the given tag id. * Handles the POST request to assign targets to the given tag id.
* *
* @param targetTagId * @param targetTagId
* the ID of the target tag to retrieve * the ID of the target tag to retrieve
* @return http status code * @param assignedTargetRequestBodies
* list of controller ids to be assigned
*
* @return the list of assigned targets.
*
* @deprecated please use {@link MgmtTargetTagRestApi#assignTargets}
*/ */
@RequestMapping(method = RequestMethod.DELETE, value = MgmtRestConstants.TARGET_TAG_TARGETS_REQUEST_MAPPING) @Deprecated
ResponseEntity<Void> unassignTargets(@PathVariable("targetTagId") final Long targetTagId); @RequestMapping(method = RequestMethod.POST, value = MgmtRestConstants.DEPRECATAED_TARGET_TAG_TARGETS_REQUEST_MAPPING, consumes = {
MediaTypes.HAL_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE }, produces = { MediaTypes.HAL_JSON_VALUE,
MediaType.APPLICATION_JSON_VALUE })
ResponseEntity<List<MgmtTarget>> assignTargetsUnpaged(@PathVariable("targetTagId") final Long targetTagId,
final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies);
/** /**
* Handles the DELETE request to unassign one target from the given tag id. * Handles the DELETE request to unassign one target from the given tag id.
@@ -183,4 +248,21 @@ public interface MgmtTargetTagRestApi {
+ "/{controllerId}") + "/{controllerId}")
ResponseEntity<Void> unassignTarget(@PathVariable("targetTagId") final Long targetTagId, ResponseEntity<Void> unassignTarget(@PathVariable("targetTagId") final Long targetTagId,
@PathVariable("controllerId") final String controllerId); @PathVariable("controllerId") final String controllerId);
/**
* Handles the DELETE request to unassign one target from the given tag id.
*
* @param targetTagId
* the ID of the target tag
* @param controllerId
* the ID of the target to unassign
* @return http status code
*
* @deprecated please use {@link MgmtTargetTagRestApi#unassignTarget}
*/
@Deprecated
@RequestMapping(method = RequestMethod.DELETE, value = MgmtRestConstants.DEPRECATAED_TARGET_TAG_TARGETS_REQUEST_MAPPING
+ "/{controllerId}")
ResponseEntity<Void> unassignTargetUnpaged(@PathVariable("targetTagId") final Long targetTagId,
@PathVariable("controllerId") final String controllerId);
} }

View File

@@ -121,8 +121,8 @@ public final class MgmtDistributionSetMapper {
.getDistributionSetType(distributionSet.getType().getId())).withRel("type")); .getDistributionSetType(distributionSet.getType().getId())).withRel("type"));
response.add(linkTo(methodOn(MgmtDistributionSetRestApi.class).getMetadata(response.getDsId(), response.add(linkTo(methodOn(MgmtDistributionSetRestApi.class).getMetadata(response.getDsId(),
Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET), MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE,
Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT), null, null)) MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, null, null))
.withRel("metadata")); .withRel("metadata"));
return response; return response;

View File

@@ -31,8 +31,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@@ -67,25 +67,20 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam); final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeTargetSortParam(sortParam); final Sort sorting = PagingUtility.sanitizeTagSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting); final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Slice<DistributionSetTag> findTargetsAll; final Page<DistributionSetTag> findTargetsAll;
final Long countTargetsAll;
if (rsqlParam == null) { if (rsqlParam == null) {
findTargetsAll = this.tagManagement.findAllDistributionSetTags(pageable); findTargetsAll = tagManagement.findAllDistributionSetTags(pageable);
countTargetsAll = this.tagManagement.countTargetTags();
} else { } else {
final Page<DistributionSetTag> findTargetPage = this.tagManagement.findAllDistributionSetTags(rsqlParam, findTargetsAll = tagManagement.findAllDistributionSetTags(rsqlParam, pageable);
pageable);
countTargetsAll = findTargetPage.getTotalElements();
findTargetsAll = findTargetPage;
} }
final List<MgmtTag> rest = MgmtTagMapper.toResponseDistributionSetTag(findTargetsAll.getContent()); final List<MgmtTag> rest = MgmtTagMapper.toResponseDistributionSetTag(findTargetsAll.getContent());
return new ResponseEntity<>(new PagedList<>(rest, countTargetsAll), HttpStatus.OK); return new ResponseEntity<>(new PagedList<>(rest, findTargetsAll.getTotalElements()), HttpStatus.OK);
} }
@Override @Override
@@ -132,10 +127,36 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
@Override @Override
public ResponseEntity<List<MgmtDistributionSet>> getAssignedDistributionSets( public ResponseEntity<List<MgmtDistributionSet>> getAssignedDistributionSets(
@PathVariable("distributionsetTagId") final Long distributionsetTagId) { @PathVariable("distributionsetTagId") final Long distributionsetTagId) {
final DistributionSetTag tag = findDistributionTagById(distributionsetTagId); return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDistributionSets(distributionSetManagement
return new ResponseEntity<>( .findDistributionSetsByTag(new PageRequest(0, MgmtRestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT),
MgmtDistributionSetMapper.toResponseDistributionSets(tag.getAssignedToDistributionSet()), distributionsetTagId)
HttpStatus.OK); .getContent()), HttpStatus.OK);
}
@Override
public ResponseEntity<PagedList<MgmtDistributionSet>> getAssignedDistributionSets(
@PathVariable("distributionsetTagId") final Long distributionsetTagId,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) {
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeTagSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
Page<DistributionSet> findDistrAll;
if (rsqlParam == null) {
findDistrAll = distributionSetManagement.findDistributionSetsByTag(pageable, distributionsetTagId);
} else {
findDistrAll = distributionSetManagement.findDistributionSetsByTag(pageable, rsqlParam,
distributionsetTagId);
}
final List<MgmtDistributionSet> rest = MgmtDistributionSetMapper
.toResponseFromDsList(findDistrAll.getContent());
return new ResponseEntity<>(new PagedList<>(rest, findDistrAll.getTotalElements()), HttpStatus.OK);
} }
@Override @Override
@@ -173,17 +194,6 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDistributionSets(assignedDs), HttpStatus.OK); return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDistributionSets(assignedDs), HttpStatus.OK);
} }
@Override
public ResponseEntity<Void> unassignDistributionSets(
@PathVariable("distributionsetTagId") final Long distributionsetTagId) {
LOG.debug("Unassign all DS for ds tag {}", distributionsetTagId);
final List<DistributionSet> distributionSets = this.distributionSetManagement
.unAssignAllDistributionSetsByTag(distributionsetTagId);
LOG.debug("Unassigned ds {}", distributionSets.size());
return new ResponseEntity<>(HttpStatus.OK);
}
@Override @Override
public ResponseEntity<Void> unassignDistributionSet( public ResponseEntity<Void> unassignDistributionSet(
@PathVariable("distributionsetTagId") final Long distributionsetTagId, @PathVariable("distributionsetTagId") final Long distributionsetTagId,
@@ -203,4 +213,24 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
return assignedDistributionSetRequestBodies.stream() return assignedDistributionSetRequestBodies.stream()
.map(MgmtAssignedDistributionSetRequestBody::getDistributionSetId).collect(Collectors.toList()); .map(MgmtAssignedDistributionSetRequestBody::getDistributionSetId).collect(Collectors.toList());
} }
@Override
public ResponseEntity<MgmtDistributionSetTagAssigmentResult> toggleTagAssignmentUnpaged(
final Long distributionsetTagId,
final List<MgmtAssignedDistributionSetRequestBody> assignedDSRequestBodies) {
return toggleTagAssignment(distributionsetTagId, assignedDSRequestBodies);
}
@Override
public ResponseEntity<List<MgmtDistributionSet>> assignDistributionSetsUnpaged(final Long distributionsetTagId,
final List<MgmtAssignedDistributionSetRequestBody> assignedDSRequestBodies) {
return assignDistributionSets(distributionsetTagId, assignedDSRequestBodies);
}
@Override
public ResponseEntity<Void> unassignDistributionSetUnpaged(final Long distributionsetTagId,
final Long distributionsetId) {
return unassignDistributionSet(distributionsetTagId, distributionsetId);
}
} }

View File

@@ -90,8 +90,8 @@ final class MgmtRolloutMapper {
body.add(linkTo(methodOn(MgmtRolloutRestApi.class).pause(rollout.getId())).withRel("pause")); body.add(linkTo(methodOn(MgmtRolloutRestApi.class).pause(rollout.getId())).withRel("pause"));
body.add(linkTo(methodOn(MgmtRolloutRestApi.class).resume(rollout.getId())).withRel("resume")); body.add(linkTo(methodOn(MgmtRolloutRestApi.class).resume(rollout.getId())).withRel("resume"));
body.add(linkTo(methodOn(MgmtRolloutRestApi.class).getRolloutGroups(rollout.getId(), body.add(linkTo(methodOn(MgmtRolloutRestApi.class).getRolloutGroups(rollout.getId(),
Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET), MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE,
Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT), null, null)) MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, null, null))
.withRel("groups")); .withRel("groups"));
return body; return body;
} }

View File

@@ -115,8 +115,8 @@ public final class MgmtSoftwareModuleMapper {
.withRel(MgmtRestConstants.SOFTWAREMODULE_V1_TYPE)); .withRel(MgmtRestConstants.SOFTWAREMODULE_V1_TYPE));
response.add(linkTo(methodOn(MgmtSoftwareModuleResource.class).getMetadata(response.getModuleId(), response.add(linkTo(methodOn(MgmtSoftwareModuleResource.class).getMetadata(response.getModuleId(),
Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET), MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE,
Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT), null, null)) MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, null, null))
.withRel("metadata").expand(ArrayUtils.toArray())); .withRel("metadata").expand(ArrayUtils.toArray()));
return response; return response;
} }

View File

@@ -19,6 +19,7 @@ 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.MgmtRestConstants;
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.builder.TagCreate;
@@ -61,8 +62,10 @@ final class MgmtTagMapper {
response.add(linkTo(methodOn(MgmtTargetTagRestApi.class).getTargetTag(targetTag.getId())).withSelfRel()); response.add(linkTo(methodOn(MgmtTargetTagRestApi.class).getTargetTag(targetTag.getId())).withSelfRel());
response.add(linkTo(methodOn(MgmtTargetTagRestApi.class).getAssignedTargets(targetTag.getId())) response.add(linkTo(methodOn(MgmtTargetTagRestApi.class).getAssignedTargets(targetTag.getId(),
.withRel("assignedTargets")); MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE,
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, null, null))
.withRel("assignedTargets"));
return response; return response;
} }
@@ -93,8 +96,9 @@ final class MgmtTagMapper {
linkTo(methodOn(MgmtDistributionSetTagRestApi.class).getDistributionSetTag(distributionSetTag.getId())) linkTo(methodOn(MgmtDistributionSetTagRestApi.class).getDistributionSetTag(distributionSetTag.getId()))
.withSelfRel()); .withSelfRel());
response.add(linkTo( response.add(linkTo(methodOn(MgmtDistributionSetTagRestApi.class).getAssignedDistributionSets(
methodOn(MgmtDistributionSetTagRestApi.class).getAssignedDistributionSets(distributionSetTag.getId())) distributionSetTag.getId(), MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE,
MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, null, null))
.withRel("assignedDistributionSets")); .withRel("assignedDistributionSets"));
return response; return response;

View File

@@ -28,6 +28,7 @@ import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTargetRequestBody;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; 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.DeploymentManagement;
import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.builder.TargetCreate; import org.eclipse.hawkbit.repository.builder.TargetCreate;
import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action;
@@ -37,6 +38,7 @@ import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.rest.data.ResponseList; import org.eclipse.hawkbit.rest.data.ResponseList;
import org.eclipse.hawkbit.rest.data.SortDirection; import org.eclipse.hawkbit.rest.data.SortDirection;
import org.eclipse.hawkbit.util.IpUtil; import org.eclipse.hawkbit.util.IpUtil;
import org.springframework.data.domain.PageRequest;
/** /**
* A mapper which maps repository model to RESTful model representation and * A mapper which maps repository model to RESTful model representation and
@@ -161,12 +163,17 @@ public final class MgmtTargetMapper {
.address(targetRest.getAddress()); .address(targetRest.getAddress());
} }
static List<MgmtActionStatus> toActionStatusRestResponse(final Collection<ActionStatus> actionStatus) { static List<MgmtActionStatus> toActionStatusRestResponse(final Collection<ActionStatus> actionStatus,
final DeploymentManagement deploymentManagement) {
if (actionStatus == null) { if (actionStatus == null) {
return Collections.emptyList(); return Collections.emptyList();
} }
return actionStatus.stream().map(MgmtTargetMapper::toResponse).collect(Collectors.toList()); return actionStatus.stream().map(status -> toResponse(status,
deploymentManagement.findMessagesByActionStatusId(
new PageRequest(0, MgmtRestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT), status.getId())
.getContent()))
.collect(Collectors.toList());
} }
static MgmtAction toResponse(final String targetId, final Action action, final boolean isActive) { static MgmtAction toResponse(final String targetId, final Action action, final boolean isActive) {
@@ -207,10 +214,10 @@ public final class MgmtTargetMapper {
return null; return null;
} }
private static MgmtActionStatus toResponse(final ActionStatus actionStatus) { private static MgmtActionStatus toResponse(final ActionStatus actionStatus, final List<String> messages) {
final MgmtActionStatus result = new MgmtActionStatus(); final MgmtActionStatus result = new MgmtActionStatus();
result.setMessages(actionStatus.getMessages()); result.setMessages(messages);
result.setReportedAt(actionStatus.getCreatedAt()); result.setReportedAt(actionStatus.getCreatedAt());
result.setStatusId(actionStatus.getId()); result.setStatusId(actionStatus.getId());
result.setType(actionStatus.getStatus().name().toLowerCase()); result.setType(actionStatus.getStatus().name().toLowerCase());

View File

@@ -252,13 +252,12 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeActionStatusSortParam(sortParam); final Sort sorting = PagingUtility.sanitizeActionStatusSortParam(sortParam);
final Page<ActionStatus> statusList = this.deploymentManagement.findActionStatusByActionWithMessages( final Page<ActionStatus> statusList = this.deploymentManagement.findActionStatusByAction(
new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting), action.getId()); new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting), action.getId());
return new ResponseEntity<>( return new ResponseEntity<>(new PagedList<>(
new PagedList<>(MgmtTargetMapper.toActionStatusRestResponse(statusList.getContent()), MgmtTargetMapper.toActionStatusRestResponse(statusList.getContent(), deploymentManagement),
statusList.getTotalElements()), statusList.getTotalElements()), HttpStatus.OK);
HttpStatus.OK);
} }

View File

@@ -31,8 +31,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@@ -67,24 +67,19 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam); final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeTargetSortParam(sortParam); final Sort sorting = PagingUtility.sanitizeTagSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting); final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Slice<TargetTag> findTargetsAll; Page<TargetTag> findTargetsAll;
final Long countTargetsAll;
if (rsqlParam == null) { if (rsqlParam == null) {
findTargetsAll = this.tagManagement.findAllTargetTags(pageable); findTargetsAll = this.tagManagement.findAllTargetTags(pageable);
countTargetsAll = this.tagManagement.countTargetTags();
} else { } else {
final Page<TargetTag> findTargetPage = this.tagManagement.findAllTargetTags(rsqlParam, pageable); findTargetsAll = this.tagManagement.findAllTargetTags(rsqlParam, pageable);
countTargetsAll = findTargetPage.getTotalElements();
findTargetsAll = findTargetPage;
} }
final List<MgmtTag> rest = MgmtTagMapper.toResponse(findTargetsAll.getContent()); final List<MgmtTag> rest = MgmtTagMapper.toResponse(findTargetsAll.getContent());
return new ResponseEntity<>(new PagedList<>(rest, countTargetsAll), HttpStatus.OK); return new ResponseEntity<>(new PagedList<>(rest, findTargetsAll.getTotalElements()), HttpStatus.OK);
} }
@Override @Override
@@ -102,7 +97,7 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
} }
@Override @Override
public ResponseEntity<MgmtTag> updateTagretTag(@PathVariable("targetTagId") final Long targetTagId, public ResponseEntity<MgmtTag> updateTargetTag(@PathVariable("targetTagId") final Long targetTagId,
@RequestBody final MgmtTagRequestBodyPut restTargetTagRest) { @RequestBody final MgmtTagRequestBodyPut restTargetTagRest) {
LOG.debug("update {} target tag", restTargetTagRest); LOG.debug("update {} target tag", restTargetTagRest);
@@ -127,8 +122,36 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
@Override @Override
public ResponseEntity<List<MgmtTarget>> getAssignedTargets(@PathVariable("targetTagId") final Long targetTagId) { public ResponseEntity<List<MgmtTarget>> getAssignedTargets(@PathVariable("targetTagId") final Long targetTagId) {
final TargetTag targetTag = findTargetTagById(targetTagId);
return new ResponseEntity<>(MgmtTargetMapper.toResponse(targetTag.getAssignedToTargets()), HttpStatus.OK); return new ResponseEntity<>(MgmtTargetMapper.toResponse(targetManagement
.findTargetsByTag(new PageRequest(0, MgmtRestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT), targetTagId)
.getContent()), HttpStatus.OK);
}
@Override
public ResponseEntity<PagedList<MgmtTarget>> getAssignedTargets(@PathVariable("targetTagId") final Long targetTagId,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) {
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeTargetSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
Page<Target> findTargetsAll;
if (rsqlParam == null) {
findTargetsAll = targetManagement.findTargetsByTag(pageable, targetTagId);
} else {
findTargetsAll = targetManagement.findTargetsByTag(pageable, rsqlParam, targetTagId);
}
final Long countTargetsAll = findTargetsAll.getTotalElements();
final List<MgmtTarget> rest = MgmtTargetMapper.toResponse(findTargetsAll.getContent());
return new ResponseEntity<>(new PagedList<>(rest, countTargetsAll), HttpStatus.OK);
} }
@Override @Override
@@ -156,14 +179,6 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
return new ResponseEntity<>(MgmtTargetMapper.toResponse(assignedTarget), HttpStatus.OK); return new ResponseEntity<>(MgmtTargetMapper.toResponse(assignedTarget), HttpStatus.OK);
} }
@Override
public ResponseEntity<Void> unassignTargets(@PathVariable("targetTagId") final Long targetTagId) {
LOG.debug("Unassign all Targets for target tag {}", targetTagId);
this.targetManagement.unAssignAllTargetsByTag(targetTagId);
return new ResponseEntity<>(HttpStatus.OK);
}
@Override @Override
public ResponseEntity<Void> unassignTarget(@PathVariable("targetTagId") final Long targetTagId, public ResponseEntity<Void> unassignTarget(@PathVariable("targetTagId") final Long targetTagId,
@PathVariable("controllerId") final String controllerId) { @PathVariable("controllerId") final String controllerId) {
@@ -183,4 +198,21 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@Override
public ResponseEntity<MgmtTargetTagAssigmentResult> toggleTagAssignmentUnpaged(final Long targetTagId,
final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies) {
return toggleTagAssignment(targetTagId, assignedTargetRequestBodies);
}
@Override
public ResponseEntity<List<MgmtTarget>> assignTargetsUnpaged(final Long targetTagId,
final List<MgmtAssignedTargetRequestBody> assignedTargetRequestBodies) {
return assignTargets(targetTagId, assignedTargetRequestBodies);
}
@Override
public ResponseEntity<Void> unassignTargetUnpaged(final Long targetTagId, final String controllerId) {
return unassignTarget(targetTagId, controllerId);
}
} }

View File

@@ -19,6 +19,7 @@ import org.eclipse.hawkbit.repository.RolloutGroupFields;
import org.eclipse.hawkbit.repository.SoftwareModuleFields; import org.eclipse.hawkbit.repository.SoftwareModuleFields;
import org.eclipse.hawkbit.repository.SoftwareModuleMetadataFields; import org.eclipse.hawkbit.repository.SoftwareModuleMetadataFields;
import org.eclipse.hawkbit.repository.SoftwareModuleTypeFields; import org.eclipse.hawkbit.repository.SoftwareModuleTypeFields;
import org.eclipse.hawkbit.repository.TagFields;
import org.eclipse.hawkbit.repository.TargetFields; import org.eclipse.hawkbit.repository.TargetFields;
import org.eclipse.hawkbit.repository.TargetFilterQueryFields; import org.eclipse.hawkbit.repository.TargetFilterQueryFields;
import org.eclipse.hawkbit.rest.util.SortUtility; import org.eclipse.hawkbit.rest.util.SortUtility;
@@ -38,14 +39,14 @@ public final class PagingUtility {
static int sanitizeOffsetParam(final int offset) { static int sanitizeOffsetParam(final int offset) {
if (offset < 0) { if (offset < 0) {
return Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET); return MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE;
} }
return offset; return offset;
} }
static int sanitizePageLimitParam(final int pageLimit) { static int sanitizePageLimitParam(final int pageLimit) {
if (pageLimit < 1) { if (pageLimit < 1) {
return Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT); return MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE;
} else if (pageLimit > MgmtRestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT) { } else if (pageLimit > MgmtRestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT) {
return MgmtRestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT; return MgmtRestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT;
} }
@@ -55,15 +56,23 @@ public final class PagingUtility {
static Sort sanitizeTargetSortParam(final String sortParam) { static Sort sanitizeTargetSortParam(final String sortParam) {
if (sortParam == null) { if (sortParam == null) {
// default // default
return new Sort(Direction.ASC, TargetFields.NAME.getFieldName()); return new Sort(Direction.ASC, TargetFields.CONTROLLERID.getFieldName());
} }
return new Sort(SortUtility.parse(TargetFields.class, sortParam)); return new Sort(SortUtility.parse(TargetFields.class, sortParam));
} }
static Sort sanitizeTagSortParam(final String sortParam) {
if (sortParam == null) {
// default
return new Sort(Direction.ASC, TagFields.ID.getFieldName());
}
return new Sort(SortUtility.parse(TagFields.class, sortParam));
}
static Sort sanitizeTargetFilterQuerySortParam(final String sortParam) { static Sort sanitizeTargetFilterQuerySortParam(final String sortParam) {
if (sortParam == null) { if (sortParam == null) {
// default // default
return new Sort(Direction.ASC, TargetFilterQueryFields.NAME.getFieldName()); return new Sort(Direction.ASC, TargetFilterQueryFields.ID.getFieldName());
} }
return new Sort(SortUtility.parse(TargetFilterQueryFields.class, sortParam)); return new Sort(SortUtility.parse(TargetFilterQueryFields.class, sortParam));
} }
@@ -71,7 +80,7 @@ public final class PagingUtility {
static Sort sanitizeSoftwareModuleSortParam(final String sortParam) { static Sort sanitizeSoftwareModuleSortParam(final String sortParam) {
if (sortParam == null) { if (sortParam == null) {
// default // default
return new Sort(Direction.ASC, SoftwareModuleFields.NAME.getFieldName()); return new Sort(Direction.ASC, SoftwareModuleFields.ID.getFieldName());
} }
return new Sort(SortUtility.parse(SoftwareModuleFields.class, sortParam)); return new Sort(SortUtility.parse(SoftwareModuleFields.class, sortParam));
} }
@@ -79,7 +88,7 @@ public final class PagingUtility {
static Sort sanitizeSoftwareModuleTypeSortParam(final String sortParam) { static Sort sanitizeSoftwareModuleTypeSortParam(final String sortParam) {
if (sortParam == null) { if (sortParam == null) {
// default // default
return new Sort(Direction.ASC, SoftwareModuleTypeFields.NAME.getFieldName()); return new Sort(Direction.ASC, SoftwareModuleTypeFields.ID.getFieldName());
} }
return new Sort(SortUtility.parse(SoftwareModuleTypeFields.class, sortParam)); return new Sort(SortUtility.parse(SoftwareModuleTypeFields.class, sortParam));
} }
@@ -87,7 +96,7 @@ public final class PagingUtility {
static Sort sanitizeDistributionSetSortParam(final String sortParam) { static Sort sanitizeDistributionSetSortParam(final String sortParam) {
if (sortParam == null) { if (sortParam == null) {
// default // default
return new Sort(Direction.ASC, DistributionSetFields.NAME.getFieldName()); return new Sort(Direction.ASC, DistributionSetFields.ID.getFieldName());
} }
return new Sort(SortUtility.parse(DistributionSetFields.class, sortParam)); return new Sort(SortUtility.parse(DistributionSetFields.class, sortParam));
} }
@@ -95,7 +104,7 @@ public final class PagingUtility {
static Sort sanitizeDistributionSetTypeSortParam(final String sortParam) { static Sort sanitizeDistributionSetTypeSortParam(final String sortParam) {
if (sortParam == null) { if (sortParam == null) {
// default // default
return new Sort(Direction.ASC, DistributionSetTypeFields.NAME.getFieldName()); return new Sort(Direction.ASC, DistributionSetTypeFields.ID.getFieldName());
} }
return new Sort(SortUtility.parse(DistributionSetTypeFields.class, sortParam)); return new Sort(SortUtility.parse(DistributionSetTypeFields.class, sortParam));
} }
@@ -137,7 +146,7 @@ public final class PagingUtility {
static Sort sanitizeRolloutSortParam(final String sortParam) { static Sort sanitizeRolloutSortParam(final String sortParam) {
if (sortParam == null) { if (sortParam == null) {
// default // default
return new Sort(Direction.ASC, RolloutFields.NAME.getFieldName()); return new Sort(Direction.ASC, RolloutFields.ID.getFieldName());
} }
return new Sort(SortUtility.parse(RolloutFields.class, sortParam)); return new Sort(SortUtility.parse(RolloutFields.class, sortParam));
} }
@@ -145,7 +154,7 @@ public final class PagingUtility {
static Sort sanitizeRolloutGroupSortParam(final String sortParam) { static Sort sanitizeRolloutGroupSortParam(final String sortParam) {
if (sortParam == null) { if (sortParam == null) {
// default // default
return new Sort(Direction.ASC, RolloutGroupFields.NAME.getFieldName()); return new Sort(Direction.ASC, RolloutGroupFields.ID.getFieldName());
} }
return new Sort(SortUtility.parse(RolloutGroupFields.class, sortParam)); return new Sort(SortUtility.parse(RolloutGroupFields.class, sortParam));
} }

View File

@@ -8,10 +8,186 @@
*/ */
package org.eclipse.hawkbit.mgmt.rest.resource; package org.eclipse.hawkbit.mgmt.rest.resource;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import org.eclipse.hawkbit.repository.model.BaseEntity;
import org.eclipse.hawkbit.repository.model.NamedEntity;
import org.eclipse.hawkbit.repository.model.NamedVersionedEntity;
import org.eclipse.hawkbit.repository.model.Tag;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest; import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.web.servlet.ResultMatcher;
@SpringApplicationConfiguration(classes = { MgmtApiConfiguration.class }) @SpringApplicationConfiguration(classes = { MgmtApiConfiguration.class })
public abstract class AbstractManagementApiIntegrationTest extends AbstractRestIntegrationTest { public abstract class AbstractManagementApiIntegrationTest extends AbstractRestIntegrationTest {
protected static ResultMatcher applyBaseEntityMatcherOnArrayResult(final BaseEntity entity,
final String arrayElement) throws Exception {
return mvcResult -> {
jsonPath("$." + arrayElement + ".[?(@.id==" + entity.getId() + ")].createdBy",
contains(entity.getCreatedBy())).match(mvcResult);
jsonPath("$." + arrayElement + ".[?(@.id==" + entity.getId() + ")].createdAt",
contains(entity.getCreatedAt())).match(mvcResult);
jsonPath("$." + arrayElement + ".[?(@.id==" + entity.getId() + ")].lastModifiedBy",
contains(entity.getLastModifiedBy())).match(mvcResult);
jsonPath("$." + arrayElement + ".[?(@.id==" + entity.getId() + ")].lastModifiedAt",
contains(entity.getLastModifiedAt())).match(mvcResult);
};
}
protected static ResultMatcher applyTargetEntityMatcherOnArrayResult(final Target entity, final String arrayElement)
throws Exception {
return mvcResult -> {
jsonPath("$." + arrayElement + ".[?(@.controllerId==" + entity.getControllerId() + ")].createdBy",
contains(entity.getCreatedBy())).match(mvcResult);
jsonPath("$." + arrayElement + ".[?(@.controllerId==" + entity.getControllerId() + ")].createdAt",
contains(entity.getCreatedAt())).match(mvcResult);
jsonPath("$." + arrayElement + ".[?(@.controllerId==" + entity.getControllerId() + ")].lastModifiedBy",
contains(entity.getLastModifiedBy())).match(mvcResult);
jsonPath("$." + arrayElement + ".[?(@.controllerId==" + entity.getControllerId() + ")].lastModifiedAt",
contains(entity.getLastModifiedAt())).match(mvcResult);
};
}
protected static ResultMatcher applyBaseEntityMatcherOnPagedResult(final BaseEntity entity) throws Exception {
return applyBaseEntityMatcherOnArrayResult(entity, "content");
}
protected static ResultMatcher applyNamedEntityMatcherOnPagedResult(final NamedEntity entity) throws Exception {
return mvcResult -> {
applyBaseEntityMatcherOnPagedResult(entity).match(mvcResult);
jsonPath("$.content.[?(@.id==" + entity.getId() + ")].name", contains(entity.getName())).match(mvcResult);
jsonPath("$.content.[?(@.id==" + entity.getId() + ")].description", contains(entity.getDescription()))
.match(mvcResult);
};
}
protected static ResultMatcher applyNamedVersionedEntityMatcherOnPagedResult(final NamedVersionedEntity entity)
throws Exception {
return mvcResult -> {
applyNamedEntityMatcherOnPagedResult(entity).match(mvcResult);
jsonPath("$.content.[?(@.id==" + entity.getId() + ")].version", contains(entity.getVersion()))
.match(mvcResult);
};
}
protected static ResultMatcher applyTagMatcherOnPagedResult(final Tag entity) throws Exception {
return mvcResult -> {
applyNamedEntityMatcherOnPagedResult(entity).match(mvcResult);
jsonPath("$.content.[?(@.id==" + entity.getId() + ")].colour", contains(entity.getColour()))
.match(mvcResult);
};
}
protected static ResultMatcher applySelfLinkMatcherOnPagedResult(final BaseEntity entity, final String link)
throws Exception {
return mvcResult -> {
jsonPath("$.content.[?(@.id==" + entity.getId() + ")]._links.self.href", contains(link)).match(mvcResult);
};
}
protected static ResultMatcher applyBaseEntityMatcherOnArrayResult(final BaseEntity entity) throws Exception {
return mvcResult -> {
jsonPath("$.[?(@.id==" + entity.getId() + ")].createdBy", contains(entity.getCreatedBy())).match(mvcResult);
jsonPath("$.[?(@.id==" + entity.getId() + ")].createdAt", contains(entity.getCreatedAt())).match(mvcResult);
jsonPath("$.[?(@.id==" + entity.getId() + ")].lastModifiedBy", contains(entity.getLastModifiedBy()))
.match(mvcResult);
jsonPath("$.[?(@.id==" + entity.getId() + ")].lastModifiedAt", contains(entity.getLastModifiedAt()))
.match(mvcResult);
};
}
protected static ResultMatcher applyTargetEntityMatcherOnArrayResult(final Target entity) throws Exception {
return mvcResult -> {
jsonPath("$.[?(@.controllerId==" + entity.getControllerId() + ")].createdBy",
contains(entity.getCreatedBy())).match(mvcResult);
jsonPath("$.[?(@.controllerId==" + entity.getControllerId() + ")].createdAt",
contains(entity.getCreatedAt())).match(mvcResult);
jsonPath("$.[?(@.controllerId==" + entity.getControllerId() + ")].lastModifiedBy",
contains(entity.getLastModifiedBy())).match(mvcResult);
jsonPath("$.[?(@.controllerId==" + entity.getControllerId() + ")].lastModifiedAt",
contains(entity.getLastModifiedAt())).match(mvcResult);
};
}
protected static ResultMatcher applyNamedEntityMatcherOnArrayResult(final NamedEntity entity) throws Exception {
return mvcResult -> {
applyBaseEntityMatcherOnPagedResult(entity);
jsonPath("$.[?(@.id==" + entity.getId() + ")].name", contains(entity.getName())).match(mvcResult);
jsonPath("$.[?(@.id==" + entity.getId() + ")].description", contains(entity.getDescription()))
.match(mvcResult);
};
}
protected static ResultMatcher applyNamedVersionedEntityMatcherOnArrayResult(final NamedVersionedEntity entity)
throws Exception {
return mvcResult -> {
applyNamedEntityMatcherOnPagedResult(entity);
jsonPath("$.[?(@.id==" + entity.getId() + ")].version", contains(entity.getVersion())).match(mvcResult);
};
}
protected static ResultMatcher applyTagMatcherOnArrayResult(final Tag entity) throws Exception {
return mvcResult -> {
applyNamedEntityMatcherOnPagedResult(entity);
jsonPath("$.[?(@.id==" + entity.getId() + ")].colour", contains(entity.getColour())).match(mvcResult);
};
}
protected static ResultMatcher applySelfLinkMatcherOnArrayResult(final BaseEntity entity, final String link)
throws Exception {
return mvcResult -> {
jsonPath("$.[?(@.id==" + entity.getId() + ")]._links.self.href", contains(link)).match(mvcResult);
};
}
protected static ResultMatcher applyBaseEntityMatcherOnSingleResult(final BaseEntity entity) throws Exception {
return mvcResult -> {
jsonPath("createdBy", equalTo(entity.getCreatedBy())).match(mvcResult);
jsonPath("createdAt", equalTo(entity.getCreatedAt())).match(mvcResult);
jsonPath("lastModifiedBy", equalTo(entity.getLastModifiedBy())).match(mvcResult);
jsonPath("lastModifiedAt", equalTo(entity.getLastModifiedAt())).match(mvcResult);
};
}
protected static ResultMatcher applyNamedEntityMatcherOnSingleResult(final NamedEntity entity) throws Exception {
return mvcResult -> {
applyBaseEntityMatcherOnSingleResult(entity);
jsonPath("name", equalTo(entity.getName())).match(mvcResult);
jsonPath("description", equalTo(entity.getDescription())).match(mvcResult);
};
}
protected static ResultMatcher applyNamedVersionedEntityMatcherOnSingleResult(final NamedVersionedEntity entity)
throws Exception {
return mvcResult -> {
applyNamedEntityMatcherOnSingleResult(entity);
jsonPath("version", equalTo(entity.getVersion())).match(mvcResult);
};
}
protected static ResultMatcher applyTagMatcherOnSingleResult(final Tag entity) throws Exception {
return mvcResult -> {
applyNamedEntityMatcherOnSingleResult(entity);
jsonPath("colour", equalTo(entity.getColour())).match(mvcResult);
};
}
protected static ResultMatcher applySelfLinkMatcherOnSingleResult(final String link) throws Exception {
return mvcResult -> {
jsonPath("_links.self.href", equalTo(link)).match(mvcResult);
};
}
} }

View File

@@ -169,14 +169,11 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
// create Software Modules // create Software Modules
final List<Long> smIDs = Lists.newArrayList(testdataFactory.createSoftwareModuleOs().getId(), final List<Long> smIDs = Lists.newArrayList(testdataFactory.createSoftwareModuleOs().getId(),
testdataFactory.createSoftwareModuleApp().getId()); testdataFactory.createSoftwareModuleApp().getId());
final JSONArray list = new JSONArray();
for (final Long smID : smIDs) {
list.put(new JSONObject().put("id", Long.valueOf(smID)));
}
// post assignment // post assignment
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(list.toString())).andDo(MockMvcResultPrinter.print()) .contentType(MediaType.APPLICATION_JSON).content(JsonBuilder.ids(smIDs)))
.andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
// Test if size is 3 // Test if size is 3
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM")) mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
@@ -228,7 +225,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.andExpect(jsonPath("$.alreadyAssigned", equalTo(1))) .andExpect(jsonPath("$.alreadyAssigned", equalTo(1)))
.andExpect(jsonPath("$.total", equalTo(knownTargetIds.length))); .andExpect(jsonPath("$.total", equalTo(knownTargetIds.length)));
assertThat(targetManagement.findTargetByAssignedDistributionSet(createdDs.getId(), pageReq).getContent()) assertThat(targetManagement.findTargetByAssignedDistributionSet(createdDs.getId(), PAGE).getContent())
.as("Five targets in repository have DS assigned").hasSize(5); .as("Five targets in repository have DS assigned").hasSize(5);
} }
@@ -417,7 +414,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
@Description("Ensures that multiple DS requested are listed with expected payload.") @Description("Ensures that multiple DS requested are listed with expected payload.")
public void getDistributionSets() throws Exception { public void getDistributionSets() throws Exception {
// prepare test data // prepare test data
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)) assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(0); .hasSize(0);
DistributionSet set = testdataFactory.createDistributionSet("one"); DistributionSet set = testdataFactory.createDistributionSet("one");
@@ -427,7 +424,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
// load also lazy stuff // load also lazy stuff
set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()).get(); set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()).get();
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)) assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(1); .hasSize(1);
// perform request // perform request
@@ -491,7 +488,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
@WithUser(principal = "uploadTester", allSpPermissions = true) @WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Ensures that multipe DS posted to API are created in the repository.") @Description("Ensures that multipe DS posted to API are created in the repository.")
public void createDistributionSets() throws Exception { public void createDistributionSets() throws Exception {
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)) assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(0); .hasSize(0);
final SoftwareModule ah = testdataFactory.createSoftwareModule(TestdataFactory.SM_TYPE_APP); final SoftwareModule ah = testdataFactory.createSoftwareModule(TestdataFactory.SM_TYPE_APP);
@@ -510,11 +507,11 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
final MvcResult mvcResult = executeMgmtTargetPost(one, two, three); final MvcResult mvcResult = executeMgmtTargetPost(one, two, three);
one = distributionSetManagement.findDistributionSetByIdWithDetails(distributionSetManagement one = distributionSetManagement.findDistributionSetByIdWithDetails(distributionSetManagement
.findDistributionSetsAll("name==one", pageReq, false).getContent().get(0).getId()).get(); .findDistributionSetsAll("name==one", PAGE, false).getContent().get(0).getId()).get();
two = distributionSetManagement.findDistributionSetByIdWithDetails(distributionSetManagement two = distributionSetManagement.findDistributionSetByIdWithDetails(distributionSetManagement
.findDistributionSetsAll("name==two", pageReq, false).getContent().get(0).getId()).get(); .findDistributionSetsAll("name==two", PAGE, false).getContent().get(0).getId()).get();
three = distributionSetManagement.findDistributionSetByIdWithDetails(distributionSetManagement three = distributionSetManagement.findDistributionSetByIdWithDetails(distributionSetManagement
.findDistributionSetsAll("name==three", pageReq, false).getContent().get(0).getId()).get(); .findDistributionSetsAll("name==three", PAGE, false).getContent().get(0).getId()).get();
assertThat( assertThat(
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString()) JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
@@ -545,7 +542,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.isEqualTo(String.valueOf(three.getId())); .isEqualTo(String.valueOf(three.getId()));
// check in database // check in database
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)) assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(3); .hasSize(3);
assertThat(one.isRequiredMigrationStep()).isEqualTo(false); assertThat(one.isRequiredMigrationStep()).isEqualTo(false);
assertThat(two.isRequiredMigrationStep()).isEqualTo(false); assertThat(two.isRequiredMigrationStep()).isEqualTo(false);
@@ -610,12 +607,12 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
@Description("Ensures that DS deletion request to API is reflected by the repository.") @Description("Ensures that DS deletion request to API is reflected by the repository.")
public void deleteUnassignedistributionSet() throws Exception { public void deleteUnassignedistributionSet() throws Exception {
// prepare test data // prepare test data
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)) assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(0); .hasSize(0);
final DistributionSet set = testdataFactory.createDistributionSet("one"); final DistributionSet set = testdataFactory.createDistributionSet("one");
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)) assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(1); .hasSize(1);
// perform request // perform request
@@ -623,7 +620,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.andExpect(status().isOk()); .andExpect(status().isOk());
// check repository content // check repository content
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)) assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.isEmpty(); .isEmpty();
assertThat(distributionSetManagement.countDistributionSetsAll()).isEqualTo(0); assertThat(distributionSetManagement.countDistributionSetsAll()).isEqualTo(0);
} }
@@ -639,14 +636,14 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
@Description("Ensures that assigned DS deletion request to API is reflected by the repository by means of deleted flag set.") @Description("Ensures that assigned DS deletion request to API is reflected by the repository by means of deleted flag set.")
public void deleteAssignedDistributionSet() throws Exception { public void deleteAssignedDistributionSet() throws Exception {
// prepare test data // prepare test data
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)) assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(0); .hasSize(0);
final DistributionSet set = testdataFactory.createDistributionSet("one"); final DistributionSet set = testdataFactory.createDistributionSet("one");
testdataFactory.createTarget("test"); testdataFactory.createTarget("test");
assignDistributionSet(set.getId(), "test"); assignDistributionSet(set.getId(), "test");
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)) assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(1); .hasSize(1);
// perform request // perform request
@@ -654,9 +651,9 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.andExpect(status().isOk()); .andExpect(status().isOk());
// check repository content // check repository content
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)) assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(0); .hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, true, true)) assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, true, true))
.hasSize(1); .hasSize(1);
} }
@@ -665,7 +662,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
public void updateDistributionSet() throws Exception { public void updateDistributionSet() throws Exception {
// prepare test data // prepare test data
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)) assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(0); .hasSize(0);
final DistributionSet set = testdataFactory.createDistributionSet("one"); final DistributionSet set = testdataFactory.createDistributionSet("one");
@@ -689,7 +686,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
public void updateRequiredMigrationStepFailsIfDistributionSetisInUse() throws Exception { public void updateRequiredMigrationStepFailsIfDistributionSetisInUse() throws Exception {
// prepare test data // prepare test data
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)) assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(0); .hasSize(0);
final DistributionSet set = testdataFactory.createDistributionSet("one"); final DistributionSet set = testdataFactory.createDistributionSet("one");

View File

@@ -0,0 +1,328 @@
/**
* 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.mgmt.rest.resource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasSize;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.event.remote.DistributionSetTagDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetTagCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetTagUpdatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetUpdatedEvent;
import org.eclipse.hawkbit.repository.model.BaseEntity;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.eclipse.hawkbit.repository.model.Tag;
import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.json.JSONException;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.ResultActions;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
@Features("Component Tests - Management API")
@Stories("Distribution Set Tag Resource")
public class MgmtDistributionSetTagResourceTest extends AbstractManagementApiIntegrationTest {
private static final String DISTRIBUTIONSETTAGS_ROOT = "http://localhost"
+ MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/";
@Test
@Description("Verfies that a paged result list of DS tags reflects the content on the repository side.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 2) })
public void getDistributionSetTags() throws Exception {
final List<DistributionSetTag> tags = testdataFactory.createDistributionSetTags(2);
final DistributionSetTag assigned = tags.get(0);
final DistributionSetTag unassigned = tags.get(1);
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(applyBaseEntityMatcherOnPagedResult(assigned))
.andExpect(applyBaseEntityMatcherOnPagedResult(unassigned))
.andExpect(applySelfLinkMatcherOnPagedResult(assigned, DISTRIBUTIONSETTAGS_ROOT + assigned.getId()))
.andExpect(applySelfLinkMatcherOnPagedResult(unassigned, DISTRIBUTIONSETTAGS_ROOT + unassigned.getId()))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(2)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(2)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(2)))
.andExpect(jsonPath(
"$.content.[?(@.id==" + assigned.getId() + ")]._links.assignedDistributionSets.href",
contains(DISTRIBUTIONSETTAGS_ROOT + assigned.getId() + "/assigned?offset=0&limit=50{&sort,q}")))
.andExpect(
jsonPath("$.content.[?(@.id==" + unassigned.getId() + ")]._links.assignedDistributionSets.href",
contains(DISTRIBUTIONSETTAGS_ROOT + unassigned.getId()
+ "/assigned?offset=0&limit=50{&sort,q}")));
}
@Test
@Description("Verfies that a single result of a DS tag reflects the content on the repository side.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 2) })
public void getDistributionSetTag() throws Exception {
final List<DistributionSetTag> tags = testdataFactory.createDistributionSetTags(2);
final DistributionSetTag assigned = tags.get(0);
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + assigned.getId())
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(applyTagMatcherOnSingleResult(assigned))
.andExpect(applySelfLinkMatcherOnSingleResult(DISTRIBUTIONSETTAGS_ROOT + assigned.getId()))
.andExpect(jsonPath("_links.assignedDistributionSets.href",
equalTo(DISTRIBUTIONSETTAGS_ROOT + assigned.getId() + "/assigned?offset=0&limit=50{&sort,q}")));
}
@Test
@Description("Verifies that created DS tags are stored in the repository as send to the API.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 2) })
public void createDistributionSetTags() throws JSONException, Exception {
final Tag tagOne = entityFactory.tag().create().colour("testcol1").description("its a test1").name("thetest1")
.build();
final Tag tagTwo = entityFactory.tag().create().colour("testcol2").description("its a test2").name("thetest2")
.build();
final ResultActions result = mvc
.perform(post(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING)
.content(JsonBuilder.tags(Arrays.asList(tagOne, tagTwo)))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
final Tag createdOne = tagManagement.findAllDistributionSetTags("name==thetest1", PAGE).getContent().get(0);
assertThat(createdOne.getName()).isEqualTo(tagOne.getName());
assertThat(createdOne.getDescription()).isEqualTo(tagOne.getDescription());
assertThat(createdOne.getColour()).isEqualTo(tagOne.getColour());
final Tag createdTwo = tagManagement.findAllDistributionSetTags("name==thetest2", PAGE).getContent().get(0);
assertThat(createdTwo.getName()).isEqualTo(tagTwo.getName());
assertThat(createdTwo.getDescription()).isEqualTo(tagTwo.getDescription());
assertThat(createdTwo.getColour()).isEqualTo(tagTwo.getColour());
result.andExpect(applyTagMatcherOnArrayResult(createdOne)).andExpect(applyTagMatcherOnArrayResult(createdTwo));
}
@Test
@Description("Verifies that an updated DS tag is stored in the repository as send to the API.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 1),
@Expect(type = DistributionSetTagUpdatedEvent.class, count = 1) })
public void updateDistributionSetTag() throws Exception {
final List<DistributionSetTag> tags = testdataFactory.createDistributionSetTags(1);
final DistributionSetTag original = tags.get(0);
final Tag update = entityFactory.tag().create().name("updatedName").colour("updatedCol")
.description("updatedDesc").build();
final ResultActions result = mvc
.perform(put(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + original.getId())
.content(JsonBuilder.tag(update)).contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
final Tag updated = tagManagement.findAllDistributionSetTags("name==updatedName", PAGE).getContent().get(0);
assertThat(updated.getName()).isEqualTo(update.getName());
assertThat(updated.getDescription()).isEqualTo(update.getDescription());
assertThat(updated.getColour()).isEqualTo(update.getColour());
result.andExpect(applyTagMatcherOnArrayResult(updated)).andExpect(applyTagMatcherOnArrayResult(updated));
}
@Test
@Description("Verfies that the delete call is reflected by the repository.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 1),
@Expect(type = DistributionSetTagDeletedEvent.class, count = 1) })
public void deleteDistributionSetTag() throws Exception {
final List<DistributionSetTag> tags = testdataFactory.createDistributionSetTags(1);
final DistributionSetTag original = tags.get(0);
mvc.perform(delete(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + original.getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(tagManagement.findDistributionSetTagById(original.getId())).isNotPresent();
}
@Test
@Description("Ensures that assigned DS to tag in repository are listed with proper paging results.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 5),
@Expect(type = DistributionSetUpdatedEvent.class, count = 5) })
public void getAssignedDistributionSets() throws Exception {
final DistributionSetTag tag = testdataFactory.createDistributionSetTags(1).get(0);
final int setsAssigned = 5;
final List<DistributionSet> sets = testdataFactory.createDistributionSetsWithoutModules(setsAssigned);
distributionSetManagement.toggleTagAssignment(sets.stream().map(BaseEntity::getId).collect(Collectors.toList()),
tag.getName());
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(setsAssigned)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(setsAssigned)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(setsAssigned)));
}
@Test
@Description("Ensures that assigned DS to tag in repository are listed with proper paging results with paging limit parameter.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 5),
@Expect(type = DistributionSetUpdatedEvent.class, count = 5) })
public void getAssignedDistributionSetsWithPagingLimitRequestParameter() throws Exception {
final DistributionSetTag tag = testdataFactory.createDistributionSetTags(1).get(0);
final int setsAssigned = 5;
final int limitSize = 1;
final List<DistributionSet> sets = testdataFactory.createDistributionSetsWithoutModules(setsAssigned);
distributionSetManagement.toggleTagAssignment(sets.stream().map(BaseEntity::getId).collect(Collectors.toList()),
tag.getName());
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize)))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(setsAssigned)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize)));
}
@Test
@Description("Ensures that assigned DS to tag in repository are listed with proper paging results with paging limit and offset parameter.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 5),
@Expect(type = DistributionSetUpdatedEvent.class, count = 5) })
public void getAssignedDistributionSetsWithPagingLimitAndOffsetRequestParameter() throws Exception {
final DistributionSetTag tag = testdataFactory.createDistributionSetTags(1).get(0);
final int setsAssigned = 5;
final int offsetParam = 2;
final int expectedSize = setsAssigned - offsetParam;
final List<DistributionSet> sets = testdataFactory.createDistributionSetsWithoutModules(setsAssigned);
distributionSetManagement.toggleTagAssignment(sets.stream().map(BaseEntity::getId).collect(Collectors.toList()),
tag.getName());
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam))
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(setsAssigned)))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(setsAssigned)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize)));
}
@Test
@Description("Verfies that tag assignments done through toggle API command are correctly assigned or unassigned.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 2),
@Expect(type = DistributionSetUpdatedEvent.class, count = 4) })
public void toggleTagAssignment() throws Exception {
final DistributionSetTag tag = testdataFactory.createDistributionSetTags(1).get(0);
final int setsAssigned = 2;
final List<DistributionSet> sets = testdataFactory.createDistributionSetsWithoutModules(setsAssigned);
// 2 DistributionSetUpdateEvent
ResultActions result = toggle(tag, sets);
List<DistributionSet> updated = distributionSetManagement.findDistributionSetsByTag(PAGE, tag.getId())
.getContent();
assertThat(updated.stream().map(DistributionSet::getId).collect(Collectors.toList()))
.containsAll(sets.stream().map(DistributionSet::getId).collect(Collectors.toList()));
result.andExpect(applyBaseEntityMatcherOnArrayResult(updated.get(0), "assignedDistributionSets"))
.andExpect(applyBaseEntityMatcherOnArrayResult(updated.get(1), "assignedDistributionSets"));
// 2 DistributionSetUpdateEvent
result = toggle(tag, sets);
updated = distributionSetManagement.findDistributionSetsAll(PAGE, false).getContent();
result.andExpect(applyBaseEntityMatcherOnArrayResult(updated.get(0), "unassignedDistributionSets"))
.andExpect(applyBaseEntityMatcherOnArrayResult(updated.get(1), "unassignedDistributionSets"));
assertThat(distributionSetManagement.findDistributionSetsByTag(PAGE, tag.getId())).isEmpty();
}
private ResultActions toggle(final DistributionSetTag tag, final List<DistributionSet> sets) throws Exception {
return mvc
.perform(post(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId()
+ "/assigned/toggleTagAssignment").content(
JsonBuilder.ids(sets.stream().map(DistributionSet::getId).collect(Collectors.toList())))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
}
@Test
@Description("Verfies that tag assignments done through tag API command are correctly stored in the repository.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 2),
@Expect(type = DistributionSetUpdatedEvent.class, count = 2) })
public void assignDistributionSets() throws Exception {
final DistributionSetTag tag = testdataFactory.createDistributionSetTags(1).get(0);
final int setsAssigned = 2;
final List<DistributionSet> sets = testdataFactory.createDistributionSetsWithoutModules(setsAssigned);
final ResultActions result = mvc
.perform(
post(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.content(JsonBuilder
.ids(sets.stream().map(DistributionSet::getId).collect(Collectors.toList())))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
final List<DistributionSet> updated = distributionSetManagement.findDistributionSetsByTag(PAGE, tag.getId())
.getContent();
assertThat(updated.stream().map(DistributionSet::getId).collect(Collectors.toList()))
.containsAll(sets.stream().map(DistributionSet::getId).collect(Collectors.toList()));
result.andExpect(applyBaseEntityMatcherOnArrayResult(updated.get(0)))
.andExpect(applyBaseEntityMatcherOnArrayResult(updated.get(1)));
}
@Test
@Description("Verfies that tag unassignments done through tag API command are correctly stored in the repository.")
@ExpectEvents({ @Expect(type = DistributionSetTagCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 2),
@Expect(type = DistributionSetUpdatedEvent.class, count = 3) })
public void unassignDistributionSet() throws Exception {
final DistributionSetTag tag = testdataFactory.createDistributionSetTags(1).get(0);
final int setsAssigned = 2;
final List<DistributionSet> sets = testdataFactory.createDistributionSetsWithoutModules(setsAssigned);
final DistributionSet assigned = sets.get(0);
final DistributionSet unassigned = sets.get(1);
distributionSetManagement.toggleTagAssignment(sets.stream().map(BaseEntity::getId).collect(Collectors.toList()),
tag.getName());
mvc.perform(delete(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned/"
+ unassigned.getId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
final List<DistributionSet> updated = distributionSetManagement.findDistributionSetsByTag(PAGE, tag.getId())
.getContent();
assertThat(updated.stream().map(DistributionSet::getId).collect(Collectors.toList()))
.containsOnly(assigned.getId());
}
}

View File

@@ -71,7 +71,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
@Before @Before
public void assertPreparationOfRepo() { public void assertPreparationOfRepo() {
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("no softwaremodule should be founded") assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).as("no softwaremodule should be founded")
.hasSize(0); .hasSize(0);
} }
@@ -182,7 +182,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
@Test @Test
@Description("Verfies that the system does not accept empty artifact uploads. Expected response: BAD REQUEST") @Description("Verfies that the system does not accept empty artifact uploads. Expected response: BAD REQUEST")
public void emptyUploadArtifact() throws Exception { public void emptyUploadArtifact() throws Exception {
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).hasSize(0);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(0); assertThat(artifactManagement.countArtifactsAll()).isEqualTo(0);
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
@@ -313,7 +313,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
assertTrue("Response has wrong response content", assertTrue("Response has wrong response content",
Arrays.equals(result2.getResponse().getContentAsByteArray(), random)); Arrays.equals(result2.getResponse().getContentAsByteArray(), random));
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Softwaremodule size is wrong").hasSize(1); assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).as("Softwaremodule size is wrong").hasSize(1);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(2); assertThat(artifactManagement.countArtifactsAll()).isEqualTo(2);
} }
@@ -551,7 +551,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")]._links.self.href", .andExpect(jsonPath("$.content.[?(@.id==" + app.getId() + ")]._links.self.href",
contains("http://localhost/rest/v1/softwaremodules/" + app.getId()))); contains("http://localhost/rest/v1/softwaremodules/" + app.getId())));
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Softwaremodule size is wrong").hasSize(2); assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).as("Softwaremodule size is wrong").hasSize(2);
} }
@Test @Test
@@ -562,7 +562,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
testdataFactory.createSoftwareModuleOs("2"); testdataFactory.createSoftwareModuleOs("2");
final SoftwareModule app2 = testdataFactory.createSoftwareModuleApp("2"); final SoftwareModule app2 = testdataFactory.createSoftwareModuleApp("2");
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(4); assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).hasSize(4);
// only by name, only one exists per name // only by name, only one exists per name
mvc.perform(get("/rest/v1/softwaremodules?q=name==" + os1.getName()).accept(MediaType.APPLICATION_JSON)) mvc.perform(get("/rest/v1/softwaremodules?q=name==" + os1.getName()).accept(MediaType.APPLICATION_JSON))
@@ -652,7 +652,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.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")));
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Softwaremodule size is wrong").hasSize(1); assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).as("Softwaremodule size is wrong").hasSize(1);
} }
@Test @Test
@@ -707,14 +707,14 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.toString()).as("Response contains invalid artifacts href") .toString()).as("Response contains invalid artifacts href")
.isEqualTo("http://localhost/rest/v1/softwaremodules/" + appCreated.getId() + "/artifacts"); .isEqualTo("http://localhost/rest/v1/softwaremodules/" + appCreated.getId() + "/artifacts");
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Wrong softwaremodule size").hasSize(2); assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).as("Wrong softwaremodule size").hasSize(2);
assertThat(softwareManagement.findSoftwareModulesByType(pageReq, osType.getId()).getContent().get(0).getName()) assertThat(softwareManagement.findSoftwareModulesByType(PAGE, 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(PAGE, 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(PAGE, 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, appType.getId()).getContent().get(0).getName()) assertThat(softwareManagement.findSoftwareModulesByType(PAGE, appType.getId()).getContent().get(0).getName())
.as("Softwaremoudle name is wrong").isEqualTo(ah.getName()); .as("Softwaremoudle name is wrong").isEqualTo(ah.getName());
} }
@@ -728,13 +728,13 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
artifactManagement.createArtifact(new ByteArrayInputStream(random), sm.getId(), "file1", false); artifactManagement.createArtifact(new ByteArrayInputStream(random), sm.getId(), "file1", false);
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("Softwaremoudle size is wrong").hasSize(1); assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).as("Softwaremoudle size is wrong").hasSize(1);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1); assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1);
mvc.perform(delete("/rest/v1/softwaremodules/{smId}", sm.getId())).andDo(MockMvcResultPrinter.print()) mvc.perform(delete("/rest/v1/softwaremodules/{smId}", sm.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()); .andExpect(status().isOk());
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)) assertThat(softwareManagement.findSoftwareModulesAll(PAGE))
.as("After delete no softwarmodule should be available").isEmpty(); .as("After delete no softwarmodule should be available").isEmpty();
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(0); assertThat(artifactManagement.countArtifactsAll()).isEqualTo(0);
} }
@@ -749,7 +749,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
artifactManagement.createArtifact(new ByteArrayInputStream(random), artifactManagement.createArtifact(new ByteArrayInputStream(random),
ds1.findFirstModuleByType(appType).get().getId(), "file1", false); ds1.findFirstModuleByType(appType).get().getId(), "file1", false);
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(3); assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).hasSize(3);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1); assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1);
mvc.perform(delete("/rest/v1/softwaremodules/{smId}", ds1.findFirstModuleByType(appType).get().getId())) mvc.perform(delete("/rest/v1/softwaremodules/{smId}", ds1.findFirstModuleByType(appType).get().getId()))
@@ -760,7 +760,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
// all 3 are now marked as deleted // all 3 are now marked as deleted
assertThat(softwareManagement.findSoftwareModulesAll(pageReq).getNumber()) assertThat(softwareManagement.findSoftwareModulesAll(PAGE).getNumber())
.as("After delete no softwarmodule should be available").isEqualTo(0); .as("After delete no softwarmodule should be available").isEqualTo(0);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1); assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1);
} }
@@ -779,7 +779,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
artifactManagement.createArtifact(new ByteArrayInputStream(random), sm.getId(), "file2", false); artifactManagement.createArtifact(new ByteArrayInputStream(random), sm.getId(), "file2", false);
// check repo before delete // check repo before delete
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(1); assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).hasSize(1);
assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts()).hasSize(2); assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts()).hasSize(2);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(2); assertThat(artifactManagement.countArtifactsAll()).isEqualTo(2);
@@ -789,7 +789,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
// check that only one artifact is still alive and still assigned // check that only one artifact is still alive and still assigned
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("After the sm should be marked as deleted") assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).as("After the sm should be marked as deleted")
.hasSize(1); .hasSize(1);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1); assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1);
assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts()) assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts())

View File

@@ -110,9 +110,10 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
entityFactory.actionStatus().create(actions.get(0).getId()).status(Status.FINISHED).message("test")); entityFactory.actionStatus().create(actions.get(0).getId()).status(Status.FINISHED).message("test"));
final PageRequest pageRequest = new PageRequest(0, 1000, Direction.ASC, ActionFields.ID.getFieldName()); final PageRequest pageRequest = new PageRequest(0, 1000, Direction.ASC, ActionFields.ID.getFieldName());
final ActionStatus status = deploymentManagement.findActionsByTarget(knownTargetId, pageRequest).getContent() final Action action = deploymentManagement.findActionsByTarget(knownTargetId, pageRequest).getContent().get(0);
.get(0).getActionStatus().stream().sorted((e1, e2) -> Long.compare(e2.getId(), e1.getId()))
.collect(Collectors.toList()).get(0); final ActionStatus status = deploymentManagement.findActionStatusByAction(PAGE, action.getId()).getContent()
.stream().sorted((e1, e2) -> Long.compare(e2.getId(), e1.getId())).collect(Collectors.toList()).get(0);
mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/"
+ MgmtRestConstants.TARGET_V1_ACTIONS + "/" + actions.get(0).getId() + "/status") + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + actions.get(0).getId() + "/status")
@@ -224,12 +225,12 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
// test - cancel the active action // test - cancel the active action
mvc.perform( mvc.perform(
delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions/{actionId}", delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions/{actionId}",
tA.getControllerId(), deploymentManagement.findActionsByTarget(tA.getControllerId(), pageReq) tA.getControllerId(), deploymentManagement.findActionsByTarget(tA.getControllerId(), PAGE)
.getContent().get(0).getId())) .getContent().get(0).getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNoContent()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isNoContent());
final Action action = deploymentManagement.findAction( final Action action = deploymentManagement.findAction(
deploymentManagement.findActionsByTarget(tA.getControllerId(), pageReq).getContent().get(0).getId()) deploymentManagement.findActionsByTarget(tA.getControllerId(), PAGE).getContent().get(0).getId())
.get(); .get();
// still active because in "canceling" state and waiting for controller // still active because in "canceling" state and waiting for controller
// feedback // feedback
@@ -250,10 +251,10 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
// cancel the active action // cancel the active action
deploymentManagement.cancelAction( deploymentManagement.cancelAction(
deploymentManagement.findActionsByTarget(tA.getControllerId(), pageReq).getContent().get(0).getId()); deploymentManagement.findActionsByTarget(tA.getControllerId(), PAGE).getContent().get(0).getId());
// find the current active action // find the current active action
final List<Action> cancelActions = deploymentManagement.findActionsByTarget(tA.getControllerId(), pageReq) final List<Action> cancelActions = deploymentManagement.findActionsByTarget(tA.getControllerId(), PAGE)
.getContent().stream().filter(Action::isCancelingOrCanceled).collect(Collectors.toList()); .getContent().stream().filter(Action::isCancelingOrCanceled).collect(Collectors.toList());
assertThat(cancelActions).hasSize(1); assertThat(cancelActions).hasSize(1);
@@ -271,10 +272,10 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
// cancel the active action // cancel the active action
deploymentManagement.cancelAction( deploymentManagement.cancelAction(
deploymentManagement.findActionsByTarget(tA.getControllerId(), pageReq).getContent().get(0).getId()); deploymentManagement.findActionsByTarget(tA.getControllerId(), PAGE).getContent().get(0).getId());
// find the current active action // find the current active action
final List<Action> cancelActions = deploymentManagement.findActionsByTarget(tA.getControllerId(), pageReq) final List<Action> cancelActions = deploymentManagement.findActionsByTarget(tA.getControllerId(), PAGE)
.getContent().stream().filter(Action::isCancelingOrCanceled).collect(Collectors.toList()); .getContent().stream().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();
@@ -294,7 +295,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
// test - cancel an cancel action returns forbidden // test - cancel an cancel action returns forbidden
mvc.perform( mvc.perform(
delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions/{actionId}?force=true", delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions/{actionId}?force=true",
tA.getControllerId(), deploymentManagement.findActionsByTarget(tA.getControllerId(), pageReq) tA.getControllerId(), deploymentManagement.findActionsByTarget(tA.getControllerId(), PAGE)
.getContent().get(0).getId())) .getContent().get(0).getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed()); .andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
} }
@@ -876,8 +877,9 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
final String knownTargetId = "targetId"; final String knownTargetId = "targetId";
final Action action = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId).get(0); final Action action = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId).get(0);
// retrieve list in default descending order for actionstaus entries // retrieve list in default descending order for actionstaus entries
final List<ActionStatus> actionStatus = action.getActionStatus().stream() final List<ActionStatus> actionStatus = deploymentManagement.findActionStatusByAction(PAGE, action.getId())
.sorted((e1, e2) -> Long.compare(e2.getId(), e1.getId())).collect(Collectors.toList()); .getContent().stream().sorted((e1, e2) -> Long.compare(e2.getId(), e1.getId()))
.collect(Collectors.toList());
// sort is default descending order, latest status first // sort is default descending order, latest status first
mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/"
@@ -902,8 +904,9 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
public void getMultipleActionStatusSortedByReportedAt() throws Exception { public void getMultipleActionStatusSortedByReportedAt() throws Exception {
final String knownTargetId = "targetId"; final String knownTargetId = "targetId";
final Action action = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId).get(0); final Action action = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId).get(0);
final List<ActionStatus> actionStatus = action.getActionStatus().stream() final List<ActionStatus> actionStatus = deploymentManagement.findActionStatusByAction(PAGE, action.getId())
.sorted((e1, e2) -> Long.compare(e1.getId(), e2.getId())).collect(Collectors.toList()); .getContent().stream().sorted((e1, e2) -> Long.compare(e1.getId(), e2.getId()))
.collect(Collectors.toList());
// descending order // descending order
mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/"
@@ -948,8 +951,9 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
final String knownTargetId = "targetId"; final String knownTargetId = "targetId";
final Action action = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId).get(0); final Action action = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId).get(0);
final List<ActionStatus> actionStatus = action.getActionStatus().stream() final List<ActionStatus> actionStatus = deploymentManagement.findActionStatusByAction(PAGE, action.getId())
.sorted((e1, e2) -> Long.compare(e1.getId(), e2.getId())).collect(Collectors.toList()); .getContent().stream().sorted((e1, e2) -> Long.compare(e1.getId(), e2.getId()))
.collect(Collectors.toList());
// Page 1 // Page 1
mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/"
@@ -1054,7 +1058,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
assignDistributionSet(two, updatedTargets); assignDistributionSet(two, updatedTargets);
// two updates, one cancellation // two updates, one cancellation
final List<Action> actions = deploymentManagement.findActionsByTarget(target.getControllerId(), pageReq) final List<Action> actions = deploymentManagement.findActionsByTarget(target.getControllerId(), PAGE)
.getContent(); .getContent();
assertThat(actions).hasSize(2); assertThat(actions).hasSize(2);
@@ -1118,7 +1122,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
.andExpect(status().isOk()); .andExpect(status().isOk());
final List<Action> findActiveActionsByTarget = deploymentManagement final List<Action> findActiveActionsByTarget = deploymentManagement
.findActiveActionsByTarget(target.getControllerId()); .findActiveActionsByTarget(PAGE, target.getControllerId()).getContent();
assertThat(findActiveActionsByTarget).hasSize(1); assertThat(findActiveActionsByTarget).hasSize(1);
assertThat(findActiveActionsByTarget.get(0).getActionType()).isEqualTo(ActionType.TIMEFORCED); assertThat(findActiveActionsByTarget.get(0).getActionType()).isEqualTo(ActionType.TIMEFORCED);
assertThat(findActiveActionsByTarget.get(0).getForcedTime()).isEqualTo(forceTime); assertThat(findActiveActionsByTarget.get(0).getForcedTime()).isEqualTo(forceTime);
@@ -1298,7 +1302,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
// assign a distribution set so we get an active update action // assign a distribution set so we get an active update action
assignDistributionSet(dsA, Lists.newArrayList(tA)); assignDistributionSet(dsA, Lists.newArrayList(tA));
// verify active action // verify active action
final Slice<Action> actionsByTarget = deploymentManagement.findActionsByTarget(tA.getControllerId(), pageReq); final Slice<Action> actionsByTarget = deploymentManagement.findActionsByTarget(tA.getControllerId(), PAGE);
assertThat(actionsByTarget.getContent()).hasSize(1); assertThat(actionsByTarget.getContent()).hasSize(1);
return targetManagement.findTargetByControllerID(tA.getControllerId()).get(); return targetManagement.findTargetByControllerID(tA.getControllerId()).get();
} }

View File

@@ -0,0 +1,318 @@
/**
* 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.mgmt.rest.resource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasSize;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.event.remote.TargetTagDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetTagCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetTagUpdatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetUpdatedEvent;
import org.eclipse.hawkbit.repository.model.Tag;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetTag;
import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.ResultActions;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
/**
* Spring MVC Tests against the MgmtTargetTagResource.
*
*/
@Features("Component Tests - Management API")
@Stories("Target Tag Resource")
public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationTest {
private static final String TARGETTAGS_ROOT = "http://localhost" + MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING
+ "/";
@Test
@Description("Verfies that a paged result list of target tags reflects the content on the repository side.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 2) })
public void getTargetTags() throws Exception {
final List<TargetTag> tags = testdataFactory.createTargetTags(2, "");
final TargetTag assigned = tags.get(0);
final TargetTag unassigned = tags.get(1);
mvc.perform(get(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(applyTagMatcherOnPagedResult(assigned)).andExpect(applyTagMatcherOnPagedResult(unassigned))
.andExpect(applySelfLinkMatcherOnPagedResult(assigned, TARGETTAGS_ROOT + assigned.getId()))
.andExpect(applySelfLinkMatcherOnPagedResult(unassigned, TARGETTAGS_ROOT + unassigned.getId()))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(2)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(2)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(2)))
.andExpect(jsonPath("$.content.[?(@.id==" + assigned.getId() + ")]._links.assignedTargets.href",
contains(TARGETTAGS_ROOT + assigned.getId() + "/assigned?offset=0&limit=50{&sort,q}")))
.andExpect(jsonPath("$.content.[?(@.id==" + unassigned.getId() + ")]._links.assignedTargets.href",
contains(TARGETTAGS_ROOT + unassigned.getId() + "/assigned?offset=0&limit=50{&sort,q}")));
}
@Test
@Description("Verfies that a single result of a target tag reflects the content on the repository side.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 2) })
public void getTargetTag() throws Exception {
final List<TargetTag> tags = testdataFactory.createTargetTags(2, "");
final TargetTag assigned = tags.get(0);
mvc.perform(get(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + assigned.getId())
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(applyTagMatcherOnSingleResult(assigned))
.andExpect(applySelfLinkMatcherOnSingleResult(TARGETTAGS_ROOT + assigned.getId()))
.andExpect(jsonPath("_links.assignedTargets.href",
equalTo(TARGETTAGS_ROOT + assigned.getId() + "/assigned?offset=0&limit=50{&sort,q}")));
}
@Test
@Description("Verifies that created target tags are stored in the repository as send to the API.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 2) })
public void createTargetTags() throws Exception {
final Tag tagOne = entityFactory.tag().create().colour("testcol1").description("its a test1").name("thetest1")
.build();
final Tag tagTwo = entityFactory.tag().create().colour("testcol2").description("its a test2").name("thetest2")
.build();
final ResultActions result = mvc
.perform(post(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING)
.content(JsonBuilder.tags(Arrays.asList(tagOne, tagTwo)))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
final Tag createdOne = tagManagement.findAllTargetTags("name==thetest1", PAGE).getContent().get(0);
assertThat(createdOne.getName()).isEqualTo(tagOne.getName());
assertThat(createdOne.getDescription()).isEqualTo(tagOne.getDescription());
assertThat(createdOne.getColour()).isEqualTo(tagOne.getColour());
final Tag createdTwo = tagManagement.findAllTargetTags("name==thetest2", PAGE).getContent().get(0);
assertThat(createdTwo.getName()).isEqualTo(tagTwo.getName());
assertThat(createdTwo.getDescription()).isEqualTo(tagTwo.getDescription());
assertThat(createdTwo.getColour()).isEqualTo(tagTwo.getColour());
result.andExpect(applyTagMatcherOnArrayResult(createdOne)).andExpect(applyTagMatcherOnArrayResult(createdTwo));
}
@Test
@Description("Verifies that an updated target tag is stored in the repository as send to the API.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 1),
@Expect(type = TargetTagUpdatedEvent.class, count = 1) })
public void updateTargetTag() throws Exception {
final List<TargetTag> tags = testdataFactory.createTargetTags(1, "");
final TargetTag original = tags.get(0);
final Tag update = entityFactory.tag().create().name("updatedName").colour("updatedCol")
.description("updatedDesc").build();
final ResultActions result = mvc
.perform(put(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + original.getId())
.content(JsonBuilder.tag(update)).contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
final Tag updated = tagManagement.findAllTargetTags("name==updatedName", PAGE).getContent().get(0);
assertThat(updated.getName()).isEqualTo(update.getName());
assertThat(updated.getDescription()).isEqualTo(update.getDescription());
assertThat(updated.getColour()).isEqualTo(update.getColour());
result.andExpect(applyTagMatcherOnArrayResult(updated)).andExpect(applyTagMatcherOnArrayResult(updated));
}
@Test
@Description("Verfies that the delete call is reflected by the repository.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 1),
@Expect(type = TargetTagDeletedEvent.class, count = 1) })
public void deleteTargetTag() throws Exception {
final List<TargetTag> tags = testdataFactory.createTargetTags(1, "");
final TargetTag original = tags.get(0);
mvc.perform(delete(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + original.getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(tagManagement.findTargetTagById(original.getId())).isNotPresent();
}
@Test
@Description("Ensures that assigned targets to tag in repository are listed with proper paging results.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 5), @Expect(type = TargetUpdatedEvent.class, count = 5) })
public void getAssignedTargets() throws Exception {
final TargetTag tag = testdataFactory.createTargetTags(1, "").get(0);
final int targetsAssigned = 5;
final List<Target> targets = testdataFactory.createTargets(targetsAssigned);
targetManagement.toggleTagAssignment(targets.stream().map(Target::getControllerId).collect(Collectors.toList()),
tag.getName());
mvc.perform(get(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(targetsAssigned)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(targetsAssigned)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(targetsAssigned)));
}
@Test
@Description("Ensures that assigned DS to tag in repository are listed with proper paging results with paging limit parameter.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 5), @Expect(type = TargetUpdatedEvent.class, count = 5) })
public void getAssignedTargetsWithPagingLimitRequestParameter() throws Exception {
final TargetTag tag = testdataFactory.createTargetTags(1, "").get(0);
final int targetsAssigned = 5;
final int limitSize = 1;
final List<Target> targets = testdataFactory.createTargets(targetsAssigned);
targetManagement.toggleTagAssignment(targets.stream().map(Target::getControllerId).collect(Collectors.toList()),
tag.getName());
mvc.perform(get(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize)))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(targetsAssigned)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize)));
}
@Test
@Description("Ensures that assigned targets to tag in repository are listed with proper paging results with paging limit and offset parameter.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 5), @Expect(type = TargetUpdatedEvent.class, count = 5) })
public void getAssignedTargetsWithPagingLimitAndOffsetRequestParameter() throws Exception {
final TargetTag tag = testdataFactory.createTargetTags(1, "").get(0);
final int targetsAssigned = 5;
final int offsetParam = 2;
final int expectedSize = targetsAssigned - offsetParam;
final List<Target> targets = testdataFactory.createTargets(targetsAssigned);
targetManagement.toggleTagAssignment(targets.stream().map(Target::getControllerId).collect(Collectors.toList()),
tag.getName());
mvc.perform(get(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam))
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(targetsAssigned)))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(targetsAssigned)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize)));
}
@Test
@Description("verfies that tag assignments done through toggle API command are correctly assigned or unassigned.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 2), @Expect(type = TargetUpdatedEvent.class, count = 4) })
public void toggleTagAssignment() throws Exception {
final TargetTag tag = testdataFactory.createTargetTags(1, "").get(0);
final int targetsAssigned = 2;
final List<Target> targets = testdataFactory.createTargets(targetsAssigned);
ResultActions result = toggle(tag, targets);
List<Target> updated = targetManagement.findTargetsByTag(PAGE, tag.getId()).getContent();
assertThat(updated.stream().map(Target::getControllerId).collect(Collectors.toList()))
.containsAll(targets.stream().map(Target::getControllerId).collect(Collectors.toList()));
result.andExpect(applyTargetEntityMatcherOnArrayResult(updated.get(0), "assignedTargets"))
.andExpect(applyTargetEntityMatcherOnArrayResult(updated.get(1), "assignedTargets"));
result = toggle(tag, targets);
updated = targetManagement.findTargetsAll(PAGE).getContent();
result.andExpect(applyTargetEntityMatcherOnArrayResult(updated.get(0), "unassignedTargets"))
.andExpect(applyTargetEntityMatcherOnArrayResult(updated.get(1), "unassignedTargets"));
assertThat(targetManagement.findTargetsByTag(PAGE, tag.getId())).isEmpty();
}
private ResultActions toggle(final TargetTag tag, final List<Target> targets) throws Exception {
return mvc
.perform(post(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId()
+ "/assigned/toggleTagAssignment")
.content(JsonBuilder.controllerIds(
targets.stream().map(Target::getControllerId).collect(Collectors.toList())))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
}
@Test
@Description("Verfies that tag assignments done through tag API command are correctly stored in the repository.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 2), @Expect(type = TargetUpdatedEvent.class, count = 2) })
public void assignTargets() throws Exception {
final TargetTag tag = testdataFactory.createTargetTags(1, "").get(0);
final int targetsAssigned = 2;
final List<Target> targets = testdataFactory.createTargets(targetsAssigned);
final ResultActions result = mvc
.perform(post(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned")
.content(JsonBuilder.controllerIds(
targets.stream().map(Target::getControllerId).collect(Collectors.toList())))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
final List<Target> updated = targetManagement.findTargetsByTag(PAGE, tag.getId()).getContent();
assertThat(updated.stream().map(Target::getControllerId).collect(Collectors.toList()))
.containsAll(targets.stream().map(Target::getControllerId).collect(Collectors.toList()));
result.andExpect(applyTargetEntityMatcherOnArrayResult(updated.get(0)))
.andExpect(applyTargetEntityMatcherOnArrayResult(updated.get(1)));
}
@Test
@Description("Verfies that tag unassignments done through tag API command are correctly stored in the repository.")
@ExpectEvents({ @Expect(type = TargetTagCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 2), @Expect(type = TargetUpdatedEvent.class, count = 3) })
public void unassignTarget() throws Exception {
final TargetTag tag = testdataFactory.createTargetTags(1, "").get(0);
final int targetsAssigned = 2;
final List<Target> targets = testdataFactory.createTargets(targetsAssigned);
final Target assigned = targets.get(0);
final Target unassigned = targets.get(1);
targetManagement.toggleTagAssignment(targets.stream().map(Target::getControllerId).collect(Collectors.toList()),
tag.getName());
mvc.perform(delete(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING + "/" + tag.getId() + "/assigned/"
+ unassigned.getControllerId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
final List<Target> updated = targetManagement.findTargetsByTag(PAGE, tag.getId()).getContent();
assertThat(updated.stream().map(Target::getControllerId).collect(Collectors.toList()))
.containsOnly(assigned.getControllerId());
}
}

View File

@@ -9,8 +9,8 @@
package org.eclipse.hawkbit.repository; package org.eclipse.hawkbit.repository;
import java.util.Collection; import java.util.Collection;
import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Collectors;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
@@ -24,7 +24,6 @@ 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;
import org.eclipse.hawkbit.repository.model.ActionStatus; import org.eclipse.hawkbit.repository.model.ActionStatus;
import org.eclipse.hawkbit.repository.model.ActionWithStatusCount;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetAssignmentResult; import org.eclipse.hawkbit.repository.model.DistributionSetAssignmentResult;
import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.DistributionSetType;
@@ -71,6 +70,7 @@ public interface DeploymentManagement {
DistributionSetAssignmentResult assignDistributionSet(@NotNull Long dsID, @NotNull ActionType actionType, DistributionSetAssignmentResult assignDistributionSet(@NotNull Long dsID, @NotNull ActionType actionType,
long forcedTimestamp, @NotEmpty Collection<String> controllerIDs); 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
* their IDs with a specific {@link ActionType} and {@code forcetime}. * their IDs with a specific {@link ActionType} and {@code forcetime}.
@@ -274,22 +274,6 @@ public interface DeploymentManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<ActionStatus> findActionStatusByAction(@NotNull Pageable pageReq, @NotNull Long actionId); Page<ActionStatus> findActionStatusByAction(@NotNull Pageable pageReq, @NotNull Long actionId);
/**
* Retrieves all {@link ActionStatus} inclusive their messages by a specific
* {@link Action}.
*
* @param pageable
* the page request parameter for paging and sorting the result
* @param actionId
* the {@link Action} to retrieve the {@link ActionStatus} from
* @return a page of {@link ActionStatus} by a speciifc {@link Action}
*
* @throws EntityNotFoundException
* if action with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<ActionStatus> findActionStatusByActionWithMessages(@NotNull Pageable pageable, @NotNull Long actionId);
/** /**
* Retrieves all messages for an {@link ActionStatus}. * Retrieves all messages for an {@link ActionStatus}.
* *
@@ -303,20 +287,6 @@ public interface DeploymentManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<String> findMessagesByActionStatusId(@NotNull Pageable pageable, @NotNull Long actionStatusId); Page<String> findMessagesByActionStatusId(@NotNull Pageable pageable, @NotNull Long actionStatusId);
/**
* Retrieves all {@link Action}s of a specific target ordered by action ID.
*
* @param controllerId
* the target associated with the actions
* @return a list of actions associated with the given target ordered by
* action ID
*
* @throws EntityNotFoundException
* if target with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
List<ActionWithStatusCount> findActionsWithStatusCountByTargetOrderByIdDesc(@NotNull String controllerId);
/** /**
* Get the {@link Action} entity for given actionId with all lazy attributes * Get the {@link Action} entity for given actionId with all lazy attributes
* (i.e. distributionSet, target, target.assignedDs). * (i.e. distributionSet, target, target.assignedDs).
@@ -331,7 +301,9 @@ public interface DeploymentManagement {
/** /**
* 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.
* *
* @param pageable
* the page request parameter for paging and sorting the result
* @param controllerId * @param controllerId
* the target associated with the actions * the target associated with the actions
* @return a list of actions associated with the given target * @return a list of actions associated with the given target
@@ -340,12 +312,14 @@ public interface DeploymentManagement {
* if target with given ID does not exist * if target with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
List<Action> findActiveActionsByTarget(@NotEmpty String controllerId); Page<Action> findActiveActionsByTarget(@NotNull Pageable pageable, @NotEmpty String controllerId);
/** /**
* 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.
* *
* @param pageable
* the page request parameter for paging and sorting the result
* @param controllerId * @param controllerId
* the target associated with the actions * the target associated with the actions
* @return a list of actions associated with the given target * @return a list of actions associated with the given target
@@ -354,7 +328,7 @@ public interface DeploymentManagement {
* if target with given ID does not exist * if target with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
List<Action> findInActiveActionsByTarget(@NotEmpty String controllerId); Page<Action> findInActiveActionsByTarget(@NotNull Pageable pageable, @NotEmpty String controllerId);
/** /**
* Force cancels given {@link Action} for given {@link Target}. Force * Force cancels given {@link Action} for given {@link Target}. Force

View File

@@ -363,17 +363,6 @@ public interface DistributionSetManagement {
Page<DistributionSetMetadata> findDistributionSetMetadataByDistributionSetId(@NotNull Long distributionSetId, Page<DistributionSetMetadata> findDistributionSetMetadataByDistributionSetId(@NotNull Long distributionSetId,
@NotNull String rsqlParam, @NotNull Pageable pageable); @NotNull String rsqlParam, @NotNull Pageable pageable);
/**
* Retrieves {@link DistributionSet} List for overview purposes (no
* {@link SoftwareModule}s and {@link DistributionSetTag}s).
*
* @param dist
* List of {@link DistributionSet} IDs to be found
* @return the found {@link DistributionSet}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
List<DistributionSet> findDistributionSetsAll(Collection<Long> dist);
/** /**
* finds all {@link DistributionSet}s. * finds all {@link DistributionSet}s.
* *
@@ -420,6 +409,21 @@ public interface DistributionSetManagement {
Page<DistributionSet> findDistributionSetsAll(@NotNull String rsqlParam, @NotNull Pageable pageReq, Page<DistributionSet> findDistributionSetsAll(@NotNull String rsqlParam, @NotNull Pageable pageReq,
Boolean deleted); Boolean deleted);
/**
* finds all {@link DistributionSet}s.
*
* @param pageReq
* the pagination parameter
* @param deleted
* if TRUE, {@link DistributionSet}s marked as deleted are
* returned. If FALSE, on {@link DistributionSet}s not marked as
* deleted are returned. <code>null</code> if both are to be
* returned
* @return all found {@link DistributionSet}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSet> findDistributionSetsAll(@NotNull Pageable pageReq, Boolean deleted);
/** /**
* method retrieves all {@link DistributionSet}s from the repository in the * method retrieves all {@link DistributionSet}s from the repository in the
* following order: * following order:
@@ -458,6 +462,45 @@ public interface DistributionSetManagement {
Page<DistributionSet> findDistributionSetsByFilters(@NotNull Pageable pageable, Page<DistributionSet> findDistributionSetsByFilters(@NotNull Pageable pageable,
@NotNull DistributionSetFilter distributionSetFilter); @NotNull DistributionSetFilter distributionSetFilter);
/**
* retrieves {@link DistributionSet}s by filtering on the given parameters.
*
* @param pageable
* page parameter
* @param tagId
* of the tag the DS are assigned to
* @return the page of found {@link DistributionSet}
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*
* @throws EntityNotFoundException
* of distribution set tag with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSet> findDistributionSetsByTag(@NotNull final Pageable pageable, @NotNull final Long tagId);
/**
* retrieves {@link DistributionSet}s by filtering on the given parameters.
*
* @param pageable
* page parameter
* @param rsqlParam
* rsql query string
* @param tagId
* of the tag the DS are assigned to
* @return the page of found {@link DistributionSet}
*
* @throws EntityNotFoundException
* of distribution set tag with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSet> findDistributionSetsByTag(@NotNull final Pageable pageable, @NotNull String rsqlParam,
@NotNull final Long tagId);
/** /**
* @param id * @param id
* as {@link DistributionSetType#getId()} * as {@link DistributionSetType#getId()}
@@ -556,20 +599,6 @@ public interface DistributionSetManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetTagAssignmentResult toggleTagAssignment(@NotEmpty Collection<Long> dsIds, @NotNull String tagName); DistributionSetTagAssignmentResult toggleTagAssignment(@NotEmpty Collection<Long> dsIds, @NotNull String tagName);
/**
* Unassign all {@link DistributionSet} from a given
* {@link DistributionSetTag} .
*
* @param tagId
* to unassign all ds
* @return list of unassigned ds
*
* @throws EntityNotFoundException
* if tag with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
List<DistributionSet> unAssignAllDistributionSetsByTag(@NotNull Long tagId);
/** /**
* Unassigns a {@link SoftwareModule} form an existing * Unassigns a {@link SoftwareModule} form an existing
* {@link DistributionSet}. * {@link DistributionSet}.
@@ -731,6 +760,6 @@ public interface DistributionSetManagement {
* @return the found {@link DistributionSet}s * @return the found {@link DistributionSet}s
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
List<DistributionSet> findDistributionSetAllById(@NotEmpty Collection<Long> ids); List<DistributionSet> findDistributionSetsById(@NotEmpty Collection<Long> ids);
} }

View File

@@ -0,0 +1,39 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.ActionStatus;
import org.eclipse.hawkbit.repository.model.Rollout;
import org.eclipse.hawkbit.repository.model.RolloutGroup;
/**
* Central service for defined limits of the repository.
*
*/
public interface QuotaManagement {
/**
* @return Maximum number of {@link ActionStatus} entries that the
* controller can report for an {@link Action}.
*/
int getMaxStatusEntriesPerAction();
/**
* @return maximum number of attributes that the controller can report;
*/
int getMaxAttributeEntriesPerTarget();
/**
* @return maximum number of allowed {@link RolloutGroup}s per
* {@link Rollout}.
*/
int getMaxRolloutGroupsPerRollout();
}

View File

@@ -82,7 +82,7 @@ public interface RolloutGroupManagement {
* Retrieves a page of {@link RolloutGroup}s filtered by a given * Retrieves a page of {@link RolloutGroup}s filtered by a given
* {@link Rollout} and the an rsql filter. * {@link Rollout} and the an rsql filter.
* *
* @param rollout * @param rolloutId
* the rollout to filter the {@link RolloutGroup}s * the rollout to filter the {@link RolloutGroup}s
* @param rsqlParam * @param rsqlParam
* the specification to filter the result set based on attributes * the specification to filter the result set based on attributes
@@ -98,7 +98,7 @@ public interface RolloutGroupManagement {
* if the RSQL syntax is wrong * if the RSQL syntax is wrong
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
Page<RolloutGroup> findRolloutGroupsAll(@NotNull Long rollout, @NotNull String rsqlParam, Page<RolloutGroup> findRolloutGroupsAll(@NotNull Long rolloutId, @NotNull String rsqlParam,
@NotNull Pageable pageable); @NotNull Pageable pageable);
/** /**
@@ -114,6 +114,19 @@ public interface RolloutGroupManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
Page<RolloutGroup> findRolloutGroupsByRolloutId(@NotNull Long rolloutId, @NotNull Pageable pageable); Page<RolloutGroup> findRolloutGroupsByRolloutId(@NotNull Long rolloutId, @NotNull Pageable pageable);
/**
* Retrieves a page of {@link RolloutGroup}s filtered by a given
* {@link Rollout}.
*
* @param rolloutId
* the ID of the rollout to filter the {@link RolloutGroup}s
* @param pageable
* the page request to sort and limit the result
* @return a page of found {@link RolloutGroup}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
long countRolloutGroupsByRolloutId(@NotNull Long rolloutId);
/** /**
* Get targets of specified rollout group. * Get targets of specified rollout group.
* *

View File

@@ -334,6 +334,23 @@ public interface SoftwareManagement {
Page<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(@NotNull Long moduleId, Page<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(@NotNull Long moduleId,
@NotNull String rsqlParam, @NotNull Pageable pageable); @NotNull String rsqlParam, @NotNull Pageable pageable);
/**
* Finds all meta data by the given software module id.
*
* @param pageable
* pagination parameter
*
* @param moduleId
* the software module id to retrieve the meta data from
* @return page with found software module metadata
*
* @throws EntityNotFoundException
* of software module with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(@NotNull Pageable pageable,
@NotNull Long moduleId);
/** /**
* Filter {@link SoftwareModule}s with given * Filter {@link SoftwareModule}s with given
* {@link SoftwareModule#getName()} or {@link SoftwareModule#getVersion()} * {@link SoftwareModule#getName()} or {@link SoftwareModule#getVersion()}
@@ -522,25 +539,4 @@ public interface SoftwareManagement {
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
SoftwareModuleType updateSoftwareModuleType(@NotNull SoftwareModuleTypeUpdate update); SoftwareModuleType updateSoftwareModuleType(@NotNull SoftwareModuleTypeUpdate update);
/**
* Finds all meta data by the given software module id.
*
* @param moduleId
* the software module id to retrieve the meta data from
*
*
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
* @return result of all meta data entries for a given software module id.
*
* @throws EntityNotFoundException
* of software module with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
List<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(@NotNull Long moduleId);
} }

View File

@@ -8,7 +8,7 @@
*/ */
package org.eclipse.hawkbit.repository; package org.eclipse.hawkbit.repository;
import java.util.List; import java.util.function.Consumer;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
@@ -18,6 +18,8 @@ import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.model.TenantMetaData; import org.eclipse.hawkbit.repository.model.TenantMetaData;
import org.eclipse.hawkbit.repository.report.model.SystemUsageReport; import org.eclipse.hawkbit.repository.report.model.SystemUsageReport;
import org.eclipse.hawkbit.tenancy.TenantAware; import org.eclipse.hawkbit.tenancy.TenantAware;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
/** /**
@@ -44,10 +46,22 @@ public interface SystemManagement {
/** /**
* *
* @param pageable
* for paging information
* @return list of all tenant names in the system. * @return list of all tenant names in the system.
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_SYSTEM_ADMIN) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_SYSTEM_ADMIN)
List<String> findTenants(); Page<String> findTenants(@NotNull Pageable pageable);
/**
* Runs consumer for each teant as
* {@link TenantAware#runAsTenant(String, org.eclipse.hawkbit.tenancy.TenantAware.TenantRunner)}
*
* @param consumer
* to run as teanant
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_SYSTEM_ADMIN)
void forEachTenant(Consumer<String> consumer);
/** /**
* Calculated system usage statistics, both overall for the entire system * Calculated system usage statistics, both overall for the entire system

View File

@@ -122,13 +122,6 @@ public interface TagManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_TARGET)
void deleteTargetTag(@NotEmpty String targetTagName); void deleteTargetTag(@NotEmpty String targetTagName);
/**
*
* @return all {@link DistributionSetTag}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
List<DistributionSetTag> findAllDistributionSetTags();
/** /**
* returns all {@link DistributionSetTag}s. * returns all {@link DistributionSetTag}s.
* *
@@ -241,6 +234,22 @@ public interface TagManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Optional<TargetTag> findTargetTagById(@NotNull Long id); Optional<TargetTag> findTargetTagById(@NotNull Long id);
/**
* Finds all {@link TargetTag} assigned to given {@link Target}.
*
* @param pageable
* information for page size, offset and sort order.
*
* @param setId
* of the {@link DistributionSet}
* @return page of the found {@link TargetTag}s
*
* @throws EntityNotFoundException
* if {@link DistributionSet} with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page<DistributionSetTag> findDistributionSetTagsByDistributionSet(@NotNull Pageable pageable, @NotNull Long setId);
/** /**
* Updates an existing {@link DistributionSetTag}. * Updates an existing {@link DistributionSetTag}.
* *

View File

@@ -339,7 +339,7 @@ public interface TargetManagement {
* @return List of found{@link Target}s * @return List of found{@link Target}s
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
List<Target> findTargetByControllerID(@NotEmpty Collection<String> controllerIDs); List<Target> findTargetsByControllerID(@NotEmpty Collection<String> controllerIDs);
/** /**
* Find a {@link Target} based a given ID. * Find a {@link Target} based a given ID.
@@ -533,13 +533,41 @@ public interface TargetManagement {
/** /**
* Find targets by tag name. * Find targets by tag name.
* *
* @param tagName * @param pageable
* tag name * the page request parameter for paging and sorting the result
* @param tagId
* tag ID
* @return list of matching targets * @return list of matching targets
*
* @throws EntityNotFoundException
* if target tag with given ID does not exist
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
List<Target> findTargetsByTag(@NotEmpty String tagName); Page<Target> findTargetsByTag(@NotNull Pageable pageable, @NotNull Long tagId);
/**
* Find targets by tag name.
*
* @param pageable
* the page request parameter for paging and sorting the result
* @param tagId
* tag ID
* @param rsqlParam
* in RSQL notation
*
* @return list of matching targets
*
* @throws EntityNotFoundException
* if target tag with given ID does not exist
* @throws RSQLParameterUnsupportedFieldException
* if a field in the RSQL string is used but not provided by the
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page<Target> findTargetsByTag(@NotNull Pageable pageable, @NotNull String rsqlParam, @NotNull Long tagId);
/** /**
* Toggles {@link TargetTag} assignment to given {@link Target}s by means * Toggles {@link TargetTag} assignment to given {@link Target}s by means
@@ -559,19 +587,6 @@ public interface TargetManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET)
TargetTagAssignmentResult toggleTagAssignment(@NotEmpty Collection<String> controllerIds, @NotEmpty String tagName); TargetTagAssignmentResult toggleTagAssignment(@NotEmpty Collection<String> controllerIds, @NotEmpty String tagName);
/**
* Un-assign all {@link Target} from a given {@link TargetTag} .
*
* @param targetTagId
* to un-assign all targets
* @return list of unassigned targets
*
* @throws EntityNotFoundException
* if TAG with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET)
List<Target> unAssignAllTargetsByTag(@NotNull Long targetTagId);
/** /**
* Un-assign a {@link TargetTag} assignment to given {@link Target}. * Un-assign a {@link TargetTag} assignment to given {@link Target}.
* *
@@ -623,7 +638,7 @@ public interface TargetManagement {
* @return the found {@link Target}s * @return the found {@link Target}s
*/ */
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
List<Target> findTargetAllById(@NotNull Collection<Long> ids); List<Target> findTargetsById(@NotNull Collection<Long> ids);
/** /**
* Get controller attributes of given {@link Target}. * Get controller attributes of given {@link Target}.

View File

@@ -14,14 +14,14 @@ import org.eclipse.hawkbit.repository.model.DistributionSetTag;
* Defines the remote event for update a {@link DistributionSetTag}. * Defines the remote event for update a {@link DistributionSetTag}.
* *
*/ */
public class DistributionSetTagUpdateEvent extends RemoteEntityEvent<DistributionSetTag> { public class DistributionSetTagUpdatedEvent extends RemoteEntityEvent<DistributionSetTag> {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** /**
* Default constructor. * Default constructor.
*/ */
public DistributionSetTagUpdateEvent() { public DistributionSetTagUpdatedEvent() {
// for serialization libs like jackson // for serialization libs like jackson
} }
@@ -33,7 +33,7 @@ public class DistributionSetTagUpdateEvent extends RemoteEntityEvent<Distributio
* @param applicationId * @param applicationId
* the applicationID * the applicationID
*/ */
public DistributionSetTagUpdateEvent(final DistributionSetTag tag, final String applicationId) { public DistributionSetTagUpdatedEvent(final DistributionSetTag tag, final String applicationId) {
super(tag, applicationId); super(tag, applicationId);
} }
} }

View File

@@ -14,14 +14,14 @@ import org.eclipse.hawkbit.repository.model.DistributionSet;
* Defines the remote event for updating a {@link DistributionSet}. * Defines the remote event for updating a {@link DistributionSet}.
* *
*/ */
public class DistributionSetUpdateEvent extends RemoteEntityEvent<DistributionSet> { public class DistributionSetUpdatedEvent extends RemoteEntityEvent<DistributionSet> {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** /**
* Default constructor. * Default constructor.
*/ */
public DistributionSetUpdateEvent() { public DistributionSetUpdatedEvent() {
// for serialization libs like jackson // for serialization libs like jackson
} }
@@ -33,7 +33,7 @@ public class DistributionSetUpdateEvent extends RemoteEntityEvent<DistributionSe
* @param applicationId * @param applicationId
* the origin application id * the origin application id
*/ */
public DistributionSetUpdateEvent(final DistributionSet ds, final String applicationId) { public DistributionSetUpdatedEvent(final DistributionSet ds, final String applicationId) {
super(ds, applicationId); super(ds, applicationId);
} }
} }

View File

@@ -14,14 +14,14 @@ import org.eclipse.hawkbit.repository.model.TargetTag;
* Defines the remote event for updating a {@link TargetTag}. * Defines the remote event for updating a {@link TargetTag}.
* *
*/ */
public class TargetTagUpdateEvent extends RemoteEntityEvent<TargetTag> { public class TargetTagUpdatedEvent extends RemoteEntityEvent<TargetTag> {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** /**
* Default constructor. * Default constructor.
*/ */
public TargetTagUpdateEvent() { public TargetTagUpdatedEvent() {
// for serialization libs like jackson // for serialization libs like jackson
} }
@@ -33,7 +33,7 @@ public class TargetTagUpdateEvent extends RemoteEntityEvent<TargetTag> {
* @param applicationId * @param applicationId
* the origin application id * the origin application id
*/ */
public TargetTagUpdateEvent(final TargetTag tag, final String applicationId) { public TargetTagUpdatedEvent(final TargetTag tag, final String applicationId) {
super(tag, applicationId); super(tag, applicationId);
} }
} }

View File

@@ -8,7 +8,6 @@
*/ */
package org.eclipse.hawkbit.repository.model; package org.eclipse.hawkbit.repository.model;
import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**
@@ -45,11 +44,6 @@ public interface Action extends TenantAwareBaseEntity {
*/ */
ActionType getActionType(); ActionType getActionType();
/**
* @return list of {@link ActionStatus} entries.
*/
List<ActionStatus> getActionStatus();
/** /**
* @return {@link Target} of this {@link Action}. * @return {@link Target} of this {@link Action}.
*/ */

View File

@@ -8,7 +8,6 @@
*/ */
package org.eclipse.hawkbit.repository.model; package org.eclipse.hawkbit.repository.model;
import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.Action.Status;
@@ -28,12 +27,6 @@ public interface ActionStatus extends TenantAwareBaseEntity {
*/ */
Long getOccurredAt(); Long getOccurredAt();
/**
* @return immutable list of message entries that in the
* {@link ActionStatus}.
*/
List<String> getMessages();
/** /**
* @return {@link Action} this {@link ActionStatus} belongs to. * @return {@link Action} this {@link ActionStatus} belongs to.
*/ */

View File

@@ -1,48 +0,0 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository.model;
/**
* View for querying {@link Action} include the count of the action's
* {@link ActionStatus} entries.
*
*/
public interface ActionWithStatusCount {
/**
* @return {@link Action}
*/
Action getAction();
/**
* @return {@link DistributionSet} ID.
*/
Long getDsId();
/**
* @return {@link DistributionSet} name.
*/
String getDsName();
/**
* @return {@link DistributionSet} version.
*/
String getDsVersion();
/**
* @return number of {@link ActionStatus} entries
*/
Long getActionStatusCount();
/**
* @return name of the {@link Rollout}.
*/
String getRolloutName();
}

View File

@@ -24,11 +24,6 @@ import java.util.Set;
*/ */
public interface DistributionSet extends NamedVersionedEntity { public interface DistributionSet extends NamedVersionedEntity {
/**
* @return immutable {@link Set} of assigned {@link DistributionSetTag}s.
*/
Set<DistributionSetTag> getTags();
/** /**
* @return <code>true</code> if the set is deleted and only kept for history * @return <code>true</code> if the set is deleted and only kept for history
* purposes. * purposes.

View File

@@ -69,7 +69,7 @@ public class DistributionSetAssignmentResult extends AssignmentResult<Target> {
return Collections.emptyList(); return Collections.emptyList();
} }
return targetManagement.findTargetByControllerID(assignedTargets); return targetManagement.findTargetsByControllerID(assignedTargets);
} }
} }

View File

@@ -15,11 +15,7 @@ import java.util.Collection;
*/ */
public final class DistributionSetFilter { public final class DistributionSetFilter {
/** /**
*
* Distribution set filter builder. * Distribution set filter builder.
*
*
*
*/ */
public static class DistributionSetFilterBuilder { public static class DistributionSetFilterBuilder {
private Boolean isDeleted; private Boolean isDeleted;
@@ -81,6 +77,7 @@ public final class DistributionSetFilter {
} }
} }
private final Boolean isDeleted; private final Boolean isDeleted;
private final Boolean isComplete; private final Boolean isComplete;
private final DistributionSetType type; private final DistributionSetType type;

View File

@@ -8,18 +8,10 @@
*/ */
package org.eclipse.hawkbit.repository.model; package org.eclipse.hawkbit.repository.model;
import java.util.List;
/** /**
* {@link Tag} of a {@link DistributionSet}. * {@link Tag} of a {@link DistributionSet}.
* *
*/ */
public interface DistributionSetTag extends Tag { public interface DistributionSetTag extends Tag {
/**
* @return immutable {@link List} of {@link DistributionSet}s this
* {@link Tag} is assigned to.
*/
List<DistributionSet> getAssignedToDistributionSet();
} }

View File

@@ -8,7 +8,6 @@
*/ */
package org.eclipse.hawkbit.repository.model; package org.eclipse.hawkbit.repository.model;
import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.eclipse.hawkbit.repository.model.Action.ActionType; import org.eclipse.hawkbit.repository.model.Action.ActionType;
@@ -37,11 +36,6 @@ public interface Rollout extends NamedEntity {
*/ */
DistributionSet getDistributionSet(); DistributionSet getDistributionSet();
/**
* @return immutable list of deployment groups of the rollout.
*/
List<RolloutGroup> getRolloutGroups();
/** /**
* @return rsql query that identifies the targets that are part of this * @return rsql query that identifies the targets that are part of this
* rollout. * rollout.

View File

@@ -8,17 +8,10 @@
*/ */
package org.eclipse.hawkbit.repository.model; package org.eclipse.hawkbit.repository.model;
import java.util.List;
/** /**
* Target tag element. * Target tag element.
* *
*/ */
public interface TargetTag extends Tag { public interface TargetTag extends Tag {
/**
* @return immutable {@link List} of targets assigned to this {@link Tag}.
*/
List<Target> getAssignedToTargets();
} }

View File

@@ -26,8 +26,8 @@ import org.eclipse.hawkbit.repository.event.remote.entity.ActionUpdatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.CancelTargetAssignmentEvent; import org.eclipse.hawkbit.repository.event.remote.entity.CancelTargetAssignmentEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetCreatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetTagCreatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetTagCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetTagUpdateEvent; import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetTagUpdatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetUpdateEvent; import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetUpdatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.RolloutGroupCreatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.RolloutGroupCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.RolloutGroupUpdatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.RolloutGroupUpdatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.RolloutUpdatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.RolloutUpdatedEvent;
@@ -35,7 +35,7 @@ import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleCreatedE
import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleUpdatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleUpdatedEvent;
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.TargetTagCreatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.TargetTagCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetTagUpdateEvent; import org.eclipse.hawkbit.repository.event.remote.entity.TargetTagUpdatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetUpdatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.TargetUpdatedEvent;
/** /**
@@ -66,7 +66,7 @@ public class EventType {
// target tag // target tag
TYPES.put(6, TargetTagCreatedEvent.class); TYPES.put(6, TargetTagCreatedEvent.class);
TYPES.put(7, TargetTagUpdateEvent.class); TYPES.put(7, TargetTagUpdatedEvent.class);
TYPES.put(8, TargetTagDeletedEvent.class); TYPES.put(8, TargetTagDeletedEvent.class);
// action // action
@@ -75,12 +75,12 @@ public class EventType {
// distribution set // distribution set
TYPES.put(11, DistributionSetCreatedEvent.class); TYPES.put(11, DistributionSetCreatedEvent.class);
TYPES.put(12, DistributionSetUpdateEvent.class); TYPES.put(12, DistributionSetUpdatedEvent.class);
TYPES.put(13, DistributionSetDeletedEvent.class); TYPES.put(13, DistributionSetDeletedEvent.class);
// distribution set tag // distribution set tag
TYPES.put(14, DistributionSetTagCreatedEvent.class); TYPES.put(14, DistributionSetTagCreatedEvent.class);
TYPES.put(15, DistributionSetTagUpdateEvent.class); TYPES.put(15, DistributionSetTagUpdatedEvent.class);
TYPES.put(16, DistributionSetTagDeletedEvent.class); TYPES.put(16, DistributionSetTagDeletedEvent.class);
// rollout // rollout

View File

@@ -0,0 +1,46 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository;
import org.eclipse.hawkbit.security.HawkbitSecurityProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* {@link QuotaManagement} implementation based on spring boot
* {@link ConfigurationProperties}.
*
*/
public class PropertiesQuotaManagement implements QuotaManagement {
private final HawkbitSecurityProperties securityProperties;
/**
* @param securityProperties
* that holds the quota definitions
*/
public PropertiesQuotaManagement(final HawkbitSecurityProperties securityProperties) {
this.securityProperties = securityProperties;
}
@Override
public int getMaxStatusEntriesPerAction() {
return securityProperties.getDos().getMaxStatusEntriesPerAction();
}
@Override
public int getMaxAttributeEntriesPerTarget() {
return securityProperties.getDos().getMaxAttributeEntriesPerTarget();
}
@Override
public int getMaxRolloutGroupsPerRollout() {
return securityProperties.getDos().getMaxRolloutGroupsPerRollout();
}
}

View File

@@ -23,6 +23,7 @@ import org.eclipse.hawkbit.repository.model.RolloutGroupConditions;
* A collection of static helper methods for the {@link RolloutManagement} * A collection of static helper methods for the {@link RolloutManagement}
*/ */
public final class RolloutHelper { public final class RolloutHelper {
private RolloutHelper() { private RolloutHelper() {
} }
@@ -68,12 +69,14 @@ public final class RolloutHelper {
* *
* @param amountGroup * @param amountGroup
* amount of groups * amount of groups
* @param quotaManagement
* to retrieve maximum number of groups allowed
*/ */
public static void verifyRolloutGroupParameter(final int amountGroup) { public static void verifyRolloutGroupParameter(final int amountGroup, final QuotaManagement quotaManagement) {
if (amountGroup <= 0) { if (amountGroup <= 0) {
throw new ConstraintViolationException("the amountGroup must be greater than zero"); throw new ConstraintViolationException("the amount of groups cannot be lower than zero");
} else if (amountGroup > 500) { } else if (amountGroup > quotaManagement.getMaxRolloutGroupsPerRollout()) {
throw new ConstraintViolationException("the amountGroup must not be greater than 500"); throw new ConstraintViolationException("the amount of groups cannot be greater than 500");
} }
} }
@@ -144,32 +147,12 @@ public final class RolloutHelper {
* the group to add * the group to add
* @return list of groups * @return list of groups
*/ */
public static List<Long> getGroupsByStatusIncludingGroup(final Rollout rollout, public static List<Long> getGroupsByStatusIncludingGroup(final List<RolloutGroup> groups,
final RolloutGroup.RolloutGroupStatus status, final RolloutGroup group) { final RolloutGroup.RolloutGroupStatus status, final RolloutGroup group) {
return rollout.getRolloutGroups().stream() return groups.stream().filter(innerGroup -> innerGroup.getStatus().equals(status) || innerGroup.equals(group))
.filter(innerGroup -> innerGroup.getStatus().equals(status) || innerGroup.equals(group))
.map(RolloutGroup::getId).collect(Collectors.toList()); .map(RolloutGroup::getId).collect(Collectors.toList());
} }
/**
* Returns the groups of a rollout by their Ids order
*
* @param rollout
* the rollout
* @return ordered list of groups
*/
public static List<RolloutGroup> getOrderedGroups(final Rollout rollout) {
return rollout.getRolloutGroups().stream().sorted((group1, group2) -> {
if (group1.getId() < group2.getId()) {
return -1;
}
if (group1.getId() > group2.getId()) {
return 1;
}
return 0;
}).collect(Collectors.toList());
}
/** /**
* Creates an RSQL expression that matches all targets in the provided * Creates an RSQL expression that matches all targets in the provided
* groups. Links all target filter queries with OR. * groups. Links all target filter queries with OR.

View File

@@ -8,10 +8,10 @@
*/ */
package org.eclipse.hawkbit.repository.builder; package org.eclipse.hawkbit.repository.builder;
import org.eclipse.hawkbit.repository.model.Action.ActionType;
import java.util.Optional; import java.util.Optional;
import org.eclipse.hawkbit.repository.model.Action.ActionType;
/** /**
* Create and update builder DTO. * Create and update builder DTO.
* *

View File

@@ -172,7 +172,8 @@ public interface ActionRepository extends BaseEntityRepository<JpaAction, Long>,
*/ */
@EntityGraph(value = "Action.ds", type = EntityGraphType.LOAD) @EntityGraph(value = "Action.ds", type = EntityGraphType.LOAD)
@Query("Select a from JpaAction a where a.target.controllerId = :target and a.active= :active order by a.id") @Query("Select a from JpaAction a where a.target.controllerId = :target and a.active= :active order by a.id")
List<Action> findByActiveAndTarget(@Param("target") String target, @Param("active") boolean active); Page<Action> findByActiveAndTarget(Pageable pageable, @Param("target") String target,
@Param("active") boolean active);
/** /**
* Switches the status of actions from one specific status into another, * Switches the status of actions from one specific status into another,

View File

@@ -17,11 +17,12 @@ import javax.persistence.EntityManager;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
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.DistributionSetTag;
import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.Rollout;
import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.Tag; import org.eclipse.hawkbit.repository.model.Tag;
import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity; import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
@@ -38,13 +39,29 @@ public interface DistributionSetRepository
/** /**
* Finds {@link DistributionSet}s by assigned {@link Tag}. * Finds {@link DistributionSet}s by assigned {@link Tag}.
*
* @param pageable
* paging and sorting information
* *
* @param tag * @param tagId
* to be found * to be found
* @return list of found {@link DistributionSet}s * @return list of found {@link DistributionSet}s
*/ */
@Query(value = "Select Distinct ds from JpaDistributionSet ds join ds.tags dst where dst = :tag") @Query(value = "Select Distinct ds from JpaDistributionSet ds join ds.tags dst where dst.id = :tag")
List<JpaDistributionSet> findByTag(@Param("tag") final DistributionSetTag tag); Page<JpaDistributionSet> findByTag(Pageable pageable, @Param("tag") final Long tagId);
/**
* Finds {@link DistributionSet}s by assigned {@link Tag}.
*
* @param pageable
* paging and sorting information
*
* @param tagId
* to be found
* @return page of found {@link DistributionSet}s
*/
@Query(value = "Select Distinct ds from JpaDistributionSet ds join ds.tags dst where dst.id = :tagId")
Page<JpaDistributionSet> findByTagId(Pageable pageable, @Param("tagId") final Long tagId);
/** /**
* deletes the {@link DistributionSet}s with the given IDs. * deletes the {@link DistributionSet}s with the given IDs.
@@ -147,9 +164,9 @@ public interface DistributionSetRepository
/** /**
* Deletes all {@link TenantAwareBaseEntity} of a given tenant. For safety * Deletes all {@link TenantAwareBaseEntity} of a given tenant. For safety
* reasons (this is a "delete everything" query after all) we add the tenant manually to * reasons (this is a "delete everything" query after all) we add the tenant
* query even if this will by done by {@link EntityManager} anyhow. The DB * manually to query even if this will by done by {@link EntityManager}
* should take care of optimizing this away. * anyhow. The DB should take care of optimizing this away.
* *
* @param tenant * @param tenant
* to delete data from * to delete data from

View File

@@ -51,6 +51,16 @@ public interface DistributionSetTagRepository
*/ */
Optional<DistributionSetTag> findByNameEquals(final String tagName); Optional<DistributionSetTag> findByNameEquals(final String tagName);
/**
* Checks if tag with given name exists.
*
* @param tagName
* to check for
* @return <code>true</code> is tag with given name exists
*/
@Query("SELECT CASE WHEN COUNT(t)>0 THEN 'true' ELSE 'false' END FROM JpaDistributionSetTag t WHERE t.name=:tagName")
boolean existsByName(@Param("tagName") String tagName);
/** /**
* Returns all instances of the type. * Returns all instances of the type.
* *

View File

@@ -20,6 +20,7 @@ import javax.persistence.criteria.Root;
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.QuotaManagement;
import org.eclipse.hawkbit.repository.RepositoryConstants; import org.eclipse.hawkbit.repository.RepositoryConstants;
import org.eclipse.hawkbit.repository.RepositoryProperties; import org.eclipse.hawkbit.repository.RepositoryProperties;
import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.TargetManagement;
@@ -47,7 +48,6 @@ import org.eclipse.hawkbit.repository.model.ActionStatus;
import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.security.HawkbitSecurityProperties;
import org.eclipse.hawkbit.security.SystemSecurityContext; import org.eclipse.hawkbit.security.SystemSecurityContext;
import org.eclipse.hawkbit.tenancy.TenantAware; import org.eclipse.hawkbit.tenancy.TenantAware;
import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationProperties.TenantConfigurationKey; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationProperties.TenantConfigurationKey;
@@ -92,7 +92,7 @@ public class JpaControllerManagement implements ControllerManagement {
private ActionStatusRepository actionStatusRepository; private ActionStatusRepository actionStatusRepository;
@Autowired @Autowired
private HawkbitSecurityProperties securityProperties; private QuotaManagement quotaManagement;
@Autowired @Autowired
private RepositoryProperties repositoryProperties; private RepositoryProperties repositoryProperties;
@@ -313,15 +313,14 @@ public class JpaControllerManagement implements ControllerManagement {
private Action handleAddUpdateActionStatus(final JpaActionStatus actionStatus, final JpaAction action) { private Action handleAddUpdateActionStatus(final JpaActionStatus actionStatus, final JpaAction action) {
LOG.debug("addUpdateActionStatus for action {}", action.getId()); LOG.debug("addUpdateActionStatus for action {}", action.getId());
JpaTarget target = (JpaTarget) action.getTarget();
switch (actionStatus.getStatus()) { switch (actionStatus.getStatus()) {
case ERROR: case ERROR:
target = DeploymentHelper.updateTargetInfo(target, TargetUpdateStatus.ERROR, false); final JpaTarget target = DeploymentHelper.updateTargetInfo((JpaTarget) action.getTarget(),
TargetUpdateStatus.ERROR, false);
handleErrorOnAction(action, target); handleErrorOnAction(action, target);
break; break;
case FINISHED: case FINISHED:
handleFinishedAndStoreInTargetStatus(target, action); handleFinishedAndStoreInTargetStatus(action);
break; break;
default: default:
// information status entry - check for a potential DOS attack // information status entry - check for a potential DOS attack
@@ -332,7 +331,7 @@ public class JpaControllerManagement implements ControllerManagement {
actionStatus.setAction(action); actionStatus.setAction(action);
actionStatusRepository.save(actionStatus); actionStatusRepository.save(actionStatus);
LOG.debug("addUpdateActionStatus {} for target {} is finished.", action, target.getId()); LOG.debug("addUpdateActionStatus for action {} isfinished.", action.getId());
return actionRepository.save(action); return actionRepository.save(action);
} }
@@ -346,21 +345,21 @@ public class JpaControllerManagement implements ControllerManagement {
} }
private void checkForToManyStatusEntries(final JpaAction action) { private void checkForToManyStatusEntries(final JpaAction action) {
if (securityProperties.getDos().getMaxStatusEntriesPerAction() > 0) { if (quotaManagement.getMaxStatusEntriesPerAction() > 0) {
final Long statusCount = actionStatusRepository.countByAction(action); final Long statusCount = actionStatusRepository.countByAction(action);
if (statusCount >= securityProperties.getDos().getMaxStatusEntriesPerAction()) { if (statusCount >= quotaManagement.getMaxStatusEntriesPerAction()) {
LOG_DOS.error( LOG_DOS.error(
"Potential denial of service (DOS) attack identfied. More status entries in the system than permitted ({})!", "Potential denial of service (DOS) attack identfied. More status entries in the system than permitted ({})!",
securityProperties.getDos().getMaxStatusEntriesPerAction()); quotaManagement.getMaxStatusEntriesPerAction());
throw new TooManyStatusEntriesException( throw new TooManyStatusEntriesException(String.valueOf(quotaManagement.getMaxStatusEntriesPerAction()));
String.valueOf(securityProperties.getDos().getMaxStatusEntriesPerAction()));
} }
} }
} }
private void handleFinishedAndStoreInTargetStatus(final JpaTarget target, final JpaAction action) { private void handleFinishedAndStoreInTargetStatus(final JpaAction action) {
final JpaTarget target = (JpaTarget) action.getTarget();
action.setActive(false); action.setActive(false);
action.setStatus(Status.FINISHED); action.setStatus(Status.FINISHED);
final JpaDistributionSet ds = (JpaDistributionSet) entityManager.merge(action.getDistributionSet()); final JpaDistributionSet ds = (JpaDistributionSet) entityManager.merge(action.getDistributionSet());
@@ -388,11 +387,11 @@ public class JpaControllerManagement implements ControllerManagement {
target.getControllerAttributes().putAll(data); target.getControllerAttributes().putAll(data);
if (target.getControllerAttributes().size() > securityProperties.getDos().getMaxAttributeEntriesPerTarget()) { if (target.getControllerAttributes().size() > quotaManagement.getMaxAttributeEntriesPerTarget()) {
LOG_DOS.info("Target tries to insert more than the allowed number of entries ({}). DOS attack anticipated!", LOG_DOS.info("Target tries to insert more than the allowed number of entries ({}). DOS attack anticipated!",
securityProperties.getDos().getMaxAttributeEntriesPerTarget()); quotaManagement.getMaxAttributeEntriesPerTarget());
throw new ToManyAttributeEntriesException( throw new ToManyAttributeEntriesException(
String.valueOf(securityProperties.getDos().getMaxAttributeEntriesPerTarget())); String.valueOf(quotaManagement.getMaxAttributeEntriesPerTarget()));
} }
target.setRequestControllerAttributes(false); target.setRequestControllerAttributes(false);

View File

@@ -21,7 +21,6 @@ import java.util.stream.Collectors;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType; import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.ListJoin; import javax.persistence.criteria.ListJoin;
import javax.persistence.criteria.Root; import javax.persistence.criteria.Root;
@@ -43,13 +42,10 @@ import org.eclipse.hawkbit.repository.jpa.executor.AfterTransactionCommitExecuto
import org.eclipse.hawkbit.repository.jpa.model.JpaAction; import org.eclipse.hawkbit.repository.jpa.model.JpaAction;
import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus; import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus;
import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus_; import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus_;
import org.eclipse.hawkbit.repository.jpa.model.JpaActionWithStatusCount;
import org.eclipse.hawkbit.repository.jpa.model.JpaAction_; import org.eclipse.hawkbit.repository.jpa.model.JpaAction_;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet_;
import org.eclipse.hawkbit.repository.jpa.model.JpaRollout; import org.eclipse.hawkbit.repository.jpa.model.JpaRollout;
import org.eclipse.hawkbit.repository.jpa.model.JpaRolloutGroup; import org.eclipse.hawkbit.repository.jpa.model.JpaRolloutGroup;
import org.eclipse.hawkbit.repository.jpa.model.JpaRollout_;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; import org.eclipse.hawkbit.repository.jpa.model.JpaTarget;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget_; import org.eclipse.hawkbit.repository.jpa.model.JpaTarget_;
import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility; import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility;
@@ -58,7 +54,6 @@ 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;
import org.eclipse.hawkbit.repository.model.ActionStatus; import org.eclipse.hawkbit.repository.model.ActionStatus;
import org.eclipse.hawkbit.repository.model.ActionWithStatusCount;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetAssignmentResult; import org.eclipse.hawkbit.repository.model.DistributionSetAssignmentResult;
import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.DistributionSetType;
@@ -538,31 +533,6 @@ public class JpaDeploymentManagement implements DeploymentManagement {
return actionRepository.findByTargetControllerId(pageable, controllerId); return actionRepository.findByTargetControllerId(pageable, controllerId);
} }
@Override
public List<ActionWithStatusCount> findActionsWithStatusCountByTargetOrderByIdDesc(final String controllerId) {
throwExceptionIfTargetDoesNotExist(controllerId);
final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
final CriteriaQuery<JpaActionWithStatusCount> query = cb.createQuery(JpaActionWithStatusCount.class);
final Root<JpaAction> actionRoot = query.from(JpaAction.class);
final ListJoin<JpaAction, JpaActionStatus> actionStatusJoin = actionRoot.join(JpaAction_.actionStatus,
JoinType.LEFT);
final Join<JpaAction, JpaDistributionSet> actionDsJoin = actionRoot.join(JpaAction_.distributionSet);
final Join<JpaAction, JpaRollout> actionRolloutJoin = actionRoot.join(JpaAction_.rollout, JoinType.LEFT);
final CriteriaQuery<JpaActionWithStatusCount> multiselect = query.distinct(true).multiselect(
actionRoot.get(JpaAction_.id), actionRoot.get(JpaAction_.actionType), actionRoot.get(JpaAction_.active),
actionRoot.get(JpaAction_.forcedTime), actionRoot.get(JpaAction_.status),
actionRoot.get(JpaAction_.createdAt), actionRoot.get(JpaAction_.lastModifiedAt),
actionDsJoin.get(JpaDistributionSet_.id), actionDsJoin.get(JpaDistributionSet_.name),
actionDsJoin.get(JpaDistributionSet_.version), cb.count(actionStatusJoin),
actionRolloutJoin.get(JpaRollout_.name));
multiselect.where(cb.equal(actionRoot.get(JpaAction_.target).get(JpaTarget_.controllerId), controllerId));
multiselect.orderBy(cb.desc(actionRoot.get(JpaAction_.id)));
multiselect.groupBy(actionRoot.get(JpaAction_.id));
return Collections.unmodifiableList(entityManager.createQuery(multiselect).getResultList());
}
@Override @Override
public Page<Action> findActionsByTarget(final String rsqlParam, final String controllerId, public Page<Action> findActionsByTarget(final String rsqlParam, final String controllerId,
final Pageable pageable) { final Pageable pageable) {
@@ -584,17 +554,17 @@ public class JpaDeploymentManagement implements DeploymentManagement {
} }
@Override @Override
public List<Action> findActiveActionsByTarget(final String controllerId) { public Page<Action> findActiveActionsByTarget(final Pageable pageable, final String controllerId) {
throwExceptionIfTargetDoesNotExist(controllerId); throwExceptionIfTargetDoesNotExist(controllerId);
return actionRepository.findByActiveAndTarget(controllerId, true); return actionRepository.findByActiveAndTarget(pageable, controllerId, true);
} }
@Override @Override
public List<Action> findInActiveActionsByTarget(final String controllerId) { public Page<Action> findInActiveActionsByTarget(final Pageable pageable, final String controllerId) {
throwExceptionIfTargetDoesNotExist(controllerId); throwExceptionIfTargetDoesNotExist(controllerId);
return actionRepository.findByActiveAndTarget(controllerId, false); return actionRepository.findByActiveAndTarget(pageable, controllerId, false);
} }
@Override @Override
@@ -645,15 +615,6 @@ public class JpaDeploymentManagement implements DeploymentManagement {
return actionStatusRepository.findByActionId(pageReq, actionId); return actionStatusRepository.findByActionId(pageReq, actionId);
} }
@Override
public Page<ActionStatus> findActionStatusByActionWithMessages(final Pageable pageReq, final Long actionId) {
if (!actionRepository.exists(actionId)) {
throw new EntityNotFoundException(Action.class, actionId);
}
return actionStatusRepository.getByActionId(pageReq, actionId);
}
@Override @Override
public Page<String> findMessagesByActionStatusId(final Pageable pageable, final Long actionStatusId) { public Page<String> findMessagesByActionStatusId(final Pageable pageable, final Long actionStatusId) {
final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaBuilder cb = entityManager.getCriteriaBuilder();

View File

@@ -125,6 +125,9 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
@Autowired @Autowired
private SoftwareModuleTypeRepository softwareModuleTypeRepository; private SoftwareModuleTypeRepository softwareModuleTypeRepository;
@Autowired
private DistributionSetTagRepository distributionSetTagRepository;
@Override @Override
public Optional<DistributionSet> findDistributionSetByIdWithDetails(final Long distid) { public Optional<DistributionSet> findDistributionSetByIdWithDetails(final Long distid) {
return Optional.ofNullable(distributionSetRepository.findOne(DistributionSetSpecification.byId(distid))); return Optional.ofNullable(distributionSetRepository.findOne(DistributionSetSpecification.byId(distid)));
@@ -235,7 +238,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
@Override @Override
@Transactional @Transactional
public void deleteDistributionSet(final Collection<Long> distributionSetIDs) { public void deleteDistributionSet(final Collection<Long> distributionSetIDs) {
final List<DistributionSet> setsFound = findDistributionSetAllById(distributionSetIDs); final List<DistributionSet> setsFound = findDistributionSetsById(distributionSetIDs);
if (setsFound.size() < distributionSetIDs.size()) { if (setsFound.size() < distributionSetIDs.size()) {
throw new EntityNotFoundException(DistributionSet.class, distributionSetIDs, throw new EntityNotFoundException(DistributionSet.class, distributionSetIDs,
@@ -485,6 +488,17 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
return convertDsPage(findByCriteriaAPI(pageReq, specList), pageReq); return convertDsPage(findByCriteriaAPI(pageReq, specList), pageReq);
} }
@Override
public Page<DistributionSet> findDistributionSetsAll(final Pageable pageReq, final Boolean deleted) {
final List<Specification<JpaDistributionSet>> specList = new ArrayList<>(1);
if (deleted != null) {
specList.add(DistributionSetSpecification.isDeleted(deleted));
}
return convertDsPage(findByCriteriaAPI(pageReq, specList), pageReq);
}
@Override @Override
public Page<DistributionSet> findDistributionSetsAllOrderedByLinkTarget(final Pageable pageable, public Page<DistributionSet> findDistributionSetsAllOrderedByLinkTarget(final Pageable pageable,
final DistributionSetFilterBuilder distributionSetFilterBuilder, final String assignedOrInstalled) { final DistributionSetFilterBuilder distributionSetFilterBuilder, final String assignedOrInstalled) {
@@ -536,12 +550,6 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
} }
@Override
public List<DistributionSet> findDistributionSetsAll(final Collection<Long> dist) {
return Collections
.unmodifiableList(distributionSetRepository.findAll(DistributionSetSpecification.byIds(dist)));
}
@Override @Override
public Long countDistributionSetsAll() { public Long countDistributionSetsAll() {
final Specification<JpaDistributionSet> spec = DistributionSetSpecification.isDeleted(Boolean.FALSE); final Specification<JpaDistributionSet> spec = DistributionSetSpecification.isDeleted(Boolean.FALSE);
@@ -827,20 +835,6 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
.unmodifiableList(allDs.stream().map(distributionSetRepository::save).collect(Collectors.toList())); .unmodifiableList(allDs.stream().map(distributionSetRepository::save).collect(Collectors.toList()));
} }
@Override
@Transactional
public List<DistributionSet> unAssignAllDistributionSetsByTag(final Long dsTagId) {
final DistributionSetTag distributionSetTag = tagManagement.findDistributionSetTagById(dsTagId)
.orElseThrow(() -> new EntityNotFoundException(DistributionSetTag.class, dsTagId));
@SuppressWarnings({ "unchecked", "rawtypes" })
final Collection<JpaDistributionSet> distributionSets = (Collection) distributionSetTag
.getAssignedToDistributionSet();
return Collections.unmodifiableList(unAssignTag(distributionSets, distributionSetTag));
}
@Override @Override
@Transactional @Transactional
public DistributionSet unAssignTag(final Long dsId, final Long dsTagId) { public DistributionSet unAssignTag(final Long dsId, final Long dsTagId) {
@@ -894,8 +888,36 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
} }
@Override @Override
public List<DistributionSet> findDistributionSetAllById(final Collection<Long> ids) { public List<DistributionSet> findDistributionSetsById(final Collection<Long> ids) {
return Collections.unmodifiableList(distributionSetRepository.findAll(ids)); return Collections.unmodifiableList(distributionSetRepository.findAll(ids));
} }
@Override
public Page<DistributionSet> findDistributionSetsByTag(final Pageable pageable, final Long tagId) {
throwEntityNotFoundExceptionIfDsTagDoesNotExist(tagId);
return convertDsPage(distributionSetRepository.findByTag(pageable, tagId), pageable);
}
private void throwEntityNotFoundExceptionIfDsTagDoesNotExist(final Long tagId) {
if (!distributionSetTagRepository.exists(tagId)) {
throw new EntityNotFoundException(DistributionSetTag.class, tagId);
}
}
@Override
public Page<DistributionSet> findDistributionSetsByTag(final Pageable pageable, final String rsqlParam,
final Long tagId) {
throwEntityNotFoundExceptionIfDsTagDoesNotExist(tagId);
final Specification<JpaDistributionSet> spec = RSQLUtility.parse(rsqlParam, DistributionSetFields.class,
virtualPropertyReplacer);
return convertDsPage(distributionSetRepository.findAll((Specification<JpaDistributionSet>) (root, query,
cb) -> cb.and(DistributionSetSpecification.hasTag(tagId).toPredicate(root, query, cb),
spec.toPredicate(root, query, cb)),
pageable), pageable);
}
} }

View File

@@ -86,6 +86,8 @@ public class JpaRolloutGroupManagement implements RolloutGroupManagement {
@Override @Override
public Page<RolloutGroup> findRolloutGroupsByRolloutId(final Long rolloutId, final Pageable pageable) { public Page<RolloutGroup> findRolloutGroupsByRolloutId(final Long rolloutId, final Pageable pageable) {
throwEntityNotFoundExceptionIfRolloutDoesNotExist(rolloutId);
return convertPage(rolloutGroupRepository.findByRolloutId(rolloutId, pageable), pageable); return convertPage(rolloutGroupRepository.findByRolloutId(rolloutId, pageable), pageable);
} }
@@ -100,6 +102,7 @@ public class JpaRolloutGroupManagement implements RolloutGroupManagement {
@Override @Override
public Page<RolloutGroup> findRolloutGroupsAll(final Long rolloutId, final String rsqlParam, public Page<RolloutGroup> findRolloutGroupsAll(final Long rolloutId, final String rsqlParam,
final Pageable pageable) { final Pageable pageable) {
throwEntityNotFoundExceptionIfRolloutDoesNotExist(rolloutId);
final Specification<JpaRolloutGroup> specification = RSQLUtility.parse(rsqlParam, RolloutGroupFields.class, final Specification<JpaRolloutGroup> specification = RSQLUtility.parse(rsqlParam, RolloutGroupFields.class,
virtualPropertyReplacer); virtualPropertyReplacer);
@@ -115,11 +118,15 @@ public class JpaRolloutGroupManagement implements RolloutGroupManagement {
pageable); pageable);
} }
@Override private void throwEntityNotFoundExceptionIfRolloutDoesNotExist(final Long rolloutId) {
public Page<RolloutGroup> findAllRolloutGroupsWithDetailedStatus(final Long rolloutId, final Pageable pageable) {
if (!rolloutRepository.exists(rolloutId)) { if (!rolloutRepository.exists(rolloutId)) {
throw new EntityNotFoundException(Rollout.class, rolloutId); throw new EntityNotFoundException(Rollout.class, rolloutId);
} }
}
@Override
public Page<RolloutGroup> findAllRolloutGroupsWithDetailedStatus(final Long rolloutId, final Pageable pageable) {
throwEntityNotFoundExceptionIfRolloutDoesNotExist(rolloutId);
final Page<JpaRolloutGroup> rolloutGroups = rolloutGroupRepository.findByRolloutId(rolloutId, pageable); final Page<JpaRolloutGroup> rolloutGroups = rolloutGroupRepository.findByRolloutId(rolloutId, pageable);
final List<Long> rolloutGroupIds = rolloutGroups.getContent().stream().map(RolloutGroup::getId) final List<Long> rolloutGroupIds = rolloutGroups.getContent().stream().map(RolloutGroup::getId)
@@ -173,6 +180,8 @@ public class JpaRolloutGroupManagement implements RolloutGroupManagement {
public Page<Target> findRolloutGroupTargets(final Long rolloutGroupId, final String rsqlParam, public Page<Target> findRolloutGroupTargets(final Long rolloutGroupId, final String rsqlParam,
final Pageable pageable) { final Pageable pageable) {
throwExceptionIfRolloutGroupDoesNotExist(rolloutGroupId);
final Specification<JpaTarget> rsqlSpecification = RSQLUtility.parse(rsqlParam, TargetFields.class, final Specification<JpaTarget> rsqlSpecification = RSQLUtility.parse(rsqlParam, TargetFields.class,
virtualPropertyReplacer); virtualPropertyReplacer);
@@ -253,4 +262,11 @@ public class JpaRolloutGroupManagement implements RolloutGroupManagement {
} }
} }
@Override
public long countRolloutGroupsByRolloutId(final Long rolloutId) {
throwEntityNotFoundExceptionIfRolloutDoesNotExist(rolloutId);
return rolloutGroupRepository.countByRolloutId(rolloutId);
}
} }

View File

@@ -24,6 +24,7 @@ import org.apache.commons.lang3.StringUtils;
import org.eclipse.hawkbit.repository.AbstractRolloutManagement; import org.eclipse.hawkbit.repository.AbstractRolloutManagement;
import org.eclipse.hawkbit.repository.DeploymentManagement; import org.eclipse.hawkbit.repository.DeploymentManagement;
import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.QuotaManagement;
import org.eclipse.hawkbit.repository.RolloutFields; import org.eclipse.hawkbit.repository.RolloutFields;
import org.eclipse.hawkbit.repository.RolloutGroupManagement; import org.eclipse.hawkbit.repository.RolloutGroupManagement;
import org.eclipse.hawkbit.repository.RolloutHelper; import org.eclipse.hawkbit.repository.RolloutHelper;
@@ -77,6 +78,8 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice; import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.domain.Specification;
import org.springframework.integration.support.locks.LockRegistry; import org.springframework.integration.support.locks.LockRegistry;
import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Async;
@@ -129,6 +132,9 @@ public class JpaRolloutManagement extends AbstractRolloutManagement {
@Autowired @Autowired
private EntityManager entityManager; private EntityManager entityManager;
@Autowired
private QuotaManagement quotaManagement;
JpaRolloutManagement(final TargetManagement targetManagement, final DeploymentManagement deploymentManagement, JpaRolloutManagement(final TargetManagement targetManagement, final DeploymentManagement deploymentManagement,
final RolloutGroupManagement rolloutGroupManagement, final RolloutGroupManagement rolloutGroupManagement,
final DistributionSetManagement distributionSetManagement, final ApplicationContext context, final DistributionSetManagement distributionSetManagement, final ApplicationContext context,
@@ -175,7 +181,7 @@ public class JpaRolloutManagement extends AbstractRolloutManagement {
@Transactional @Transactional
public Rollout createRollout(final RolloutCreate rollout, final int amountGroup, public Rollout createRollout(final RolloutCreate rollout, final int amountGroup,
final RolloutGroupConditions conditions) { final RolloutGroupConditions conditions) {
RolloutHelper.verifyRolloutGroupParameter(amountGroup); RolloutHelper.verifyRolloutGroupParameter(amountGroup, quotaManagement);
final JpaRollout savedRollout = createRollout((JpaRollout) rollout.build()); final JpaRollout savedRollout = createRollout((JpaRollout) rollout.build());
return createRolloutGroups(amountGroup, conditions, savedRollout); return createRolloutGroups(amountGroup, conditions, savedRollout);
} }
@@ -184,7 +190,7 @@ public class JpaRolloutManagement extends AbstractRolloutManagement {
@Transactional @Transactional
public Rollout createRollout(final RolloutCreate rollout, final List<RolloutGroupCreate> groups, public Rollout createRollout(final RolloutCreate rollout, final List<RolloutGroupCreate> groups,
final RolloutGroupConditions conditions) { final RolloutGroupConditions conditions) {
RolloutHelper.verifyRolloutGroupParameter(groups.size()); RolloutHelper.verifyRolloutGroupParameter(groups.size(), quotaManagement);
final JpaRollout savedRollout = createRollout((JpaRollout) rollout.build()); final JpaRollout savedRollout = createRollout((JpaRollout) rollout.build());
return createRolloutGroups(groups, conditions, savedRollout); return createRolloutGroups(groups, conditions, savedRollout);
} }
@@ -297,7 +303,10 @@ public class JpaRolloutManagement extends AbstractRolloutManagement {
private void handleCreateRollout(final JpaRollout rollout) { private void handleCreateRollout(final JpaRollout rollout) {
LOGGER.debug("handleCreateRollout called for rollout {}", rollout.getId()); LOGGER.debug("handleCreateRollout called for rollout {}", rollout.getId());
final List<RolloutGroup> rolloutGroups = RolloutHelper.getOrderedGroups(rollout); final List<RolloutGroup> rolloutGroups = rolloutGroupManagement.findRolloutGroupsByRolloutId(rollout.getId(),
new PageRequest(0, quotaManagement.getMaxRolloutGroupsPerRollout(), new Sort(Direction.ASC, "id")))
.getContent();
int readyGroups = 0; int readyGroups = 0;
int totalTargets = 0; int totalTargets = 0;
for (final RolloutGroup group : rolloutGroups) { for (final RolloutGroup group : rolloutGroups) {
@@ -325,7 +334,7 @@ public class JpaRolloutManagement extends AbstractRolloutManagement {
} }
} }
private RolloutGroup fillRolloutGroupWithTargets(final Rollout rollout, final RolloutGroup group1) { private RolloutGroup fillRolloutGroupWithTargets(final JpaRollout rollout, final RolloutGroup group1) {
RolloutHelper.verifyRolloutInStatus(rollout, RolloutStatus.CREATING); RolloutHelper.verifyRolloutInStatus(rollout, RolloutStatus.CREATING);
final JpaRolloutGroup group = (JpaRolloutGroup) group1; final JpaRolloutGroup group = (JpaRolloutGroup) group1;
@@ -338,8 +347,8 @@ public class JpaRolloutManagement extends AbstractRolloutManagement {
groupTargetFilter = baseFilter + ";" + group.getTargetFilterQuery(); groupTargetFilter = baseFilter + ";" + group.getTargetFilterQuery();
} }
final List<Long> readyGroups = RolloutHelper.getGroupsByStatusIncludingGroup(rollout, RolloutGroupStatus.READY, final List<Long> readyGroups = RolloutHelper.getGroupsByStatusIncludingGroup(rollout.getRolloutGroups(),
group); RolloutGroupStatus.READY, group);
final long targetsInGroupFilter = runInNewTransaction("countAllTargetsByTargetFilterQueryAndNotInRolloutGroups", final long targetsInGroupFilter = runInNewTransaction("countAllTargetsByTargetFilterQueryAndNotInRolloutGroups",
count -> targetManagement.countAllTargetsByTargetFilterQueryAndNotInRolloutGroups(readyGroups, count -> targetManagement.countAllTargetsByTargetFilterQueryAndNotInRolloutGroups(readyGroups,
@@ -376,12 +385,12 @@ public class JpaRolloutManagement extends AbstractRolloutManagement {
} }
} }
private Long assignTargetsToGroupInNewTransaction(final Rollout rollout, final RolloutGroup group, private Long assignTargetsToGroupInNewTransaction(final JpaRollout rollout, final RolloutGroup group,
final String targetFilter, final long limit) { final String targetFilter, final long limit) {
return runInNewTransaction("assignTargetsToRolloutGroup", status -> { return runInNewTransaction("assignTargetsToRolloutGroup", status -> {
final PageRequest pageRequest = new PageRequest(0, Math.toIntExact(limit)); final PageRequest pageRequest = new PageRequest(0, Math.toIntExact(limit));
final List<Long> readyGroups = RolloutHelper.getGroupsByStatusIncludingGroup(rollout, final List<Long> readyGroups = RolloutHelper.getGroupsByStatusIncludingGroup(rollout.getRolloutGroups(),
RolloutGroupStatus.READY, group); RolloutGroupStatus.READY, group);
final Page<Target> targets = targetManagement final Page<Target> targets = targetManagement
.findAllTargetsByTargetFilterQueryAndNotInRolloutGroups(pageRequest, readyGroups, targetFilter); .findAllTargetsByTargetFilterQueryAndNotInRolloutGroups(pageRequest, readyGroups, targetFilter);

View File

@@ -622,7 +622,7 @@ public class JpaSoftwareManagement implements SoftwareManagement {
return convertSmMdPage( return convertSmMdPage(
softwareModuleMetadataRepository softwareModuleMetadataRepository
.findAll( .findAll(
(Specification<JpaSoftwareModuleMetadata>) (root, query, cb) -> cb.and( (root, query, cb) -> cb.and(
cb.equal(root.get(JpaSoftwareModuleMetadata_.softwareModule) cb.equal(root.get(JpaSoftwareModuleMetadata_.softwareModule)
.get(JpaSoftwareModule_.id), softwareModuleId), .get(JpaSoftwareModule_.id), softwareModuleId),
spec.toPredicate(root, query, cb)), spec.toPredicate(root, query, cb)),
@@ -631,13 +631,13 @@ public class JpaSoftwareManagement implements SoftwareManagement {
} }
@Override @Override
public List<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(final Long softwareModuleId) { public Page<SoftwareModuleMetadata> findSoftwareModuleMetadataBySoftwareModuleId(final Pageable pageable,
final Long softwareModuleId) {
throwExceptionIfSoftwareModuleDoesNotExist(softwareModuleId); throwExceptionIfSoftwareModuleDoesNotExist(softwareModuleId);
return Collections.unmodifiableList(softwareModuleMetadataRepository return convertSmMdPage(softwareModuleMetadataRepository.findAll((root, query, cb) -> cb.equal(
.findAll((Specification<JpaSoftwareModuleMetadata>) (root, query, cb) -> cb root.get(JpaSoftwareModuleMetadata_.softwareModule).get(JpaSoftwareModule_.id), softwareModuleId),
.and(cb.equal(root.get(JpaSoftwareModuleMetadata_.softwareModule).get(JpaSoftwareModule_.id), pageable), pageable);
softwareModuleId))));
} }
@Override @Override

View File

@@ -9,7 +9,9 @@
package org.eclipse.hawkbit.repository.jpa; package org.eclipse.hawkbit.repository.jpa;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
@@ -32,6 +34,10 @@ import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Propagation;
@@ -47,6 +53,8 @@ import org.springframework.validation.annotation.Validated;
@Transactional(readOnly = true) @Transactional(readOnly = true)
@Validated @Validated
public class JpaSystemManagement implements CurrentTenantCacheKeyGenerator, SystemManagement { public class JpaSystemManagement implements CurrentTenantCacheKeyGenerator, SystemManagement {
private static final int MAX_TENANTS_QUERY = 500;
@Autowired @Autowired
private EntityManager entityManager; private EntityManager entityManager;
@@ -135,7 +143,7 @@ public class JpaSystemManagement implements CurrentTenantCacheKeyGenerator, Syst
} }
private void usageStatsPerTenant(final SystemUsageReport report) { private void usageStatsPerTenant(final SystemUsageReport report) {
final List<String> tenants = findTenants(); final List<String> tenants = findTenants(new PageRequest(0, MAX_TENANTS_QUERY)).getContent();
tenants.forEach(tenant -> tenantAware.runAsTenant(tenant, () -> { tenants.forEach(tenant -> tenantAware.runAsTenant(tenant, () -> {
report.addTenantData(systemStatsManagement.getStatsOfTenant()); report.addTenantData(systemStatsManagement.getStatsOfTenant());
@@ -192,8 +200,13 @@ public class JpaSystemManagement implements CurrentTenantCacheKeyGenerator, Syst
} }
@Override @Override
public List<String> findTenants() { public Page<String> findTenants(final Pageable pageable) {
return tenantMetaDataRepository.findAll().stream().map(TenantMetaData::getTenant).collect(Collectors.toList()); final Page<JpaTenantMetaData> result = tenantMetaDataRepository.findAll(pageable);
return new PageImpl<>(
Collections.unmodifiableList(
result.getContent().stream().map(TenantMetaData::getTenant).collect(Collectors.toList())),
pageable, result.getTotalElements());
} }
@Override @Override
@@ -271,4 +284,20 @@ public class JpaSystemManagement implements CurrentTenantCacheKeyGenerator, Syst
public TenantMetaData getTenantMetadata(final Long tenantId) { public TenantMetaData getTenantMetadata(final Long tenantId) {
return tenantMetaDataRepository.findOne(tenantId); return tenantMetaDataRepository.findOne(tenantId);
} }
@Override
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void forEachTenant(final Consumer<String> consumer) {
Page<String> tenants;
Pageable query = new PageRequest(0, MAX_TENANTS_QUERY);
do {
tenants = findTenants(query);
tenants.forEach(tenant -> tenantAware.runAsTenant(tenant, () -> {
consumer.accept(tenant);
return null;
}));
} while (tenants.hasNext() && (query = tenants.nextPageable()) != null);
}
} }

View File

@@ -25,7 +25,9 @@ import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag;
import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag; import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag;
import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility; import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility;
import org.eclipse.hawkbit.repository.jpa.specifications.TagSpecification; import org.eclipse.hawkbit.repository.jpa.specifications.TagSpecification;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetTag; import org.eclipse.hawkbit.repository.model.TargetTag;
import org.eclipse.hawkbit.repository.rsql.VirtualPropertyReplacer; import org.eclipse.hawkbit.repository.rsql.VirtualPropertyReplacer;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -85,17 +87,12 @@ public class JpaTagManagement implements TagManagement {
@Override @Override
@Transactional @Transactional
public void deleteTargetTag(final String targetTagName) { public void deleteTargetTag(final String targetTagName) {
final TargetTag tag = targetTagRepository.findByNameEquals(targetTagName) if (!targetTagRepository.existsByName(targetTagName)) {
.orElseThrow(() -> new EntityNotFoundException(TargetTag.class, targetTagName)); throw new EntityNotFoundException(TargetTag.class, targetTagName);
}
targetRepository.findByTag(tag.getId()).forEach(set -> {
set.removeTag(tag);
targetRepository.save(set);
});
// finally delete the tag itself // finally delete the tag itself
targetTagRepository.deleteByName(targetTagName); targetTagRepository.deleteByName(targetTagName);
} }
@Override @Override
@@ -177,22 +174,13 @@ public class JpaTagManagement implements TagManagement {
@Override @Override
@Transactional @Transactional
public void deleteDistributionSetTag(final String tagName) { public void deleteDistributionSetTag(final String tagName) {
final DistributionSetTag tag = distributionSetTagRepository.findByNameEquals(tagName) if (!distributionSetTagRepository.existsByName(tagName)) {
.orElseThrow(() -> new EntityNotFoundException(DistributionSetTag.class, tagName)); throw new EntityNotFoundException(DistributionSetTag.class, tagName);
}
distributionSetRepository.findByTag(tag).forEach(set -> {
set.removeTag(tag);
distributionSetRepository.save(set);
});
distributionSetTagRepository.deleteByName(tagName); distributionSetTagRepository.deleteByName(tagName);
} }
@Override
public List<DistributionSetTag> findAllDistributionSetTags() {
return Collections.unmodifiableList(distributionSetTagRepository.findAll());
}
@Override @Override
public Optional<TargetTag> findTargetTagById(final Long id) { public Optional<TargetTag> findTargetTagById(final Long id) {
return Optional.ofNullable(targetTagRepository.findOne(id)); return Optional.ofNullable(targetTagRepository.findOne(id));
@@ -223,7 +211,21 @@ public class JpaTagManagement implements TagManagement {
@Override @Override
public Page<TargetTag> findAllTargetTags(final Pageable pageable, final String controllerId) { public Page<TargetTag> findAllTargetTags(final Pageable pageable, final String controllerId) {
if (!targetRepository.existsByControllerId(controllerId)) {
throw new EntityNotFoundException(Target.class, controllerId);
}
return convertTPage(targetTagRepository.findAll(TagSpecification.ofTarget(controllerId), pageable), pageable); return convertTPage(targetTagRepository.findAll(TagSpecification.ofTarget(controllerId), pageable), pageable);
} }
@Override
public Page<DistributionSetTag> findDistributionSetTagsByDistributionSet(final Pageable pageable,
final Long setId) {
if (!distributionSetRepository.exists(setId)) {
throw new EntityNotFoundException(DistributionSet.class, setId);
}
return convertDsPage(distributionSetTagRepository.findAll(TagSpecification.ofDistributionSet(setId), pageable),
pageable);
}
} }

View File

@@ -113,7 +113,7 @@ public class JpaTargetManagement implements TargetManagement {
} }
@Override @Override
public List<Target> findTargetByControllerID(final Collection<String> controllerIDs) { public List<Target> findTargetsByControllerID(final Collection<String> controllerIDs) {
return Collections.unmodifiableList( return Collections.unmodifiableList(
targetRepository.findAll(TargetSpecifications.byControllerIdWithAssignedDsInJoin(controllerIDs))); targetRepository.findAll(TargetSpecifications.byControllerIdWithAssignedDsInJoin(controllerIDs)));
} }
@@ -376,41 +376,18 @@ public class JpaTargetManagement implements TargetManagement {
.unmodifiableList(allTargets.stream().map(targetRepository::save).collect(Collectors.toList())); .unmodifiableList(allTargets.stream().map(targetRepository::save).collect(Collectors.toList()));
} }
private List<Target> unAssignTag(final Collection<Target> targets, final TargetTag tag) {
@SuppressWarnings({ "unchecked", "rawtypes" })
final Collection<JpaTarget> toUnassign = (Collection) targets;
toUnassign.forEach(target -> target.removeTag(tag));
return Collections
.unmodifiableList(toUnassign.stream().map(targetRepository::save).collect(Collectors.toList()));
}
@Override
@Transactional
public List<Target> unAssignAllTargetsByTag(final Long targetTagId) {
final TargetTag tag = targetTagRepository.findById(targetTagId)
.orElseThrow(() -> new EntityNotFoundException(TargetTag.class, targetTagId));
if (tag.getAssignedToTargets().isEmpty()) {
return Collections.emptyList();
}
return unAssignTag(tag.getAssignedToTargets(), tag);
}
@Override @Override
@Transactional @Transactional
public Target unAssignTag(final String controllerID, final Long targetTagId) { public Target unAssignTag(final String controllerID, final Long targetTagId) {
final Target target = targetRepository.findByControllerId(controllerID) final JpaTarget target = (JpaTarget) targetRepository.findByControllerId(controllerID)
.orElseThrow(() -> new EntityNotFoundException(Target.class, controllerID)); .orElseThrow(() -> new EntityNotFoundException(Target.class, controllerID));
final TargetTag tag = targetTagRepository.findById(targetTagId) final TargetTag tag = targetTagRepository.findById(targetTagId)
.orElseThrow(() -> new EntityNotFoundException(TargetTag.class, targetTagId)); .orElseThrow(() -> new EntityNotFoundException(TargetTag.class, targetTagId));
final List<Target> unAssignTag = unAssignTag(Lists.newArrayList(target), tag); target.removeTag(tag);
return unAssignTag.isEmpty() ? null : unAssignTag.get(0);
return targetRepository.save(target);
} }
@Override @Override
@@ -559,13 +536,28 @@ public class JpaTargetManagement implements TargetManagement {
} }
@Override @Override
public List<Target> findTargetsByTag(final String tagName) { public Page<Target> findTargetsByTag(final Pageable pageable, final Long tagId) {
final Optional<TargetTag> tag = targetTagRepository.findByNameEquals(tagName); throwEntityNotFoundExceptionIfTagDoesNotExist(tagId);
if (!tag.isPresent()) {
return Collections.emptyList();
}
return Collections.unmodifiableList(targetRepository.findByTag(tag.get().getId())); return convertPage(targetRepository.findByTag(pageable, tagId), pageable);
}
private void throwEntityNotFoundExceptionIfTagDoesNotExist(final Long tagId) {
if (!targetTagRepository.exists(tagId)) {
throw new EntityNotFoundException(TargetTag.class, tagId);
}
}
@Override
public Page<Target> findTargetsByTag(final Pageable pageable, final String rsqlParam, final Long tagId) {
throwEntityNotFoundExceptionIfTagDoesNotExist(tagId);
final Specification<JpaTarget> spec = RSQLUtility.parse(rsqlParam, TargetFields.class, virtualPropertyReplacer);
return convertPage(targetRepository.findAll((Specification<JpaTarget>) (root, query, cb) -> cb.and(
TargetSpecifications.hasTag(tagId).toPredicate(root, query, cb), spec.toPredicate(root, query, cb)),
pageable), pageable);
} }
@Override @Override
@@ -594,7 +586,7 @@ public class JpaTargetManagement implements TargetManagement {
} }
@Override @Override
public List<Target> findTargetAllById(final Collection<Long> ids) { public List<Target> findTargetsById(final Collection<Long> ids) {
return Collections.unmodifiableList(targetRepository.findAll(ids)); return Collections.unmodifiableList(targetRepository.findAll(ids));
} }

View File

@@ -24,6 +24,7 @@ import org.eclipse.hawkbit.repository.RepositoryProperties;
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.SoftwareManagement; import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.PropertiesQuotaManagement;
import org.eclipse.hawkbit.repository.SystemManagement; import org.eclipse.hawkbit.repository.SystemManagement;
import org.eclipse.hawkbit.repository.TagManagement; import org.eclipse.hawkbit.repository.TagManagement;
import org.eclipse.hawkbit.repository.TargetFilterQueryManagement; import org.eclipse.hawkbit.repository.TargetFilterQueryManagement;
@@ -63,6 +64,7 @@ import org.eclipse.hawkbit.repository.model.helper.SystemManagementHolder;
import org.eclipse.hawkbit.repository.model.helper.TenantConfigurationManagementHolder; import org.eclipse.hawkbit.repository.model.helper.TenantConfigurationManagementHolder;
import org.eclipse.hawkbit.repository.rsql.RsqlValidationOracle; import org.eclipse.hawkbit.repository.rsql.RsqlValidationOracle;
import org.eclipse.hawkbit.repository.rsql.VirtualPropertyReplacer; import org.eclipse.hawkbit.repository.rsql.VirtualPropertyReplacer;
import org.eclipse.hawkbit.security.HawkbitSecurityProperties;
import org.eclipse.hawkbit.security.SecurityTokenGenerator; import org.eclipse.hawkbit.security.SecurityTokenGenerator;
import org.eclipse.hawkbit.security.SystemSecurityContext; import org.eclipse.hawkbit.security.SystemSecurityContext;
import org.eclipse.hawkbit.tenancy.TenantAware; import org.eclipse.hawkbit.tenancy.TenantAware;
@@ -123,6 +125,11 @@ public class RepositoryApplicationConfiguration extends JpaBaseConfiguration {
return new RsqlParserValidationOracle(); return new RsqlParserValidationOracle();
} }
@Bean
PropertiesQuotaManagement staticQuotaManagement(final HawkbitSecurityProperties securityProperties) {
return new PropertiesQuotaManagement(securityProperties);
}
/** /**
* @param distributionSetManagement * @param distributionSetManagement
* to loading the {@link DistributionSetType} * to loading the {@link DistributionSetType}
@@ -557,8 +564,7 @@ public class RepositoryApplicationConfiguration extends JpaBaseConfiguration {
AutoAssignScheduler autoAssignScheduler(final TenantAware tenantAware, final SystemManagement systemManagement, AutoAssignScheduler autoAssignScheduler(final TenantAware tenantAware, final SystemManagement systemManagement,
final SystemSecurityContext systemSecurityContext, final AutoAssignChecker autoAssignChecker, final SystemSecurityContext systemSecurityContext, final AutoAssignChecker autoAssignChecker,
final LockRegistry lockRegistry) { final LockRegistry lockRegistry) {
return new AutoAssignScheduler(tenantAware, systemManagement, systemSecurityContext, autoAssignChecker, return new AutoAssignScheduler(systemManagement, systemSecurityContext, autoAssignChecker, lockRegistry);
lockRegistry);
} }
/** /**
@@ -567,8 +573,6 @@ public class RepositoryApplicationConfiguration extends JpaBaseConfiguration {
* Note: does not activate in test profile, otherwise it is hard to test the * Note: does not activate in test profile, otherwise it is hard to test the
* rollout handling functionality. * rollout handling functionality.
* *
* @param tenantAware
* to run as specific tenant
* @param systemManagement * @param systemManagement
* to find all tenants * to find all tenants
* @param rolloutManagement * @param rolloutManagement
@@ -583,6 +587,6 @@ public class RepositoryApplicationConfiguration extends JpaBaseConfiguration {
@ConditionalOnProperty(prefix = "hawkbit.rollout.scheduler", name = "enabled", matchIfMissing = true) @ConditionalOnProperty(prefix = "hawkbit.rollout.scheduler", name = "enabled", matchIfMissing = true)
RolloutScheduler rolloutScheduler(final TenantAware tenantAware, final SystemManagement systemManagement, RolloutScheduler rolloutScheduler(final TenantAware tenantAware, final SystemManagement systemManagement,
final RolloutManagement rolloutManagement, final SystemSecurityContext systemSecurityContext) { final RolloutManagement rolloutManagement, final SystemSecurityContext systemSecurityContext) {
return new RolloutScheduler(tenantAware, systemManagement, rolloutManagement, systemSecurityContext); return new RolloutScheduler(systemManagement, rolloutManagement, systemSecurityContext);
} }
} }

View File

@@ -146,6 +146,16 @@ public interface RolloutGroupRepository
*/ */
Page<JpaRolloutGroup> findByRolloutId(final Long rolloutId, Pageable page); Page<JpaRolloutGroup> findByRolloutId(final Long rolloutId, Pageable page);
/**
* Counts all {@link RolloutGroup} for a specific rollout.
*
* @param rolloutId
* the ID of the rollout to find the rollout groups
*
* @return the amount of found {@link RolloutGroup}s.
*/
long countByRolloutId(final Long rolloutId);
@Modifying @Modifying
@Query("DELETE FROM JpaRolloutGroup g where g.id in :rolloutGroupIds") @Query("DELETE FROM JpaRolloutGroup g where g.id in :rolloutGroupIds")
void deleteByIds(@Param("rolloutGroupIds") List<Long> rolloutGroups); void deleteByIds(@Param("rolloutGroupIds") List<Long> rolloutGroups);

View File

@@ -94,13 +94,16 @@ public interface TargetRepository extends BaseEntityRepository<JpaTarget, Long>,
/** /**
* Finds {@link Target}s by assigned {@link Tag}. * Finds {@link Target}s by assigned {@link Tag}.
*
* @param page
* pages query and sorting information
* *
* @param tagId * @param tagId
* to be found * to be found
* @return list of found targets * @return page of found targets
*/ */
@Query(value = "SELECT DISTINCT t FROM JpaTarget t JOIN t.tags tt WHERE tt.id = :tag") @Query(value = "SELECT DISTINCT t FROM JpaTarget t JOIN t.tags tt WHERE tt.id = :tag")
List<JpaTarget> findByTag(@Param("tag") final Long tagId); Page<JpaTarget> findByTag(Pageable page, @Param("tag") final Long tagId);
/** /**
* Finds all {@link Target}s based on given {@link Target#getControllerId()} * Finds all {@link Target}s based on given {@link Target#getControllerId()}

View File

@@ -50,6 +50,16 @@ public interface TargetTagRepository
*/ */
Optional<TargetTag> findByNameEquals(String tagName); Optional<TargetTag> findByNameEquals(String tagName);
/**
* Checks if tag with given name exists.
*
* @param tagName
* to check for
* @return <code>true</code> is tag with given name exists
*/
@Query("SELECT CASE WHEN COUNT(t)>0 THEN 'true' ELSE 'false' END FROM JpaTargetTag t WHERE t.name=:tagName")
boolean existsByName(@Param("tagName") String tagName);
/** /**
* Returns all instances of the type. * Returns all instances of the type.
* *

View File

@@ -9,7 +9,6 @@
package org.eclipse.hawkbit.repository.jpa.aspects; package org.eclipse.hawkbit.repository.jpa.aspects;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -25,16 +24,17 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered; import org.springframework.core.Ordered;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException; import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator; import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator;
import org.springframework.orm.jpa.JpaSystemException; import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.AccessDeniedException;
import org.springframework.transaction.TransactionSystemException; import org.springframework.transaction.TransactionSystemException;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
/** /**
@@ -54,8 +54,7 @@ public class ExceptionMappingAspectHandler implements Ordered {
* most specific mappable exception according to the type hierarchy of the * most specific mappable exception according to the type hierarchy of the
* exception. * exception.
*/ */
private static final List<Class<?>> MAPPED_EXCEPTION_ORDER = new ArrayList<>(4); private static final List<Class<?>> MAPPED_EXCEPTION_ORDER = Lists.newArrayListWithExpectedSize(4);
@Autowired @Autowired
private JpaVendorAdapter jpaVendorAdapter; private JpaVendorAdapter jpaVendorAdapter;
@@ -65,14 +64,14 @@ public class ExceptionMappingAspectHandler implements Ordered {
MAPPED_EXCEPTION_ORDER.add(DuplicateKeyException.class); MAPPED_EXCEPTION_ORDER.add(DuplicateKeyException.class);
MAPPED_EXCEPTION_ORDER.add(DataIntegrityViolationException.class); MAPPED_EXCEPTION_ORDER.add(DataIntegrityViolationException.class);
MAPPED_EXCEPTION_ORDER.add(ConcurrencyFailureException.class); MAPPED_EXCEPTION_ORDER.add(OptimisticLockingFailureException.class);
MAPPED_EXCEPTION_ORDER.add(AccessDeniedException.class); MAPPED_EXCEPTION_ORDER.add(AccessDeniedException.class);
EXCEPTION_MAPPING.put(DuplicateKeyException.class.getName(), EntityAlreadyExistsException.class.getName()); EXCEPTION_MAPPING.put(DuplicateKeyException.class.getName(), EntityAlreadyExistsException.class.getName());
EXCEPTION_MAPPING.put(DataIntegrityViolationException.class.getName(), EXCEPTION_MAPPING.put(DataIntegrityViolationException.class.getName(),
EntityAlreadyExistsException.class.getName()); EntityAlreadyExistsException.class.getName());
EXCEPTION_MAPPING.put(ConcurrencyFailureException.class.getName(), EXCEPTION_MAPPING.put(OptimisticLockingFailureException.class.getName(),
ConcurrentModificationException.class.getName()); ConcurrentModificationException.class.getName());
EXCEPTION_MAPPING.put(AccessDeniedException.class.getName(), InsufficientPermissionException.class.getName()); EXCEPTION_MAPPING.put(AccessDeniedException.class.getName(), InsufficientPermissionException.class.getName());
} }
@@ -86,10 +85,7 @@ public class ExceptionMappingAspectHandler implements Ordered {
* @throws Throwable * @throws Throwable
*/ */
@AfterThrowing(pointcut = "( execution( * org.springframework.transaction..*.*(..)) " @AfterThrowing(pointcut = "( execution( * org.springframework.transaction..*.*(..)) "
+ " || execution( * org.eclipse.hawkbit.repository.*.*(..)) " + " || execution( * org.eclipse.hawkbit.repository.*.*(..)) )", throwing = "ex")
+ " || execution( * org.eclipse.hawkbit.controller.*.*(..)) "
+ " || execution( * org.eclipse.hawkbit.rest.resource.*.*(..)) "
+ " || execution( * org.eclipse.hawkbit.service.*.*(..)) )", throwing = "ex")
// Exception for squid:S00112, squid:S1162 // Exception for squid:S00112, squid:S1162
// It is a AspectJ proxy which deals with exceptions. // It is a AspectJ proxy which deals with exceptions.
@SuppressWarnings({ "squid:S00112", "squid:S1162" }) @SuppressWarnings({ "squid:S00112", "squid:S1162" })

View File

@@ -8,12 +8,10 @@
*/ */
package org.eclipse.hawkbit.repository.jpa.autoassign; package org.eclipse.hawkbit.repository.jpa.autoassign;
import java.util.List;
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Lock;
import org.eclipse.hawkbit.repository.SystemManagement; import org.eclipse.hawkbit.repository.SystemManagement;
import org.eclipse.hawkbit.security.SystemSecurityContext; import org.eclipse.hawkbit.security.SystemSecurityContext;
import org.eclipse.hawkbit.tenancy.TenantAware;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.integration.support.locks.LockRegistry; import org.springframework.integration.support.locks.LockRegistry;
@@ -27,8 +25,6 @@ public class AutoAssignScheduler {
private static final String PROP_SCHEDULER_DELAY_PLACEHOLDER = "${hawkbit.autoassign.scheduler.fixedDelay:2000}"; private static final String PROP_SCHEDULER_DELAY_PLACEHOLDER = "${hawkbit.autoassign.scheduler.fixedDelay:2000}";
private final TenantAware tenantAware;
private final SystemManagement systemManagement; private final SystemManagement systemManagement;
private final SystemSecurityContext systemSecurityContext; private final SystemSecurityContext systemSecurityContext;
@@ -40,8 +36,6 @@ public class AutoAssignScheduler {
/** /**
* Instantiates a new AutoAssignScheduler * Instantiates a new AutoAssignScheduler
* *
* @param tenantAware
* to run as specific tenant
* @param systemManagement * @param systemManagement
* to find all tenants * to find all tenants
* @param systemSecurityContext * @param systemSecurityContext
@@ -51,10 +45,9 @@ public class AutoAssignScheduler {
* @param lockRegistry * @param lockRegistry
* to acquire a lock per tenant * to acquire a lock per tenant
*/ */
public AutoAssignScheduler(final TenantAware tenantAware, final SystemManagement systemManagement, public AutoAssignScheduler(final SystemManagement systemManagement,
final SystemSecurityContext systemSecurityContext, final AutoAssignChecker autoAssignChecker, final SystemSecurityContext systemSecurityContext, final AutoAssignChecker autoAssignChecker,
final LockRegistry lockRegistry) { final LockRegistry lockRegistry) {
this.tenantAware = tenantAware;
this.systemManagement = systemManagement; this.systemManagement = systemManagement;
this.systemSecurityContext = systemSecurityContext; this.systemSecurityContext = systemSecurityContext;
this.autoAssignChecker = autoAssignChecker; this.autoAssignChecker = autoAssignChecker;
@@ -82,24 +75,17 @@ public class AutoAssignScheduler {
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=355458. So // https://bugs.eclipse.org/bugs/show_bug.cgi?id=355458. So
// iterate through all tenants and execute the rollout check for // iterate through all tenants and execute the rollout check for
// each tenant separately. // each tenant separately.
final List<String> tenants = systemManagement.findTenants();
LOGGER.info("Checking target filter queries for tenants: {}", tenants.size());
final Lock lock = lockRegistry.obtain("autoassign"); final Lock lock = lockRegistry.obtain("autoassign");
if (!lock.tryLock()) { if (!lock.tryLock()) {
return null; return null;
} }
try { try {
for (final String tenant : tenants) { systemManagement.forEachTenant(tenant -> autoAssignChecker.check());
tenantAware.runAsTenant(tenant, () -> {
autoAssignChecker.check();
return null;
});
}
} finally { } finally {
lock.unlock(); lock.unlock();
} }
return null; return null;
} }
} }

View File

@@ -131,7 +131,6 @@ public class JpaAction extends AbstractJpaTenantAwareBaseEntity implements Actio
return actionType; return actionType;
} }
@Override
public List<ActionStatus> getActionStatus() { public List<ActionStatus> getActionStatus() {
if (actionStatus == null) { if (actionStatus == null) {
return Collections.emptyList(); return Collections.emptyList();

View File

@@ -142,7 +142,6 @@ public class JpaActionStatus extends AbstractJpaTenantAwareBaseEntity implements
} }
} }
@Override
public List<String> getMessages() { public List<String> getMessages() {
if (messages == null) { if (messages == null) {
messages = Collections.emptyList(); messages = Collections.emptyList();

View File

@@ -1,112 +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.jpa.model;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.ActionType;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.ActionStatus;
import org.eclipse.hawkbit.repository.model.ActionWithStatusCount;
/**
* Custom JPA Model for querying {@link Action} include the count of the
* action's {@link ActionStatus}.
*
*/
public class JpaActionWithStatusCount implements ActionWithStatusCount {
private final Long actionStatusCount;
private final Long dsId;
private final String dsName;
private final String dsVersion;
private final JpaAction action;
private final String rolloutName;
/**
* JPA constructor, the parameter are the result set columns of the custom
* query.
*
* @param actionId
* the ID of the action
* @param actionType
* the action type
* @param active
* the active attribute of the action
* @param forcedTime
* the forced time attribute of the action
* @param status
* the status attribute of the action
* @param actionCreatedAt
* the createdAt timestamp of the action
* @param actionLastModifiedAt
* the last modified timestamp of the action
* @param dsId
* the ID of the distributionset
* @param dsName
* the name of the distributionset
* @param dsVersion
* the version of the distributionset
* @param actionStatusCount
* the count of the action status for this action
* @param rolloutName
* the rollout name
*/
// Exception squid:S00107 - needed this way for JPA to fill the view
@SuppressWarnings("squid:S00107")
public JpaActionWithStatusCount(final Long actionId, final ActionType actionType, final boolean active,
final Long forcedTime, final Status status, final Long actionCreatedAt, final Long actionLastModifiedAt,
final Long dsId, final String dsName, final String dsVersion, final Long actionStatusCount,
final String rolloutName) {
this.dsId = dsId;
this.dsName = dsName;
this.dsVersion = dsVersion;
this.actionStatusCount = actionStatusCount;
this.rolloutName = rolloutName;
action = new JpaAction();
action.setActionType(actionType);
action.setActive(active);
action.setForcedTime(forcedTime);
action.setStatus(status);
action.setId(actionId);
action.setActionType(actionType);
action.setCreatedAt(actionCreatedAt);
action.setLastModifiedAt(actionLastModifiedAt);
}
@Override
public Action getAction() {
return action;
}
@Override
public Long getDsId() {
return dsId;
}
@Override
public String getDsName() {
return dsName;
}
@Override
public String getDsVersion() {
return dsVersion;
}
@Override
public Long getActionStatusCount() {
return actionStatusCount;
}
@Override
public String getRolloutName() {
return rolloutName;
}
}

View File

@@ -35,7 +35,7 @@ import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.repository.event.remote.DistributionSetDeletedEvent; import org.eclipse.hawkbit.repository.event.remote.DistributionSetDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetCreatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetUpdateEvent; import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetUpdatedEvent;
import org.eclipse.hawkbit.repository.exception.DistributionSetTypeUndefinedException; import org.eclipse.hawkbit.repository.exception.DistributionSetTypeUndefinedException;
import org.eclipse.hawkbit.repository.exception.UnsupportedSoftwareModuleForThisDistributionSetException; import org.eclipse.hawkbit.repository.exception.UnsupportedSoftwareModuleForThisDistributionSetException;
import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action;
@@ -174,7 +174,6 @@ public class JpaDistributionSet extends AbstractJpaNamedVersionedEntity implemen
this(name, version, description, type, moduleList, false); this(name, version, description, type, moduleList, false);
} }
@Override
public Set<DistributionSetTag> getTags() { public Set<DistributionSetTag> getTags() {
if (tags == null) { if (tags == null) {
return Collections.emptySet(); return Collections.emptySet();
@@ -339,7 +338,7 @@ public class JpaDistributionSet extends AbstractJpaNamedVersionedEntity implemen
public void fireUpdateEvent(final DescriptorEvent descriptorEvent) { public void fireUpdateEvent(final DescriptorEvent descriptorEvent) {
publishEventWithEventPublisher( publishEventWithEventPublisher(
new DistributionSetUpdateEvent(this, EventPublisherHolder.getInstance().getApplicationId())); new DistributionSetUpdatedEvent(this, EventPublisherHolder.getInstance().getApplicationId()));
if (isSoftDeleted(descriptorEvent)) { if (isSoftDeleted(descriptorEvent)) {
publishEventWithEventPublisher(new DistributionSetDeletedEvent(getTenant(), getId(), getClass().getName(), publishEventWithEventPublisher(new DistributionSetDeletedEvent(getTenant(), getId(), getClass().getName(),

View File

@@ -20,7 +20,7 @@ import javax.persistence.UniqueConstraint;
import org.eclipse.hawkbit.repository.event.remote.DistributionSetTagDeletedEvent; import org.eclipse.hawkbit.repository.event.remote.DistributionSetTagDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetTagCreatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetTagCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetTagUpdateEvent; import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetTagUpdatedEvent;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.eclipse.hawkbit.repository.model.helper.EventPublisherHolder; import org.eclipse.hawkbit.repository.model.helper.EventPublisherHolder;
@@ -64,7 +64,6 @@ public class JpaDistributionSetTag extends JpaTag implements DistributionSetTag,
// Default constructor for JPA. // Default constructor for JPA.
} }
@Override
public List<DistributionSet> getAssignedToDistributionSet() { public List<DistributionSet> getAssignedToDistributionSet() {
if (assignedToDistributionSet == null) { if (assignedToDistributionSet == null) {
return Collections.emptyList(); return Collections.emptyList();
@@ -82,7 +81,7 @@ public class JpaDistributionSetTag extends JpaTag implements DistributionSetTag,
@Override @Override
public void fireUpdateEvent(final DescriptorEvent descriptorEvent) { public void fireUpdateEvent(final DescriptorEvent descriptorEvent) {
EventPublisherHolder.getInstance().getEventPublisher().publishEvent( EventPublisherHolder.getInstance().getEventPublisher().publishEvent(
new DistributionSetTagUpdateEvent(this, EventPublisherHolder.getInstance().getApplicationId())); new DistributionSetTagUpdatedEvent(this, EventPublisherHolder.getInstance().getApplicationId()));
} }

View File

@@ -130,7 +130,6 @@ public class JpaRollout extends AbstractJpaNamedEntity implements Rollout, Event
this.distributionSet = (JpaDistributionSet) distributionSet; this.distributionSet = (JpaDistributionSet) distributionSet;
} }
@Override
public List<RolloutGroup> getRolloutGroups() { public List<RolloutGroup> getRolloutGroups() {
if (rolloutGroups == null) { if (rolloutGroups == null) {
return Collections.emptyList(); return Collections.emptyList();

View File

@@ -20,7 +20,7 @@ import javax.persistence.UniqueConstraint;
import org.eclipse.hawkbit.repository.event.remote.TargetTagDeletedEvent; import org.eclipse.hawkbit.repository.event.remote.TargetTagDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetTagCreatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.TargetTagCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetTagUpdateEvent; import org.eclipse.hawkbit.repository.event.remote.entity.TargetTagUpdatedEvent;
import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetTag; import org.eclipse.hawkbit.repository.model.TargetTag;
import org.eclipse.hawkbit.repository.model.helper.EventPublisherHolder; import org.eclipse.hawkbit.repository.model.helper.EventPublisherHolder;
@@ -61,7 +61,6 @@ public class JpaTargetTag extends JpaTag implements TargetTag, EventAwareEntity
// Default constructor for JPA. // Default constructor for JPA.
} }
@Override
public List<Target> getAssignedToTargets() { public List<Target> getAssignedToTargets() {
if (assignedToTargets == null) { if (assignedToTargets == null) {
return Collections.emptyList(); return Collections.emptyList();
@@ -80,7 +79,7 @@ public class JpaTargetTag extends JpaTag implements TargetTag, EventAwareEntity
@Override @Override
public void fireUpdateEvent(final DescriptorEvent descriptorEvent) { public void fireUpdateEvent(final DescriptorEvent descriptorEvent) {
EventPublisherHolder.getInstance().getEventPublisher() EventPublisherHolder.getInstance().getEventPublisher()
.publishEvent(new TargetTagUpdateEvent(this, EventPublisherHolder.getInstance().getApplicationId())); .publishEvent(new TargetTagUpdatedEvent(this, EventPublisherHolder.getInstance().getApplicationId()));
} }
@Override @Override

View File

@@ -8,12 +8,9 @@
*/ */
package org.eclipse.hawkbit.repository.jpa.rollout; package org.eclipse.hawkbit.repository.jpa.rollout;
import java.util.List;
import org.eclipse.hawkbit.repository.RolloutManagement; import org.eclipse.hawkbit.repository.RolloutManagement;
import org.eclipse.hawkbit.repository.SystemManagement; import org.eclipse.hawkbit.repository.SystemManagement;
import org.eclipse.hawkbit.security.SystemSecurityContext; import org.eclipse.hawkbit.security.SystemSecurityContext;
import org.eclipse.hawkbit.tenancy.TenantAware;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
@@ -29,8 +26,6 @@ public class RolloutScheduler {
private static final String PROP_SCHEDULER_DELAY_PLACEHOLDER = "${hawkbit.rollout.scheduler.fixedDelay:2000}"; private static final String PROP_SCHEDULER_DELAY_PLACEHOLDER = "${hawkbit.rollout.scheduler.fixedDelay:2000}";
private final TenantAware tenantAware;
private final SystemManagement systemManagement; private final SystemManagement systemManagement;
private final RolloutManagement rolloutManagement; private final RolloutManagement rolloutManagement;
@@ -40,8 +35,6 @@ public class RolloutScheduler {
/** /**
* Constructor. * Constructor.
* *
* @param tenantAware
* to run as specific tenant
* @param systemManagement * @param systemManagement
* to find all tenants * to find all tenants
* @param rolloutManagement * @param rolloutManagement
@@ -49,9 +42,8 @@ public class RolloutScheduler {
* @param systemSecurityContext * @param systemSecurityContext
* to run as system * to run as system
*/ */
public RolloutScheduler(final TenantAware tenantAware, final SystemManagement systemManagement, public RolloutScheduler(final SystemManagement systemManagement, final RolloutManagement rolloutManagement,
final RolloutManagement rolloutManagement, final SystemSecurityContext systemSecurityContext) { final SystemSecurityContext systemSecurityContext) {
this.tenantAware = tenantAware;
this.systemManagement = systemManagement; this.systemManagement = systemManagement;
this.rolloutManagement = rolloutManagement; this.rolloutManagement = rolloutManagement;
this.systemSecurityContext = systemSecurityContext; this.systemSecurityContext = systemSecurityContext;
@@ -76,22 +68,9 @@ public class RolloutScheduler {
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=355458. So // https://bugs.eclipse.org/bugs/show_bug.cgi?id=355458. So
// iterate through all tenants and execute the rollout check for // iterate through all tenants and execute the rollout check for
// each tenant seperately. // each tenant seperately.
final List<String> tenants = systemManagement.findTenants();
LOGGER.info("Checking rollouts for {} tenants", tenants.size()); systemManagement.forEachTenant(tenant -> rolloutManagement.handleRollouts());
for (final String tenant : tenants) {
tenantAware.runAsTenant(tenant, () -> {
try {
rolloutManagement.handleRollouts();
// We catch all potential runtime exceptions here to
// ensure that not all tenants are blocked if we have a
// problem with a rollout.
} catch (@SuppressWarnings("squid:S1166") final RuntimeException e) {
LOGGER.error("Failed to handle rollouts for tenant {}. I will move on to next tenant.", tenant,
e);
}
return null;
});
}
return null; return null;
}); });
} }

View File

@@ -78,7 +78,6 @@ public final class DistributionSetSpecification {
return (targetRoot, query, cb) -> { return (targetRoot, query, cb) -> {
final Predicate predicate = cb.equal(targetRoot.<Long> get(JpaDistributionSet_.id), distid); final Predicate predicate = cb.equal(targetRoot.<Long> get(JpaDistributionSet_.id), distid);
targetRoot.fetch(JpaDistributionSet_.modules, JoinType.LEFT); targetRoot.fetch(JpaDistributionSet_.modules, JoinType.LEFT);
targetRoot.fetch(JpaDistributionSet_.tags, JoinType.LEFT);
targetRoot.fetch(JpaDistributionSet_.type, JoinType.LEFT); targetRoot.fetch(JpaDistributionSet_.type, JoinType.LEFT);
query.distinct(true); query.distinct(true);
@@ -218,4 +217,20 @@ public final class DistributionSetSpecification {
}; };
} }
/**
* {@link Specification} for retrieving {@link DistributionSet}s by tag.
*
* @param tagId
* the ID of the distribution set which must be assigned
* @return the {@link DistributionSet} {@link Specification}
*/
public static Specification<JpaDistributionSet> hasTag(final Long tagId) {
return (targetRoot, query, cb) -> {
final SetJoin<JpaDistributionSet, JpaDistributionSetTag> tags = targetRoot.join(JpaDistributionSet_.tags,
JoinType.LEFT);
return cb.equal(tags.get(JpaDistributionSetTag_.id), tagId);
};
}
} }

View File

@@ -8,9 +8,6 @@
*/ */
package org.eclipse.hawkbit.repository.jpa.specifications; package org.eclipse.hawkbit.repository.jpa.specifications;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType; import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType_; import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType_;
@@ -28,24 +25,6 @@ public final class SoftwareModuleSpecification {
// utility class // utility class
} }
/**
* {@link Specification} for retrieving {@link SoftwareModule}s by its ID
* attribute.
*
* @param moduleId
* to search for
* @return the {@link SoftwareModule} {@link Specification}
*/
public static Specification<JpaSoftwareModule> byId(final Long moduleId) {
return (targetRoot, query, cb) -> {
final Predicate predicate = cb.equal(targetRoot.<Long> get(JpaSoftwareModule_.id), moduleId);
targetRoot.fetch(JpaSoftwareModule_.type);
targetRoot.fetch(JpaSoftwareModule_.metadata, JoinType.LEFT);
query.distinct(true);
return predicate;
};
}
/** /**
* {@link Specification} for retrieving {@link SoftwareModule}s where its * {@link Specification} for retrieving {@link SoftwareModule}s where its
* DELETED attribute is false. * DELETED attribute is false.
@@ -57,8 +36,8 @@ public final class SoftwareModuleSpecification {
} }
/** /**
* {@link Specification} for retrieving {@link SoftwareModule}s by * {@link Specification} for retrieving {@link SoftwareModule}s by "like
* "like name or like version". * name or like version".
* *
* @param subString * @param subString
* to be filtered on * to be filtered on
@@ -71,8 +50,8 @@ public final class SoftwareModuleSpecification {
} }
/** /**
* {@link Specification} for retrieving {@link SoftwareModule}s by * {@link Specification} for retrieving {@link SoftwareModule}s by "like
* "like name or like version". * name or like version".
* *
* @param type * @param type
* to be filtered on * to be filtered on

View File

@@ -10,11 +10,18 @@ package org.eclipse.hawkbit.repository.jpa.specifications;
import javax.persistence.criteria.Join; import javax.persistence.criteria.Join;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag_;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet_;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; import org.eclipse.hawkbit.repository.jpa.model.JpaTarget;
import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag; import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag;
import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag_; import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag_;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget_; import org.eclipse.hawkbit.repository.jpa.model.JpaTarget_;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetTag;
import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.domain.Specification;
/** /**
@@ -28,13 +35,13 @@ public final class TagSpecification {
} }
/** /**
* {@link Specification} for retrieving {@link DistributionSet}s by its * {@link Specification} for retrieving {@link TargetTag}s by assigned
* DELETED attribute. * {@link Target}.
* *
* @param isDeleted * @param controllerId
* TRUE/FALSE are compared to the attribute DELETED. If NULL the * of the target
* attribute is ignored *
* @return the {@link DistributionSet} {@link Specification} * @return the {@link JpaTargetTag} {@link Specification}
*/ */
public static Specification<JpaTargetTag> ofTarget(final String controllerId) { public static Specification<JpaTargetTag> ofTarget(final String controllerId) {
return (targetRoot, query, criteriaBuilder) -> { return (targetRoot, query, criteriaBuilder) -> {
@@ -47,4 +54,25 @@ public final class TagSpecification {
} }
/**
* {@link Specification} for retrieving {@link DistributionSetTag}s by
* assigned {@link DistributionSet}.
*
* @param dsId
* of the distribution set
*
* @return the {@link JpaDistributionSetTag} {@link Specification}
*/
public static Specification<JpaDistributionSetTag> ofDistributionSet(final Long dsId) {
return (dsRoot, query, criteriaBuilder) -> {
final Join<JpaDistributionSetTag, JpaDistributionSet> tagJoin = dsRoot
.join(JpaDistributionSetTag_.assignedToDistributionSet);
query.distinct(true);
return criteriaBuilder.equal(tagJoin.get(JpaDistributionSet_.id), dsId);
};
}
} }

View File

@@ -287,4 +287,19 @@ public final class TargetSpecifications {
return (targetRoot, query, cb) -> cb.equal( return (targetRoot, query, cb) -> cb.equal(
targetRoot.get(JpaTarget_.installedDistributionSet).get(JpaDistributionSet_.id), distributionSetId); targetRoot.get(JpaTarget_.installedDistributionSet).get(JpaDistributionSet_.id), distributionSetId);
} }
/**
* {@link Specification} for retrieving {@link Target}s by tag.
*
* @param tagId
* the ID of the distribution set which must be assigned
* @return the {@link Target} {@link Specification}
*/
public static Specification<JpaTarget> hasTag(final Long tagId) {
return (targetRoot, query, cb) -> {
final SetJoin<JpaTarget, JpaTargetTag> tags = targetRoot.join(JpaTarget_.tags, JoinType.LEFT);
return cb.equal(tags.get(JpaTargetTag_.id), tagId);
};
}
} }

View File

@@ -31,7 +31,7 @@ public class DistributionSetEventTest extends AbstractRemoteEntityEventTest<Dist
@Test @Test
@Description("Verifies that the distribution set entity reloading by remote updated event works") @Description("Verifies that the distribution set entity reloading by remote updated event works")
public void testDistributionSetUpdateEvent() { public void testDistributionSetUpdateEvent() {
assertAndCreateRemoteEvent(DistributionSetUpdateEvent.class); assertAndCreateRemoteEvent(DistributionSetUpdatedEvent.class);
} }
@Override @Override

View File

@@ -31,7 +31,7 @@ public class DistributionSetTagEventTest extends AbstractRemoteEntityEventTest<D
@Test @Test
@Description("Verifies that the distribution set tag entity reloading by remote updated event works") @Description("Verifies that the distribution set tag entity reloading by remote updated event works")
public void testDistributionSetTagUpdateEvent() { public void testDistributionSetTagUpdateEvent() {
assertAndCreateRemoteEvent(DistributionSetTagUpdateEvent.class); assertAndCreateRemoteEvent(DistributionSetTagUpdatedEvent.class);
} }
@Override @Override

View File

@@ -99,7 +99,7 @@ public class RolloutGroupEventTest extends AbstractRemoteEntityEventTest<Rollout
10, new RolloutGroupConditionBuilder().withDefaults() 10, new RolloutGroupConditionBuilder().withDefaults()
.successCondition(RolloutGroupSuccessCondition.THRESHOLD, "10").build()); .successCondition(RolloutGroupSuccessCondition.THRESHOLD, "10").build());
return rolloutManagement.findRolloutById(entity.getId()).get().getRolloutGroups().get(0); return rolloutGroupManagement.findRolloutGroupsByRolloutId(entity.getId(), PAGE).getContent().get(0);
} }
} }

View File

@@ -31,7 +31,7 @@ public class TargetTagEventTest extends AbstractRemoteEntityEventTest<TargetTag>
@Test @Test
@Description("Verifies that the target tag entity reloading by remote updated event works") @Description("Verifies that the target tag entity reloading by remote updated event works")
public void testTargetTagUpdateEventt() { public void testTargetTagUpdateEventt() {
assertAndCreateRemoteEvent(TargetTagUpdateEvent.class); assertAndCreateRemoteEvent(TargetTagUpdatedEvent.class);
} }
@Override @Override

View File

@@ -98,7 +98,7 @@ public abstract class AbstractJpaIntegrationTest extends AbstractIntegrationTest
@Transactional(readOnly = true) @Transactional(readOnly = true)
protected List<Action> findActionsByRolloutAndStatus(final Rollout rollout, final Action.Status actionStatus) { protected List<Action> findActionsByRolloutAndStatus(final Rollout rollout, final Action.Status actionStatus) {
return Lists.newArrayList(actionRepository.findByRolloutIdAndStatus(pageReq, rollout.getId(), actionStatus)); return Lists.newArrayList(actionRepository.findByRolloutIdAndStatus(PAGE, rollout.getId(), actionStatus));
} }
protected static void verifyThrownExceptionBy(final ThrowingCallable tc, final String objectType) { protected static void verifyThrownExceptionBy(final ThrowingCallable tc, final String objectType) {

View File

@@ -76,7 +76,7 @@ public class ArtifactManagementTest extends AbstractJpaIntegrationTest {
verifyThrownExceptionBy(() -> artifactManagement.deleteArtifact(NOT_EXIST_IDL), "Artifact"); verifyThrownExceptionBy(() -> artifactManagement.deleteArtifact(NOT_EXIST_IDL), "Artifact");
verifyThrownExceptionBy(() -> artifactManagement.findArtifactBySoftwareModule(pageReq, NOT_EXIST_IDL), verifyThrownExceptionBy(() -> artifactManagement.findArtifactBySoftwareModule(PAGE, NOT_EXIST_IDL),
"SoftwareModule"); "SoftwareModule");
assertThat(artifactManagement.findArtifactByFilename(NOT_EXIST_ID).isPresent()).isFalse(); assertThat(artifactManagement.findArtifactByFilename(NOT_EXIST_ID).isPresent()).isFalse();
@@ -260,12 +260,12 @@ public class ArtifactManagementTest extends AbstractJpaIntegrationTest {
public void findArtifactBySoftwareModule() { public void findArtifactBySoftwareModule() {
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
assertThat(artifactManagement.findArtifactBySoftwareModule(pageReq, sm.getId())).isEmpty(); assertThat(artifactManagement.findArtifactBySoftwareModule(PAGE, sm.getId())).isEmpty();
final Artifact result = artifactManagement.createArtifact(new RandomGeneratedInputStream(5 * 1024), sm.getId(), final Artifact result = artifactManagement.createArtifact(new RandomGeneratedInputStream(5 * 1024), sm.getId(),
"file1", false); "file1", false);
assertThat(artifactManagement.findArtifactBySoftwareModule(pageReq, sm.getId())).hasSize(1); assertThat(artifactManagement.findArtifactBySoftwareModule(PAGE, sm.getId())).hasSize(1);
} }
@Test @Test

View File

@@ -138,7 +138,7 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest {
Action.Status.FINISHED, Action.Status.FINISHED, false); Action.Status.FINISHED, Action.Status.FINISHED, false);
assertThat(actionStatusRepository.count()).isEqualTo(6); assertThat(actionStatusRepository.count()).isEqualTo(6);
assertThat(deploymentManagement.findActionStatusByAction(pageReq, actionId).getNumberOfElements()).isEqualTo(6); assertThat(deploymentManagement.findActionStatusByAction(PAGE, actionId).getNumberOfElements()).isEqualTo(6);
} }
@Test @Test
@@ -161,7 +161,7 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest {
Action.Status.FINISHED, Action.Status.FINISHED, false); Action.Status.FINISHED, Action.Status.FINISHED, false);
assertThat(actionStatusRepository.count()).isEqualTo(3); assertThat(actionStatusRepository.count()).isEqualTo(3);
assertThat(deploymentManagement.findActionStatusByAction(pageReq, actionId).getNumberOfElements()).isEqualTo(3); assertThat(deploymentManagement.findActionStatusByAction(PAGE, actionId).getNumberOfElements()).isEqualTo(3);
} }
@Test @Test
@@ -186,7 +186,7 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest {
Action.Status.RUNNING, Action.Status.RUNNING, true); Action.Status.RUNNING, Action.Status.RUNNING, true);
assertThat(actionStatusRepository.count()).isEqualTo(1); assertThat(actionStatusRepository.count()).isEqualTo(1);
assertThat(deploymentManagement.findActionStatusByAction(pageReq, actionId).getNumberOfElements()).isEqualTo(1); assertThat(deploymentManagement.findActionStatusByAction(PAGE, actionId).getNumberOfElements()).isEqualTo(1);
} }
@@ -214,7 +214,7 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest {
Action.Status.CANCELED, Action.Status.FINISHED, false); Action.Status.CANCELED, Action.Status.FINISHED, false);
assertThat(actionStatusRepository.count()).isEqualTo(7); assertThat(actionStatusRepository.count()).isEqualTo(7);
assertThat(deploymentManagement.findActionStatusByAction(pageReq, actionId).getNumberOfElements()).isEqualTo(7); assertThat(deploymentManagement.findActionStatusByAction(PAGE, actionId).getNumberOfElements()).isEqualTo(7);
} }
@Test @Test
@@ -241,7 +241,7 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest {
Action.Status.CANCELED, Action.Status.CANCELED, false); Action.Status.CANCELED, Action.Status.CANCELED, false);
assertThat(actionStatusRepository.count()).isEqualTo(7); assertThat(actionStatusRepository.count()).isEqualTo(7);
assertThat(deploymentManagement.findActionStatusByAction(pageReq, actionId).getNumberOfElements()).isEqualTo(7); assertThat(deploymentManagement.findActionStatusByAction(PAGE, actionId).getNumberOfElements()).isEqualTo(7);
} }
@Test @Test
@@ -269,7 +269,7 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest {
Action.Status.RUNNING, Action.Status.CANCEL_REJECTED, true); Action.Status.RUNNING, Action.Status.CANCEL_REJECTED, true);
assertThat(actionStatusRepository.count()).isEqualTo(7); assertThat(actionStatusRepository.count()).isEqualTo(7);
assertThat(deploymentManagement.findActionStatusByAction(pageReq, actionId).getNumberOfElements()).isEqualTo(7); assertThat(deploymentManagement.findActionStatusByAction(PAGE, actionId).getNumberOfElements()).isEqualTo(7);
} }
@Test @Test
@@ -297,7 +297,7 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest {
Action.Status.RUNNING, Action.Status.ERROR, true); Action.Status.RUNNING, Action.Status.ERROR, true);
assertThat(actionStatusRepository.count()).isEqualTo(7); assertThat(actionStatusRepository.count()).isEqualTo(7);
assertThat(deploymentManagement.findActionStatusByAction(pageReq, actionId).getNumberOfElements()).isEqualTo(7); assertThat(deploymentManagement.findActionStatusByAction(PAGE, actionId).getNumberOfElements()).isEqualTo(7);
} }
@Step @Step
@@ -308,7 +308,8 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get() assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); .getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
return deploymentManagement.findActiveActionsByTarget(TestdataFactory.DEFAULT_CONTROLLER_ID).get(0).getId(); return deploymentManagement.findActiveActionsByTarget(PAGE, TestdataFactory.DEFAULT_CONTROLLER_ID)
.getContent().get(0).getId();
} }
@Step @Step
@@ -366,7 +367,7 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest {
final Action action = deploymentManagement.findAction(actionId).get(); final Action action = deploymentManagement.findAction(actionId).get();
assertThat(action.getStatus()).isEqualTo(expectedActionActionStatus); assertThat(action.getStatus()).isEqualTo(expectedActionActionStatus);
assertThat(action.isActive()).isEqualTo(actionActive); assertThat(action.isActive()).isEqualTo(actionActive);
final List<ActionStatus> actionStatusList = deploymentManagement.findActionStatusByAction(pageReq, actionId) final List<ActionStatus> actionStatusList = deploymentManagement.findActionStatusByAction(PAGE, actionId)
.getContent(); .getContent();
assertThat(actionStatusList.get(actionStatusList.size() - 1).getStatus()).isEqualTo(expectedActionStatus); assertThat(actionStatusList.get(actionStatusList.size() - 1).getStatus()).isEqualTo(expectedActionStatus);
if (actionActive) { if (actionActive) {
@@ -472,7 +473,7 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest {
Action.Status.ERROR, Action.Status.ERROR, false); Action.Status.ERROR, Action.Status.ERROR, false);
assertThat(actionStatusRepository.count()).isEqualTo(3); assertThat(actionStatusRepository.count()).isEqualTo(3);
assertThat(deploymentManagement.findActionStatusByAction(pageReq, actionId).getNumberOfElements()).isEqualTo(3); assertThat(deploymentManagement.findActionStatusByAction(PAGE, actionId).getNumberOfElements()).isEqualTo(3);
} }
@@ -507,7 +508,7 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest {
Action.Status.FINISHED, Action.Status.FINISHED, false); Action.Status.FINISHED, Action.Status.FINISHED, false);
assertThat(actionStatusRepository.count()).isEqualTo(3); assertThat(actionStatusRepository.count()).isEqualTo(3);
assertThat(deploymentManagement.findActionStatusByAction(pageReq, actionId).getNumberOfElements()).isEqualTo(3); assertThat(deploymentManagement.findActionStatusByAction(PAGE, actionId).getNumberOfElements()).isEqualTo(3);
} }
@@ -533,7 +534,7 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest {
.getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC); .getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC);
assertThat(actionStatusRepository.count()).isEqualTo(3); assertThat(actionStatusRepository.count()).isEqualTo(3);
assertThat(deploymentManagement.findActionStatusByAction(pageReq, action.getId()).getNumberOfElements()) assertThat(deploymentManagement.findActionStatusByAction(PAGE, action.getId()).getNumberOfElements())
.isEqualTo(3); .isEqualTo(3);
} }
@@ -558,8 +559,8 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest {
.getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC); .getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC);
// however, additional action status has been stored // however, additional action status has been stored
assertThat(actionStatusRepository.findAll(pageReq).getNumberOfElements()).isEqualTo(4); assertThat(actionStatusRepository.findAll(PAGE).getNumberOfElements()).isEqualTo(4);
assertThat(deploymentManagement.findActionStatusByAction(pageReq, action.getId()).getNumberOfElements()) assertThat(deploymentManagement.findActionStatusByAction(PAGE, action.getId()).getNumberOfElements())
.isEqualTo(4); .isEqualTo(4);
} }

View File

@@ -36,6 +36,7 @@ import org.eclipse.hawkbit.repository.exception.ForceQuitActionNotAllowedExcepti
import org.eclipse.hawkbit.repository.exception.IncompleteDistributionSetException; import org.eclipse.hawkbit.repository.exception.IncompleteDistributionSetException;
import org.eclipse.hawkbit.repository.jpa.configuration.Constants; import org.eclipse.hawkbit.repository.jpa.configuration.Constants;
import org.eclipse.hawkbit.repository.jpa.model.JpaAction; import org.eclipse.hawkbit.repository.jpa.model.JpaAction;
import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; import org.eclipse.hawkbit.repository.jpa.model.JpaTarget;
import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action;
@@ -122,16 +123,15 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
verifyThrownExceptionBy(() -> deploymentManagement.countActionsByTarget(NOT_EXIST_ID), "Target"); verifyThrownExceptionBy(() -> deploymentManagement.countActionsByTarget(NOT_EXIST_ID), "Target");
verifyThrownExceptionBy(() -> deploymentManagement.countActionsByTarget("xxx", NOT_EXIST_ID), "Target"); verifyThrownExceptionBy(() -> deploymentManagement.countActionsByTarget("xxx", NOT_EXIST_ID), "Target");
verifyThrownExceptionBy(() -> deploymentManagement.findActionsByDistributionSet(pageReq, NOT_EXIST_IDL), verifyThrownExceptionBy(() -> deploymentManagement.findActionsByDistributionSet(PAGE, NOT_EXIST_IDL),
"DistributionSet"); "DistributionSet");
verifyThrownExceptionBy(() -> deploymentManagement.findActionsByTarget(NOT_EXIST_ID, pageReq), "Target"); verifyThrownExceptionBy(() -> deploymentManagement.findActionsByTarget(NOT_EXIST_ID, PAGE), "Target");
verifyThrownExceptionBy(() -> deploymentManagement.findActionsByTarget("id==*", NOT_EXIST_ID, pageReq), verifyThrownExceptionBy(() -> deploymentManagement.findActionsByTarget("id==*", NOT_EXIST_ID, PAGE),
"Target"); "Target");
verifyThrownExceptionBy(
() -> deploymentManagement.findActionsWithStatusCountByTargetOrderByIdDesc(NOT_EXIST_ID), "Target");
verifyThrownExceptionBy(() -> deploymentManagement.findActiveActionsByTarget(NOT_EXIST_ID), "Target"); verifyThrownExceptionBy(() -> deploymentManagement.findActiveActionsByTarget(PAGE, NOT_EXIST_ID), "Target");
verifyThrownExceptionBy(() -> deploymentManagement.findInActiveActionsByTarget(NOT_EXIST_ID), "Target"); verifyThrownExceptionBy(() -> deploymentManagement.findInActiveActionsByTarget(PAGE, NOT_EXIST_ID),
"Target");
verifyThrownExceptionBy(() -> deploymentManagement.forceQuitAction(NOT_EXIST_IDL), "Action"); verifyThrownExceptionBy(() -> deploymentManagement.forceQuitAction(NOT_EXIST_IDL), "Action");
verifyThrownExceptionBy(() -> deploymentManagement.forceTargetAction(NOT_EXIST_IDL), "Action"); verifyThrownExceptionBy(() -> deploymentManagement.forceTargetAction(NOT_EXIST_IDL), "Action");
} }
@@ -164,7 +164,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
// act // act
final Slice<Action> actions = deploymentManagement.findActionsByTarget(testTarget.get(0).getControllerId(), final Slice<Action> actions = deploymentManagement.findActionsByTarget(testTarget.get(0).getControllerId(),
pageReq); PAGE);
final Long count = deploymentManagement.countActionsByTarget(testTarget.get(0).getControllerId()); final Long count = deploymentManagement.countActionsByTarget(testTarget.get(0).getControllerId());
assertThat(count).as("One Action for target").isEqualTo(1L).isEqualTo(actions.getContent().size()); assertThat(count).as("One Action for target").isEqualTo(1L).isEqualTo(actions.getContent().size());
@@ -180,11 +180,11 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
// one action with one action status is generated // one action with one action status is generated
final Long actionId = assignDistributionSet(testDs, testTarget).getActions().get(0); final Long actionId = assignDistributionSet(testDs, testTarget).getActions().get(0);
final Slice<Action> actions = deploymentManagement.findActionsByTarget(testTarget.get(0).getControllerId(), final Slice<Action> actions = deploymentManagement.findActionsByTarget(testTarget.get(0).getControllerId(),
pageReq); PAGE);
final ActionStatus expectedActionStatus = actions.getContent().get(0).getActionStatus().get(0); final ActionStatus expectedActionStatus = ((JpaAction) actions.getContent().get(0)).getActionStatus().get(0);
// act // act
final Page<ActionStatus> actionStates = deploymentManagement.findActionStatusByAction(pageReq, actionId); final Page<ActionStatus> actionStates = deploymentManagement.findActionStatusByAction(PAGE, actionId);
assertThat(actionStates.getContent()).hasSize(1); assertThat(actionStates.getContent()).hasSize(1);
assertThat(actionStates.getContent().get(0)).as("Action-status of action").isEqualTo(expectedActionStatus); assertThat(actionStates.getContent().get(0)).as("Action-status of action").isEqualTo(expectedActionStatus);
@@ -201,14 +201,15 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
// create action-status entry with one message // create action-status entry with one message
controllerManagement.addUpdateActionStatus(entityFactory.actionStatus().create(actionId) controllerManagement.addUpdateActionStatus(entityFactory.actionStatus().create(actionId)
.status(Action.Status.FINISHED).messages(Lists.newArrayList("finished message"))); .status(Action.Status.FINISHED).messages(Lists.newArrayList("finished message")));
final Page<ActionStatus> actionStates = deploymentManagement.findActionStatusByAction(pageReq, actionId); final Page<ActionStatus> actionStates = deploymentManagement.findActionStatusByAction(PAGE, actionId);
// find newly created action-status entry with message // find newly created action-status entry with message
final ActionStatus actionStatusWithMessage = actionStates.getContent().stream() final JpaActionStatus actionStatusWithMessage = actionStates.getContent().stream().map(c -> (JpaActionStatus) c)
.filter(entry -> entry.getMessages() != null && entry.getMessages().size() > 0).findFirst().get(); .filter(entry -> entry.getMessages() != null && entry.getMessages().size() > 0).findFirst().get();
final String expectedMsg = actionStatusWithMessage.getMessages().get(0); final String expectedMsg = actionStatusWithMessage.getMessages().get(0);
// act // act
final Page<String> messages = deploymentManagement.findMessagesByActionStatusId(pageReq, final Page<String> messages = deploymentManagement.findMessagesByActionStatusId(PAGE,
actionStatusWithMessage.getId()); actionStatusWithMessage.getId());
assertThat(actionStates.getTotalElements()).as("Two action-states in total").isEqualTo(2L); assertThat(actionStates.getTotalElements()).as("Two action-states in total").isEqualTo(2L);
@@ -425,7 +426,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertThat(deploymentManagement.getAssignedDistributionSet(target.getControllerId()).get()) assertThat(deploymentManagement.getAssignedDistributionSet(target.getControllerId()).get())
.as("wrong assigned ds").isEqualTo(ds); .as("wrong assigned ds").isEqualTo(ds);
final JpaAction action = actionRepository final JpaAction action = actionRepository
.findByTargetAndDistributionSet(pageReq, (JpaTarget) target, (JpaDistributionSet) ds).getContent() .findByTargetAndDistributionSet(PAGE, (JpaTarget) target, (JpaDistributionSet) ds).getContent()
.get(0); .get(0);
assertThat(action).as("action should not be null").isNotNull(); assertThat(action).as("action should not be null").isNotNull();
return action; return action;
@@ -455,12 +456,12 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assignDistributionSet(ds, savedDeployedTargets); assignDistributionSet(ds, savedDeployedTargets);
// verify that one Action for each assignDistributionSet // verify that one Action for each assignDistributionSet
assertThat(actionRepository.findAll(pageReq).getNumberOfElements()).as("wrong size of actions").isEqualTo(20); assertThat(actionRepository.findAll(PAGE).getNumberOfElements()).as("wrong size of actions").isEqualTo(20);
final Iterable<Target> allFoundTargets = targetManagement.findTargetsAll(pageReq).getContent(); final Iterable<Target> allFoundTargets = targetManagement.findTargetsAll(PAGE).getContent();
// get final updated version of targets // get final updated version of targets
savedDeployedTargets = targetManagement.findTargetByControllerID( savedDeployedTargets = targetManagement.findTargetsByControllerID(
savedDeployedTargets.stream().map(target -> target.getControllerId()).collect(Collectors.toList())); savedDeployedTargets.stream().map(target -> target.getControllerId()).collect(Collectors.toList()));
assertThat(allFoundTargets).as("founded targets are wrong").containsAll(savedDeployedTargets) assertThat(allFoundTargets).as("founded targets are wrong").containsAll(savedDeployedTargets)
@@ -479,7 +480,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
for (final Target myt : savedDeployedTargets) { for (final Target myt : savedDeployedTargets) {
final Target t = targetManagement.findTargetByControllerID(myt.getControllerId()).get(); final Target t = targetManagement.findTargetByControllerID(myt.getControllerId()).get();
final List<Action> activeActionsByTarget = deploymentManagement final List<Action> activeActionsByTarget = deploymentManagement
.findActiveActionsByTarget(t.getControllerId()); .findActiveActionsByTarget(PAGE, t.getControllerId()).getContent();
assertThat(activeActionsByTarget).as("action should not be empty").isNotEmpty(); assertThat(activeActionsByTarget).as("action should not be empty").isNotEmpty();
assertThat(t.getUpdateStatus()).as("wrong target update status").isEqualTo(TargetUpdateStatus.PENDING); assertThat(t.getUpdateStatus()).as("wrong target update status").isEqualTo(TargetUpdateStatus.PENDING);
for (final Action ua : activeActionsByTarget) { for (final Action ua : activeActionsByTarget) {
@@ -558,7 +559,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
final Collection<JpaTarget> savedDeployedTargets = (Collection) deploymentResult.getDeployedTargets(); final Collection<JpaTarget> savedDeployedTargets = (Collection) deploymentResult.getDeployedTargets();
// retrieving all Actions created by the assignDistributionSet call // retrieving all Actions created by the assignDistributionSet call
final Page<JpaAction> page = actionRepository.findAll(pageReq); final Page<JpaAction> page = actionRepository.findAll(PAGE);
// and verify the number // and verify the number
assertThat(page.getTotalElements()).as("wrong size of actions") assertThat(page.getTotalElements()).as("wrong size of actions")
.isEqualTo(noOfDeployedTargets * noOfDistributionSets); .isEqualTo(noOfDeployedTargets * noOfDistributionSets);
@@ -653,7 +654,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
.as("installed ds is wrong").isEqualTo(dsA); .as("installed ds is wrong").isEqualTo(dsA);
assertThat(targetManagement.findTargetByControllerID(t.getControllerId()).get().getUpdateStatus()) assertThat(targetManagement.findTargetByControllerID(t.getControllerId()).get().getUpdateStatus())
.as("wrong target info update status").isEqualTo(TargetUpdateStatus.IN_SYNC); .as("wrong target info update status").isEqualTo(TargetUpdateStatus.IN_SYNC);
assertThat(deploymentManagement.findActiveActionsByTarget(t.getControllerId())) assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, t.getControllerId()))
.as("no actions should be active").hasSize(0); .as("no actions should be active").hasSize(0);
} }
@@ -666,7 +667,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
actionRepository.findByDistributionSetId(pageRequest, dsA.getId()).getContent().get(1); actionRepository.findByDistributionSetId(pageRequest, dsA.getId()).getContent().get(1);
// get final updated version of targets // get final updated version of targets
final List<Target> deployResWithDsBTargets = targetManagement.findTargetByControllerID(deployResWithDsB final List<Target> deployResWithDsBTargets = targetManagement.findTargetsByControllerID(deployResWithDsB
.getDeployedTargets().stream().map(Target::getControllerId).collect(Collectors.toList())); .getDeployedTargets().stream().map(Target::getControllerId).collect(Collectors.toList()));
assertThat(deployed2DS).as("deployed ds is wrong").containsAll(deployResWithDsBTargets); assertThat(deployed2DS).as("deployed ds is wrong").containsAll(deployResWithDsBTargets);
@@ -724,7 +725,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
// verify that deleted attribute is used correctly // verify that deleted attribute is used correctly
List<DistributionSet> allFoundDS = distributionSetManagement List<DistributionSet> allFoundDS = distributionSetManagement
.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true).getContent(); .findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true).getContent();
assertThat(allFoundDS.size()).as("no ds should be founded").isEqualTo(0); assertThat(allFoundDS.size()).as("no ds should be founded").isEqualTo(0);
allFoundDS = distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageRequest, true, true) allFoundDS = distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageRequest, true, true)
.getContent(); .getContent();
@@ -798,28 +799,28 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
distributionSetManagement.findDistributionSetByIdWithDetails(dsA.getId()).get().getOptLockRevision()); distributionSetManagement.findDistributionSetByIdWithDetails(dsA.getId()).get().getOptLockRevision());
// verifying that the assignment is correct // verifying that the assignment is correct
assertThat(deploymentManagement.findActiveActionsByTarget(targ.getControllerId()).size()) assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, targ.getControllerId()).getTotalElements())
.as("Active target actions are wrong").isEqualTo(1); .as("Active target actions are wrong").isEqualTo(1);
assertThat(deploymentManagement.countActionsByTarget(targ.getControllerId())).as("Target actions are wrong") assertThat(deploymentManagement.countActionsByTarget(targ.getControllerId())).as("Target actions are wrong")
.isEqualTo(1); .isEqualTo(1);
assertThat(targ.getUpdateStatus()).as("UpdateStatus of target is wrong").isEqualTo(TargetUpdateStatus.PENDING); assertThat(targ.getUpdateStatus()).as("UpdateStatus of target is wrong").isEqualTo(TargetUpdateStatus.PENDING);
assertThat(deploymentManagement.getAssignedDistributionSet(targ.getControllerId()).get()) assertThat(deploymentManagement.getAssignedDistributionSet(targ.getControllerId()).get())
.as("Assigned distribution set of target is wrong").isEqualTo(dsA); .as("Assigned distribution set of target is wrong").isEqualTo(dsA);
assertThat(deploymentManagement.findActiveActionsByTarget(targ.getControllerId()).get(0).getDistributionSet()) assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, targ.getControllerId()).getContent().get(0)
.as("Distribution set of actionn is wrong").isEqualTo(dsA); .getDistributionSet()).as("Distribution set of actionn is wrong").isEqualTo(dsA);
assertThat(deploymentManagement.findActiveActionsByTarget(targ.getControllerId()).get(0).getDistributionSet()) assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, targ.getControllerId()).getContent().get(0)
.as("Installed distribution set of action should be null").isNotNull(); .getDistributionSet()).as("Installed distribution set of action should be null").isNotNull();
final Page<Action> updAct = actionRepository.findByDistributionSetId(pageReq, dsA.getId()); final Page<Action> updAct = actionRepository.findByDistributionSetId(PAGE, dsA.getId());
controllerManagement.addUpdateActionStatus( controllerManagement.addUpdateActionStatus(
entityFactory.actionStatus().create(updAct.getContent().get(0).getId()).status(Status.FINISHED)); entityFactory.actionStatus().create(updAct.getContent().get(0).getId()).status(Status.FINISHED));
targ = targetManagement.findTargetByControllerID(targ.getControllerId()).get(); targ = targetManagement.findTargetByControllerID(targ.getControllerId()).get();
assertEquals("active target actions are wrong", 0, assertEquals("active target actions are wrong", 0,
deploymentManagement.findActiveActionsByTarget(targ.getControllerId()).size()); deploymentManagement.findActiveActionsByTarget(PAGE, targ.getControllerId()).getTotalElements());
assertEquals("active actions are wrong", 1, assertEquals("active actions are wrong", 1,
deploymentManagement.findInActiveActionsByTarget(targ.getControllerId()).size()); deploymentManagement.findInActiveActionsByTarget(PAGE, targ.getControllerId()).getTotalElements());
assertEquals("tagret update status is not correct", TargetUpdateStatus.IN_SYNC, targ.getUpdateStatus()); assertEquals("tagret update status is not correct", TargetUpdateStatus.IN_SYNC, targ.getUpdateStatus());
assertEquals("wrong assigned ds", dsA, assertEquals("wrong assigned ds", dsA,
@@ -832,15 +833,15 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
targ = targs.iterator().next(); targ = targs.iterator().next();
assertEquals("active actions are wrong", 1, assertEquals("active actions are wrong", 1,
deploymentManagement.findActiveActionsByTarget(targ.getControllerId()).size()); deploymentManagement.findActiveActionsByTarget(PAGE, targ.getControllerId()).getTotalElements());
assertEquals("target status is wrong", TargetUpdateStatus.PENDING, assertEquals("target status is wrong", TargetUpdateStatus.PENDING,
targetManagement.findTargetByControllerID(targ.getControllerId()).get().getUpdateStatus()); targetManagement.findTargetByControllerID(targ.getControllerId()).get().getUpdateStatus());
assertEquals("wrong assigned ds", dsB, assertEquals("wrong assigned ds", dsB,
deploymentManagement.getAssignedDistributionSet(targ.getControllerId()).get()); deploymentManagement.getAssignedDistributionSet(targ.getControllerId()).get());
assertEquals("Installed ds is wrong", dsA.getId(), assertEquals("Installed ds is wrong", dsA.getId(),
deploymentManagement.getInstalledDistributionSet(targ.getControllerId()).get().getId()); deploymentManagement.getInstalledDistributionSet(targ.getControllerId()).get().getId());
assertEquals("Active ds is wrong", dsB, assertEquals("Active ds is wrong", dsB, deploymentManagement
deploymentManagement.findActiveActionsByTarget(targ.getControllerId()).get(0).getDistributionSet()); .findActiveActionsByTarget(PAGE, targ.getControllerId()).getContent().get(0).getDistributionSet());
} }
@@ -972,7 +973,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest {
if (event.getControllerId().equals(myt.getControllerId())) { if (event.getControllerId().equals(myt.getControllerId())) {
found = true; found = true;
final List<Action> activeActionsByTarget = deploymentManagement final List<Action> activeActionsByTarget = deploymentManagement
.findActiveActionsByTarget(myt.getControllerId()); .findActiveActionsByTarget(PAGE, myt.getControllerId()).getContent();
assertThat(activeActionsByTarget).as("size of active actions for target is wrong").isNotEmpty(); assertThat(activeActionsByTarget).as("size of active actions for target is wrong").isNotEmpty();
assertThat(event.getActionId()).as("Action id in database and event do not match") assertThat(event.getActionId()).as("Action id in database and event do not match")
.isEqualTo(activeActionsByTarget.get(0).getId()); .isEqualTo(activeActionsByTarget.get(0).getId());

View File

@@ -29,6 +29,7 @@ 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.UnsupportedSoftwareModuleForThisDistributionSetException; import org.eclipse.hawkbit.repository.exception.UnsupportedSoftwareModuleForThisDistributionSetException;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetMetadata; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetMetadata;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType;
import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.Action.Status;
@@ -121,6 +122,12 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
() -> distributionSetManagement.assignTag(Lists.newArrayList(NOT_EXIST_IDL), dsTag.getId()), () -> distributionSetManagement.assignTag(Lists.newArrayList(NOT_EXIST_IDL), dsTag.getId()),
"DistributionSet"); "DistributionSet");
verifyThrownExceptionBy(() -> distributionSetManagement.findDistributionSetsByTag(PAGE, NOT_EXIST_IDL),
"DistributionSetTag");
verifyThrownExceptionBy(
() -> distributionSetManagement.findDistributionSetsByTag(PAGE, "name==*", NOT_EXIST_IDL),
"DistributionSetTag");
verifyThrownExceptionBy( verifyThrownExceptionBy(
() -> distributionSetManagement.toggleTagAssignment(Lists.newArrayList(NOT_EXIST_IDL), dsTag.getName()), () -> distributionSetManagement.toggleTagAssignment(Lists.newArrayList(NOT_EXIST_IDL), dsTag.getName()),
"DistributionSet"); "DistributionSet");
@@ -128,9 +135,6 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
() -> distributionSetManagement.toggleTagAssignment(Lists.newArrayList(set.getId()), NOT_EXIST_ID), () -> distributionSetManagement.toggleTagAssignment(Lists.newArrayList(set.getId()), NOT_EXIST_ID),
"DistributionSetTag"); "DistributionSetTag");
verifyThrownExceptionBy(() -> distributionSetManagement.unAssignAllDistributionSetsByTag(NOT_EXIST_IDL),
"DistributionSetTag");
verifyThrownExceptionBy(() -> distributionSetManagement.unAssignTag(set.getId(), NOT_EXIST_IDL), verifyThrownExceptionBy(() -> distributionSetManagement.unAssignTag(set.getId(), NOT_EXIST_IDL),
"DistributionSetTag"); "DistributionSetTag");
@@ -168,11 +172,11 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
"DistributionSet"); "DistributionSet");
verifyThrownExceptionBy( verifyThrownExceptionBy(
() -> distributionSetManagement.findDistributionSetMetadataByDistributionSetId(NOT_EXIST_IDL, pageReq), () -> distributionSetManagement.findDistributionSetMetadataByDistributionSetId(NOT_EXIST_IDL, PAGE),
"DistributionSet"); "DistributionSet");
verifyThrownExceptionBy(() -> distributionSetManagement verifyThrownExceptionBy(() -> distributionSetManagement
.findDistributionSetMetadataByDistributionSetId(NOT_EXIST_IDL, "name==*", pageReq), "DistributionSet"); .findDistributionSetMetadataByDistributionSetId(NOT_EXIST_IDL, "name==*", PAGE), "DistributionSet");
assertThatThrownBy(() -> distributionSetManagement.isDistributionSetInUse(NOT_EXIST_IDL)) assertThatThrownBy(() -> distributionSetManagement.isDistributionSetInUse(NOT_EXIST_IDL))
.isInstanceOf(EntityNotFoundException.class).hasMessageContaining(NOT_EXIST_ID) .isInstanceOf(EntityNotFoundException.class).hasMessageContaining(NOT_EXIST_ID)
@@ -390,28 +394,28 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
final List<DistributionSet> assignedDS = distributionSetManagement.assignTag(assignDS, tag.getId()); final List<DistributionSet> assignedDS = distributionSetManagement.assignTag(assignDS, tag.getId());
assertThat(assignedDS.size()).as("assigned ds has wrong size").isEqualTo(4); assertThat(assignedDS.size()).as("assigned ds has wrong size").isEqualTo(4);
assignedDS.forEach(ds -> assertThat(ds.getTags().size()).as("ds has wrong tag size").isEqualTo(1)); assignedDS.stream().map(c -> (JpaDistributionSet) c)
.forEach(ds -> assertThat(ds.getTags().size()).as("ds has wrong tag size").isEqualTo(1));
DistributionSetTag findDistributionSetTag = tagManagement.findDistributionSetTag("Tag1").get(); DistributionSetTag findDistributionSetTag = tagManagement.findDistributionSetTag("Tag1").get();
assertThat(assignedDS.size()).as("assigned ds has wrong size")
.isEqualTo(findDistributionSetTag.getAssignedToDistributionSet().size());
final DistributionSet unAssignDS = distributionSetManagement.unAssignTag(assignDS.get(0), assertThat(assignedDS.size()).as("assigned ds has wrong size").isEqualTo(
findDistributionSetTag.getId()); distributionSetManagement.findDistributionSetsByTag(PAGE, tag.getId()).getNumberOfElements());
final JpaDistributionSet unAssignDS = (JpaDistributionSet) distributionSetManagement
.unAssignTag(assignDS.get(0), findDistributionSetTag.getId());
assertThat(unAssignDS.getId()).as("unassigned ds is wrong").isEqualTo(assignDS.get(0)); assertThat(unAssignDS.getId()).as("unassigned ds is wrong").isEqualTo(assignDS.get(0));
assertThat(unAssignDS.getTags().size()).as("unassigned ds has wrong tag size").isEqualTo(0); assertThat(unAssignDS.getTags().size()).as("unassigned ds has wrong tag size").isEqualTo(0);
findDistributionSetTag = tagManagement.findDistributionSetTag("Tag1").get(); findDistributionSetTag = tagManagement.findDistributionSetTag("Tag1").get();
assertThat(findDistributionSetTag.getAssignedToDistributionSet().size()).as("ds tag ds has wrong ds size") assertThat(distributionSetManagement.findDistributionSetsByTag(PAGE, tag.getId()).getNumberOfElements())
.isEqualTo(3); .as("ds tag ds has wrong ds size").isEqualTo(3);
final List<DistributionSet> unAssignTargets = distributionSetManagement assertThat(distributionSetManagement
.unAssignAllDistributionSetsByTag(findDistributionSetTag.getId()); .findDistributionSetsByTag(PAGE, "name==" + unAssignDS.getName(), tag.getId()).getNumberOfElements())
findDistributionSetTag = tagManagement.findDistributionSetTag("Tag1").get(); .as("ds tag ds has wrong ds size").isEqualTo(0);
assertThat(findDistributionSetTag.getAssignedToDistributionSet().size()).as("ds tag has wrong ds size") assertThat(distributionSetManagement
.isEqualTo(0); .findDistributionSetsByTag(PAGE, "name!=" + unAssignDS.getName(), tag.getId()).getNumberOfElements())
assertThat(unAssignTargets.size()).as("unassigned target has wrong size").isEqualTo(3); .as("ds tag ds has wrong ds size").isEqualTo(3);
unAssignTargets
.forEach(target -> assertThat(target.getTags().size()).as("target has wrong tag size").isEqualTo(0));
} }
@Test @Test
@@ -559,14 +563,14 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
// target first only has an assigned DS-three so check order correct // target first only has an assigned DS-three so check order correct
final List<DistributionSet> tFirstPin = distributionSetManagement.findDistributionSetsAllOrderedByLinkTarget( final List<DistributionSet> tFirstPin = distributionSetManagement.findDistributionSetsAllOrderedByLinkTarget(
pageReq, distributionSetFilterBuilder, tFirst.getControllerId()).getContent(); PAGE, distributionSetFilterBuilder, tFirst.getControllerId()).getContent();
assertThat(tFirstPin.get(0)).isEqualTo(dsThree); assertThat(tFirstPin.get(0)).isEqualTo(dsThree);
assertThat(tFirstPin).hasSize(10); assertThat(tFirstPin).hasSize(10);
// target second has installed DS-2 and assigned DS-4 so check order // target second has installed DS-2 and assigned DS-4 so check order
// correct // correct
final List<DistributionSet> tSecondPin = distributionSetManagement.findDistributionSetsAllOrderedByLinkTarget( final List<DistributionSet> tSecondPin = distributionSetManagement.findDistributionSetsAllOrderedByLinkTarget(
pageReq, distributionSetFilterBuilder, tSecond.getControllerId()).getContent(); PAGE, distributionSetFilterBuilder, tSecond.getControllerId()).getContent();
assertThat(tSecondPin.get(0)).isEqualTo(dsSecond); assertThat(tSecondPin.get(0)).isEqualTo(dsSecond);
assertThat(tSecondPin.get(1)).isEqualTo(dsFour); assertThat(tSecondPin.get(1)).isEqualTo(dsFour);
assertThat(tFirstPin).hasSize(10); assertThat(tFirstPin).hasSize(10);
@@ -624,7 +628,7 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
expected.add(dsNewType); expected.add(dsNewType);
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, getDistributionSetFilterBuilder().build()).getContent()) .findDistributionSetsByFilters(PAGE, getDistributionSetFilterBuilder().build()).getContent())
.hasSize(203).containsOnly(expected.toArray(new DistributionSet[0])); .hasSize(203).containsOnly(expected.toArray(new DistributionSet[0]));
DistributionSetFilterBuilder distributionSetFilterBuilder; DistributionSetFilterBuilder distributionSetFilterBuilder;
@@ -632,11 +636,11 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
// search for not deleted // search for not deleted
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsDeleted(Boolean.TRUE); distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsDeleted(Boolean.TRUE);
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(1); .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(1);
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsDeleted(false); distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsDeleted(false);
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()) .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent())
.hasSize(202); .hasSize(202);
// search for completed // search for completed
@@ -648,61 +652,61 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(true); distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(true);
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(202) .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(202)
.containsOnly(expected.toArray(new DistributionSet[0])); .containsOnly(expected.toArray(new DistributionSet[0]));
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.FALSE); distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.FALSE);
expected = new ArrayList<>(); expected = new ArrayList<>();
expected.add(dsInComplete); expected.add(dsInComplete);
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(1) .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(1)
.containsOnly(expected.toArray(new DistributionSet[0])); .containsOnly(expected.toArray(new DistributionSet[0]));
// search for type // search for type
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setType(newType); distributionSetFilterBuilder = getDistributionSetFilterBuilder().setType(newType);
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(1); .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(1);
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setType(standardDsType); distributionSetFilterBuilder = getDistributionSetFilterBuilder().setType(standardDsType);
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()) .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent())
.hasSize(202); .hasSize(202);
// search for text // search for text
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setSearchText("%test2"); distributionSetFilterBuilder = getDistributionSetFilterBuilder().setSearchText("%test2");
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()) .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent())
.hasSize(100); .hasSize(100);
// search for tags // search for tags
distributionSetFilterBuilder = getDistributionSetFilterBuilder() distributionSetFilterBuilder = getDistributionSetFilterBuilder()
.setTagNames(Lists.newArrayList(dsTagA.getName())); .setTagNames(Lists.newArrayList(dsTagA.getName()));
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()) .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent())
.hasSize(200); .hasSize(200);
distributionSetFilterBuilder = getDistributionSetFilterBuilder() distributionSetFilterBuilder = getDistributionSetFilterBuilder()
.setTagNames(Lists.newArrayList(dsTagB.getName())); .setTagNames(Lists.newArrayList(dsTagB.getName()));
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()) .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent())
.hasSize(100); .hasSize(100);
distributionSetFilterBuilder = getDistributionSetFilterBuilder() distributionSetFilterBuilder = getDistributionSetFilterBuilder()
.setTagNames(Lists.newArrayList(dsTagA.getName(), dsTagB.getName())); .setTagNames(Lists.newArrayList(dsTagA.getName(), dsTagB.getName()));
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()) .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent())
.hasSize(200); .hasSize(200);
distributionSetFilterBuilder = getDistributionSetFilterBuilder() distributionSetFilterBuilder = getDistributionSetFilterBuilder()
.setTagNames(Lists.newArrayList(dsTagC.getName(), dsTagB.getName())); .setTagNames(Lists.newArrayList(dsTagC.getName(), dsTagB.getName()));
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()) .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent())
.hasSize(100); .hasSize(100);
distributionSetFilterBuilder = getDistributionSetFilterBuilder() distributionSetFilterBuilder = getDistributionSetFilterBuilder()
.setTagNames(Lists.newArrayList(dsTagC.getName())); .setTagNames(Lists.newArrayList(dsTagC.getName()));
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(0); .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(0);
// combine deleted and complete // combine deleted and complete
expected = new ArrayList<>(); expected = new ArrayList<>();
@@ -713,14 +717,14 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE) distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE)
.setIsDeleted(Boolean.FALSE); .setIsDeleted(Boolean.FALSE);
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(201) .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(201)
.containsOnly(expected.toArray(new DistributionSet[0])); .containsOnly(expected.toArray(new DistributionSet[0]));
expected = new ArrayList<>(); expected = new ArrayList<>();
expected.add(dsInComplete); expected.add(dsInComplete);
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.FALSE); distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.FALSE);
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(1) .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(1)
.containsOnly(expected.toArray(new DistributionSet[0])); .containsOnly(expected.toArray(new DistributionSet[0]));
expected = new ArrayList<>(); expected = new ArrayList<>();
@@ -728,13 +732,13 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE) distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE)
.setIsDeleted(Boolean.TRUE); .setIsDeleted(Boolean.TRUE);
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(1) .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(1)
.containsOnly(expected.toArray(new DistributionSet[0])); .containsOnly(expected.toArray(new DistributionSet[0]));
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsDeleted(Boolean.TRUE) distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsDeleted(Boolean.TRUE)
.setIsComplete(Boolean.FALSE); .setIsComplete(Boolean.FALSE);
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(0); .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(0);
// combine deleted and complete and type // combine deleted and complete and type
expected = new ArrayList<>(); expected = new ArrayList<>();
@@ -743,7 +747,7 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsDeleted(Boolean.FALSE) distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsDeleted(Boolean.FALSE)
.setIsComplete(Boolean.TRUE).setType(standardDsType); .setIsComplete(Boolean.TRUE).setType(standardDsType);
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(200) .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(200)
.containsOnly(expected.toArray(new DistributionSet[0])); .containsOnly(expected.toArray(new DistributionSet[0]));
expected = new ArrayList<>(); expected = new ArrayList<>();
@@ -751,19 +755,19 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE) distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE)
.setType(standardDsType).setIsDeleted(Boolean.TRUE); .setType(standardDsType).setIsDeleted(Boolean.TRUE);
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(1) .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(1)
.containsOnly(expected.toArray(new DistributionSet[0])); .containsOnly(expected.toArray(new DistributionSet[0]));
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsDeleted(Boolean.TRUE) distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsDeleted(Boolean.TRUE)
.setIsComplete(Boolean.FALSE).setType(standardDsType); .setIsComplete(Boolean.FALSE).setType(standardDsType);
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(0); .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(0);
expected = new ArrayList<>(); expected = new ArrayList<>();
expected.add(dsNewType); expected.add(dsNewType);
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE).setType(newType); distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE).setType(newType);
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(1) .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(1)
.containsOnly(expected.toArray(new DistributionSet[0])); .containsOnly(expected.toArray(new DistributionSet[0]));
// combine deleted and complete and type and text // combine deleted and complete and type and text
@@ -772,23 +776,23 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE) distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE)
.setType(standardDsType).setSearchText("%test2"); .setType(standardDsType).setSearchText("%test2");
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(100) .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(100)
.containsOnly(expected.toArray(new DistributionSet[0])); .containsOnly(expected.toArray(new DistributionSet[0]));
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE) distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE)
.setIsDeleted(Boolean.TRUE).setType(standardDsType).setSearchText("%test2"); .setIsDeleted(Boolean.TRUE).setType(standardDsType).setSearchText("%test2");
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(0); .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(0);
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setType(standardDsType).setSearchText("%test2") distributionSetFilterBuilder = getDistributionSetFilterBuilder().setType(standardDsType).setSearchText("%test2")
.setIsComplete(false).setIsDeleted(false); .setIsComplete(false).setIsDeleted(false);
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(0); .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(0);
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setType(newType).setSearchText("%test2") distributionSetFilterBuilder = getDistributionSetFilterBuilder().setType(newType).setSearchText("%test2")
.setIsComplete(Boolean.TRUE).setIsDeleted(false); .setIsComplete(Boolean.TRUE).setIsDeleted(false);
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(0); .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(0);
// combine deleted and complete and type and text and tag // combine deleted and complete and type and text and tag
expected = new ArrayList<>(); expected = new ArrayList<>();
@@ -796,14 +800,14 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(true).setType(standardDsType) distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(true).setType(standardDsType)
.setSearchText("%test2").setTagNames(Lists.newArrayList(dsTagA.getName())); .setSearchText("%test2").setTagNames(Lists.newArrayList(dsTagA.getName()));
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(100) .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(100)
.containsOnly(expected.toArray(new DistributionSet[0])); .containsOnly(expected.toArray(new DistributionSet[0]));
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setType(standardDsType).setSearchText("%test2") distributionSetFilterBuilder = getDistributionSetFilterBuilder().setType(standardDsType).setSearchText("%test2")
.setTagNames(Lists.newArrayList(dsTagA.getName())).setIsComplete(Boolean.FALSE) .setTagNames(Lists.newArrayList(dsTagA.getName())).setIsComplete(Boolean.FALSE)
.setIsDeleted(Boolean.FALSE); .setIsDeleted(Boolean.FALSE);
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(0); .findDistributionSetsByFilters(PAGE, distributionSetFilterBuilder.build()).getContent()).hasSize(0);
} }
@@ -816,7 +820,7 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
public void findDistributionSetsWithoutLazy() { public void findDistributionSetsWithoutLazy() {
testdataFactory.createDistributionSets(20); testdataFactory.createDistributionSets(20);
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true)) assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(PAGE, false, true))
.hasSize(20); .hasSize(20);
} }
@@ -832,7 +836,7 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
// not assigned so not marked as deleted but fully deleted // not assigned so not marked as deleted but fully deleted
assertThat(distributionSetRepository.findAll()).hasSize(1); assertThat(distributionSetRepository.findAll()).hasSize(1);
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByDeletedAndOrCompleted(pageReq, Boolean.FALSE, Boolean.TRUE).getTotalElements()) .findDistributionSetsByDeletedAndOrCompleted(PAGE, Boolean.FALSE, Boolean.TRUE).getTotalElements())
.isEqualTo(1); .isEqualTo(1);
} }
@@ -892,7 +896,7 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
// not assigned so not marked as deleted // not assigned so not marked as deleted
assertThat(distributionSetRepository.findAll()).hasSize(4); assertThat(distributionSetRepository.findAll()).hasSize(4);
assertThat(distributionSetManagement assertThat(distributionSetManagement
.findDistributionSetsByDeletedAndOrCompleted(pageReq, Boolean.FALSE, Boolean.TRUE).getTotalElements()) .findDistributionSetsByDeletedAndOrCompleted(PAGE, Boolean.FALSE, Boolean.TRUE).getTotalElements())
.isEqualTo(2); .isEqualTo(2);
} }
@@ -926,7 +930,7 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
testdataFactory.createDistributionSet("test" + i); testdataFactory.createDistributionSet("test" + i);
} }
final List<DistributionSet> foundDs = distributionSetManagement.findDistributionSetAllById(searchIds); final List<DistributionSet> foundDs = distributionSetManagement.findDistributionSetsById(searchIds);
assertThat(foundDs).hasSize(3); assertThat(foundDs).hasSize(3);

View File

@@ -0,0 +1,71 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository.jpa;
import static org.assertj.core.api.Assertions.assertThat;
import org.eclipse.hawkbit.repository.event.remote.RolloutDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.RolloutGroupCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.RolloutGroupUpdatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.RolloutUpdatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetCreatedEvent;
import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.junit.Test;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
@Features("Component Tests - Repository")
@Stories("Rollout Management")
public class RolloutGroupManagementTest extends AbstractJpaIntegrationTest {
@Test
@Description("Verifies that management get access reacts as specfied on calls for non existing entities by means "
+ "of Optional not present.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
public void nonExistingEntityAccessReturnsNotPresent() {
assertThat(rolloutGroupManagement.findRolloutGroupById(NOT_EXIST_IDL)).isNotPresent();
assertThat(rolloutGroupManagement.findRolloutGroupWithDetailedStatus(NOT_EXIST_IDL)).isNotPresent();
}
@Test
@Description("Verifies that management queries react as specfied on calls for non existing entities "
+ " by means of throwing EntityNotFoundException.")
@ExpectEvents({ @Expect(type = RolloutDeletedEvent.class, count = 0),
@Expect(type = RolloutGroupCreatedEvent.class, count = 10),
@Expect(type = RolloutGroupUpdatedEvent.class, count = 10),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = RolloutUpdatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 10) })
public void entityQueriesReferringToNotExistingEntitiesThrowsException() {
testdataFactory.createRollout("xxx");
verifyThrownExceptionBy(() -> rolloutGroupManagement.countRolloutGroupsByRolloutId(NOT_EXIST_IDL), "Rollout");
verifyThrownExceptionBy(() -> rolloutGroupManagement.countTargetsOfRolloutsGroup(NOT_EXIST_IDL),
"RolloutGroup");
verifyThrownExceptionBy(
() -> rolloutGroupManagement.findAllRolloutGroupsWithDetailedStatus(NOT_EXIST_IDL, PAGE), "Rollout");
verifyThrownExceptionBy(() -> rolloutGroupManagement.findAllTargetsWithActionStatus(PAGE, NOT_EXIST_IDL),
"RolloutGroup");
verifyThrownExceptionBy(() -> rolloutGroupManagement.findRolloutGroupsAll(NOT_EXIST_IDL, "name==*", PAGE),
"Rollout");
verifyThrownExceptionBy(() -> rolloutGroupManagement.findRolloutGroupTargets(NOT_EXIST_IDL, PAGE),
"RolloutGroup");
verifyThrownExceptionBy(() -> rolloutGroupManagement.findRolloutGroupTargets(NOT_EXIST_IDL, "name==*", PAGE),
"RolloutGroup");
}
}

View File

@@ -10,9 +10,9 @@ package org.eclipse.hawkbit.repository.jpa;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.fail;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@@ -36,7 +36,6 @@ 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.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.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.EntityReadOnlyException; import org.eclipse.hawkbit.repository.exception.EntityReadOnlyException;
import org.eclipse.hawkbit.repository.exception.RolloutIllegalStateException; import org.eclipse.hawkbit.repository.exception.RolloutIllegalStateException;
import org.eclipse.hawkbit.repository.jpa.model.JpaAction; import org.eclipse.hawkbit.repository.jpa.model.JpaAction;
@@ -103,7 +102,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
// verify that manually created action is still running and action // verify that manually created action is still running and action
// created from rollout is finished // created from rollout is finished
final List<Action> actionsByKnownTarget = deploymentManagement.findActionsByTarget(knownControllerId, pageReq) final List<Action> actionsByKnownTarget = deploymentManagement.findActionsByTarget(knownControllerId, PAGE)
.getContent(); .getContent();
// should be 2 actions, one manually and one from the rollout // should be 2 actions, one manually and one from the rollout
assertThat(actionsByKnownTarget).hasSize(2); assertThat(actionsByKnownTarget).hasSize(2);
@@ -164,7 +163,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
// verify the split of the target and targetGroup // verify the split of the target and targetGroup
final Page<RolloutGroup> rolloutGroups = rolloutGroupManagement final Page<RolloutGroup> rolloutGroups = rolloutGroupManagement
.findRolloutGroupsByRolloutId(createdRollout.getId(), pageReq); .findRolloutGroupsByRolloutId(createdRollout.getId(), PAGE);
// we have total of #amountTargetsForRollout in rollouts splitted in // we have total of #amountTargetsForRollout in rollouts splitted in
// group size #groupSize // group size #groupSize
assertThat(rolloutGroups).hasSize(amountGroups); assertThat(rolloutGroups).hasSize(amountGroups);
@@ -279,7 +278,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
@Step("Finish three actions of the rollout group and delete two targets") @Step("Finish three actions of the rollout group and delete two targets")
private void finishActionAndDeleteTargetsOfFirstRunningGroup(final Rollout createdRollout) { private void finishActionAndDeleteTargetsOfFirstRunningGroup(final Rollout createdRollout) {
// finish group one by finishing targets and deleting targets // finish group one by finishing targets and deleting targets
final Slice<JpaAction> runningActionsSlice = actionRepository.findByRolloutIdAndStatus(pageReq, final Slice<JpaAction> runningActionsSlice = actionRepository.findByRolloutIdAndStatus(PAGE,
createdRollout.getId(), Status.RUNNING); createdRollout.getId(), Status.RUNNING);
final List<JpaAction> runningActions = Lists.newArrayList(runningActionsSlice.iterator()); final List<JpaAction> runningActions = Lists.newArrayList(runningActionsSlice.iterator());
finishAction(runningActions.get(0)); finishAction(runningActions.get(0));
@@ -301,7 +300,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
@Step("Finish one action of the rollout group and delete four targets") @Step("Finish one action of the rollout group and delete four targets")
private void finishActionAndDeleteTargetsOfSecondRunningGroup(final Rollout createdRollout) { private void finishActionAndDeleteTargetsOfSecondRunningGroup(final Rollout createdRollout) {
final Slice<JpaAction> runningActionsSlice = actionRepository.findByRolloutIdAndStatus(pageReq, final Slice<JpaAction> runningActionsSlice = actionRepository.findByRolloutIdAndStatus(PAGE,
createdRollout.getId(), Status.RUNNING); createdRollout.getId(), Status.RUNNING);
final List<JpaAction> runningActions = Lists.newArrayList(runningActionsSlice.iterator()); final List<JpaAction> runningActions = Lists.newArrayList(runningActionsSlice.iterator());
finishAction(runningActions.get(0)); finishAction(runningActions.get(0));
@@ -313,7 +312,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
@Step("Delete all targets of the rollout group") @Step("Delete all targets of the rollout group")
private void deleteAllTargetsFromThirdGroup(final Rollout createdRollout) { private void deleteAllTargetsFromThirdGroup(final Rollout createdRollout) {
final Slice<JpaAction> runningActionsSlice = actionRepository.findByRolloutIdAndStatus(pageReq, final Slice<JpaAction> runningActionsSlice = actionRepository.findByRolloutIdAndStatus(PAGE,
createdRollout.getId(), Status.SCHEDULED); createdRollout.getId(), Status.SCHEDULED);
final List<JpaAction> runningActions = Lists.newArrayList(runningActionsSlice.iterator()); final List<JpaAction> runningActions = Lists.newArrayList(runningActionsSlice.iterator());
targetManagement.deleteTargets(Lists.newArrayList(runningActions.get(0).getTarget().getId(), targetManagement.deleteTargets(Lists.newArrayList(runningActions.get(0).getTarget().getId(),
@@ -325,7 +324,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
private void verifyRolloutAndAllGroupsAreFinished(final Rollout createdRollout) { private void verifyRolloutAndAllGroupsAreFinished(final Rollout createdRollout) {
rolloutManagement.handleRollouts(); rolloutManagement.handleRollouts();
final List<RolloutGroup> runningRolloutGroups = rolloutGroupManagement final List<RolloutGroup> runningRolloutGroups = rolloutGroupManagement
.findRolloutGroupsByRolloutId(createdRollout.getId(), pageReq).getContent(); .findRolloutGroupsByRolloutId(createdRollout.getId(), PAGE).getContent();
assertThat(runningRolloutGroups.get(0).getStatus()).isEqualTo(RolloutGroupStatus.FINISHED); assertThat(runningRolloutGroups.get(0).getStatus()).isEqualTo(RolloutGroupStatus.FINISHED);
assertThat(runningRolloutGroups.get(1).getStatus()).isEqualTo(RolloutGroupStatus.FINISHED); assertThat(runningRolloutGroups.get(1).getStatus()).isEqualTo(RolloutGroupStatus.FINISHED);
assertThat(runningRolloutGroups.get(2).getStatus()).isEqualTo(RolloutGroupStatus.FINISHED); assertThat(runningRolloutGroups.get(2).getStatus()).isEqualTo(RolloutGroupStatus.FINISHED);
@@ -589,7 +588,8 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
// round(5/2)=3 targets SCHEDULED (Group 3) // round(5/2)=3 targets SCHEDULED (Group 3)
// round(2/1)=2 targets SCHEDULED (Group 4) // round(2/1)=2 targets SCHEDULED (Group 4)
createdRollout = rolloutManagement.findRolloutById(createdRollout.getId()).get(); createdRollout = rolloutManagement.findRolloutById(createdRollout.getId()).get();
final List<RolloutGroup> rolloutGroups = createdRollout.getRolloutGroups(); final List<RolloutGroup> rolloutGroups = rolloutGroupManagement
.findRolloutGroupsByRolloutId(createdRollout.getId(), PAGE).getContent();
Map<TotalTargetCountStatus.Status, Long> expectedTargetCountStatus = createInitStatusMap(); Map<TotalTargetCountStatus.Status, Long> expectedTargetCountStatus = createInitStatusMap();
expectedTargetCountStatus.put(TotalTargetCountStatus.Status.FINISHED, 2L); expectedTargetCountStatus.put(TotalTargetCountStatus.Status.FINISHED, 2L);
@@ -628,9 +628,10 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(runningActions.size()).isEqualTo(5); assertThat(runningActions.size()).isEqualTo(5);
// 5 targets are in the group and the DS has been assigned // 5 targets are in the group and the DS has been assigned
final List<RolloutGroup> rolloutGroups = createdRollout.getRolloutGroups(); final List<RolloutGroup> rolloutGroups = rolloutGroupManagement
.findRolloutGroupsByRolloutId(createdRollout.getId(), PAGE).getContent();
final Page<Target> targets = rolloutGroupManagement.findRolloutGroupTargets(rolloutGroups.get(0).getId(), final Page<Target> targets = rolloutGroupManagement.findRolloutGroupTargets(rolloutGroups.get(0).getId(),
pageReq); PAGE);
final List<Target> targetList = targets.getContent(); final List<Target> targetList = targets.getContent();
assertThat(targetList.size()).isEqualTo(5); assertThat(targetList.size()).isEqualTo(5);
@@ -742,7 +743,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
expectedTargetCountStatus.put(TotalTargetCountStatus.Status.FINISHED, 9L); expectedTargetCountStatus.put(TotalTargetCountStatus.Status.FINISHED, 9L);
validateRolloutActionStatus(rolloutTwo.getId(), expectedTargetCountStatus); validateRolloutActionStatus(rolloutTwo.getId(), expectedTargetCountStatus);
changeStatusForAllRunningActions(rolloutTwo, Status.FINISHED); changeStatusForAllRunningActions(rolloutTwo, Status.FINISHED);
final Page<Target> targetPage = targetManagement.findTargetByUpdateStatus(pageReq, TargetUpdateStatus.IN_SYNC); final Page<Target> targetPage = targetManagement.findTargetByUpdateStatus(PAGE, TargetUpdateStatus.IN_SYNC);
final List<Target> targetList = targetPage.getContent(); final List<Target> targetList = targetPage.getContent();
// 15 targets in finished/IN_SYNC status and same DS assigned // 15 targets in finished/IN_SYNC status and same DS assigned
assertThat(targetList.size()).isEqualTo(amountTargetsForRollout); assertThat(targetList.size()).isEqualTo(amountTargetsForRollout);
@@ -767,7 +768,8 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
changeStatusForRunningActions(rolloutOne, Status.FINISHED, 3); changeStatusForRunningActions(rolloutOne, Status.FINISHED, 3);
rolloutManagement.handleRollouts(); rolloutManagement.handleRollouts();
// verify: 40% error but 60% finished -> should move to next group // verify: 40% error but 60% finished -> should move to next group
final List<RolloutGroup> rolloutGruops = rolloutOne.getRolloutGroups(); final List<RolloutGroup> rolloutGruops = rolloutGroupManagement
.findRolloutGroupsByRolloutId(rolloutOne.getId(), PAGE).getContent();
final Map<TotalTargetCountStatus.Status, Long> expectedTargetCountStatus = createInitStatusMap(); final Map<TotalTargetCountStatus.Status, Long> expectedTargetCountStatus = createInitStatusMap();
expectedTargetCountStatus.put(TotalTargetCountStatus.Status.RUNNING, 5L); expectedTargetCountStatus.put(TotalTargetCountStatus.Status.RUNNING, 5L);
validateRolloutGroupActionStatus(rolloutGruops.get(1), expectedTargetCountStatus); validateRolloutGroupActionStatus(rolloutGruops.get(1), expectedTargetCountStatus);
@@ -792,8 +794,8 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
rolloutManagement.handleRollouts(); rolloutManagement.handleRollouts();
// verify: 40% error and 60% finished -> should not move to next group // verify: 40% error and 60% finished -> should not move to next group
// because successCondition 80% // because successCondition 80%
rolloutOne = rolloutManagement.findRolloutById(rolloutOne.getId()).get(); final List<RolloutGroup> rolloutGruops = rolloutGroupManagement
final List<RolloutGroup> rolloutGruops = rolloutOne.getRolloutGroups(); .findRolloutGroupsByRolloutId(rolloutOne.getId(), PAGE).getContent();
final Map<TotalTargetCountStatus.Status, Long> expectedTargetCountStatus = createInitStatusMap(); final Map<TotalTargetCountStatus.Status, Long> expectedTargetCountStatus = createInitStatusMap();
expectedTargetCountStatus.put(TotalTargetCountStatus.Status.SCHEDULED, 5L); expectedTargetCountStatus.put(TotalTargetCountStatus.Status.SCHEDULED, 5L);
validateRolloutGroupActionStatus(rolloutGruops.get(1), expectedTargetCountStatus); validateRolloutGroupActionStatus(rolloutGruops.get(1), expectedTargetCountStatus);
@@ -1000,14 +1002,17 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
myRollout = rolloutManagement.findRolloutById(myRollout.getId()).get(); myRollout = rolloutManagement.findRolloutById(myRollout.getId()).get();
float percent = rolloutGroupManagement float percent = rolloutGroupManagement
.findRolloutGroupWithDetailedStatus(myRollout.getRolloutGroups().get(0).getId()).get() .findRolloutGroupWithDetailedStatus(rolloutGroupManagement
.getTotalTargetCountStatus().getFinishedPercent(); .findRolloutGroupsByRolloutId(myRollout.getId(), PAGE).getContent().get(0).getId())
.get().getTotalTargetCountStatus().getFinishedPercent();
assertThat(percent).isEqualTo(40); assertThat(percent).isEqualTo(40);
changeStatusForRunningActions(myRollout, Status.FINISHED, 3); changeStatusForRunningActions(myRollout, Status.FINISHED, 3);
rolloutManagement.handleRollouts(); rolloutManagement.handleRollouts();
percent = rolloutGroupManagement.findRolloutGroupWithDetailedStatus(myRollout.getRolloutGroups().get(0).getId()) percent = rolloutGroupManagement
.findRolloutGroupWithDetailedStatus(rolloutGroupManagement
.findRolloutGroupsByRolloutId(myRollout.getId(), PAGE).getContent().get(0).getId())
.get().getTotalTargetCountStatus().getFinishedPercent(); .get().getTotalTargetCountStatus().getFinishedPercent();
assertThat(percent).isEqualTo(100); assertThat(percent).isEqualTo(100);
@@ -1015,7 +1020,9 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
changeStatusForAllRunningActions(myRollout, Status.ERROR); changeStatusForAllRunningActions(myRollout, Status.ERROR);
rolloutManagement.handleRollouts(); rolloutManagement.handleRollouts();
percent = rolloutGroupManagement.findRolloutGroupWithDetailedStatus(myRollout.getRolloutGroups().get(1).getId()) percent = rolloutGroupManagement
.findRolloutGroupWithDetailedStatus(rolloutGroupManagement
.findRolloutGroupsByRolloutId(myRollout.getId(), PAGE).getContent().get(1).getId())
.get().getTotalTargetCountStatus().getFinishedPercent(); .get().getTotalTargetCountStatus().getFinishedPercent();
assertThat(percent).isEqualTo(80); assertThat(percent).isEqualTo(80);
} }
@@ -1043,7 +1050,8 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
rolloutManagement.handleRollouts(); rolloutManagement.handleRollouts();
myRollout = rolloutManagement.findRolloutById(myRollout.getId()).get(); myRollout = rolloutManagement.findRolloutById(myRollout.getId()).get();
final List<RolloutGroup> rolloutGroups = myRollout.getRolloutGroups(); final List<RolloutGroup> rolloutGroups = rolloutGroupManagement
.findRolloutGroupsByRolloutId(myRollout.getId(), PAGE).getContent();
Page<Target> targetPage = rolloutGroupManagement.findRolloutGroupTargets(rolloutGroups.get(0).getId(), Page<Target> targetPage = rolloutGroupManagement.findRolloutGroupTargets(rolloutGroups.get(0).getId(),
rsqlParam, new OffsetBasedPageRequest(0, 100, new Sort(Direction.ASC, "controllerId"))); rsqlParam, new OffsetBasedPageRequest(0, 100, new Sort(Direction.ASC, "controllerId")));
@@ -1075,13 +1083,10 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
final DistributionSet distributionSet = testdataFactory.createDistributionSet("dsFor" + rolloutName); final DistributionSet distributionSet = testdataFactory.createDistributionSet("dsFor" + rolloutName);
try { assertThatExceptionOfType(ConstraintViolationException.class)
testdataFactory.createRolloutByVariables(rolloutName, "desc", amountGroups, "id==notExisting", .isThrownBy(() -> testdataFactory.createRolloutByVariables(rolloutName, "desc", amountGroups,
distributionSet, successCondition, errorCondition); "id==notExisting", distributionSet, successCondition, errorCondition))
fail("Was able to create a Rollout without targets."); .withMessageContaining("does not match any existing");
} catch (final ConstraintViolationException e) {
// OK
}
} }
@@ -1100,14 +1105,10 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
testdataFactory.createRolloutByVariables(rolloutName, "desc", amountGroups, "id==dup-ro-*", distributionSet, testdataFactory.createRolloutByVariables(rolloutName, "desc", amountGroups, "id==dup-ro-*", distributionSet,
successCondition, errorCondition); successCondition, errorCondition);
try { assertThatExceptionOfType(EntityAlreadyExistsException.class)
testdataFactory.createRolloutByVariables(rolloutName, "desc", amountGroups, "id==dup-ro-*", distributionSet, .isThrownBy(() -> testdataFactory.createRolloutByVariables(rolloutName, "desc", amountGroups,
successCondition, errorCondition); "id==dup-ro-*", distributionSet, successCondition, errorCondition))
fail("Was able to create a duplicate Rollout."); .withMessageContaining("already exists in database");
} catch (final EntityAlreadyExistsException e) {
// OK
}
} }
@Test @Test
@@ -1127,7 +1128,9 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.READY); assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.READY);
final List<RolloutGroup> groups = myRollout.getRolloutGroups(); final List<RolloutGroup> groups = rolloutGroupManagement
.findRolloutGroupsByRolloutId(myRollout.getId(), PAGE).getContent();
assertThat(groups.get(0).getStatus()).isEqualTo(RolloutGroupStatus.READY); assertThat(groups.get(0).getStatus()).isEqualTo(RolloutGroupStatus.READY);
assertThat(groups.get(0).getTotalTargets()).isEqualTo(1); assertThat(groups.get(0).getTotalTargets()).isEqualTo(1);
assertThat(groups.get(1).getStatus()).isEqualTo(RolloutGroupStatus.READY); assertThat(groups.get(1).getStatus()).isEqualTo(RolloutGroupStatus.READY);
@@ -1282,7 +1285,8 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
myRollout = rolloutManagement.findRolloutById(myRollout.getId()).get(); myRollout = rolloutManagement.findRolloutById(myRollout.getId()).get();
assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.CREATING); assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.CREATING);
for (final RolloutGroup group : myRollout.getRolloutGroups()) { for (final RolloutGroup group : rolloutGroupManagement.findRolloutGroupsByRolloutId(myRollout.getId(), PAGE)
.getContent()) {
assertThat(group.getStatus()).isEqualTo(RolloutGroupStatus.CREATING); assertThat(group.getStatus()).isEqualTo(RolloutGroupStatus.CREATING);
} }
@@ -1297,7 +1301,9 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.READY); assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.READY);
assertThat(myRollout.getTotalTargets()).isEqualTo(amountTargetsInGroup1and2 + amountTargetsInGroup1); assertThat(myRollout.getTotalTargets()).isEqualTo(amountTargetsInGroup1and2 + amountTargetsInGroup1);
final List<RolloutGroup> groups = myRollout.getRolloutGroups(); final List<RolloutGroup> groups = rolloutGroupManagement
.findRolloutGroupsByRolloutId(myRollout.getId(), PAGE).getContent();
;
assertThat(groups.get(0).getStatus()).isEqualTo(RolloutGroupStatus.READY); assertThat(groups.get(0).getStatus()).isEqualTo(RolloutGroupStatus.READY);
assertThat(groups.get(0).getTotalTargets()).isEqualTo(amountTargetsInGroup1); assertThat(groups.get(0).getTotalTargets()).isEqualTo(amountTargetsInGroup1);
@@ -1324,12 +1330,9 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
rolloutGroups.add(generateRolloutGroup(0, percentTargetsInGroup1, null)); rolloutGroups.add(generateRolloutGroup(0, percentTargetsInGroup1, null));
rolloutGroups.add(generateRolloutGroup(1, percentTargetsInGroup2, null)); rolloutGroups.add(generateRolloutGroup(1, percentTargetsInGroup2, null));
try { assertThatExceptionOfType(ConstraintViolationException.class)
rolloutManagement.createRollout(myRollout, rolloutGroups, conditions); .isThrownBy(() -> rolloutManagement.createRollout(myRollout, rolloutGroups, conditions))
fail("Was able to create a Rollout with groups that are not addressing all targets"); .withMessageContaining("groups don't match");
} catch (final ConstraintViolationException e) {
// OK
}
} }
@@ -1344,16 +1347,13 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
final RolloutGroupConditions conditions = new RolloutGroupConditionBuilder().withDefaults().build(); final RolloutGroupConditions conditions = new RolloutGroupConditionBuilder().withDefaults().build();
final RolloutCreate myRollout = generateTargetsAndRollout(rolloutName, amountTargetsForRollout); final RolloutCreate myRollout = generateTargetsAndRollout(rolloutName, amountTargetsForRollout);
final List<RolloutGroupCreate> rolloutGroups = new ArrayList<>(2); final List<RolloutGroupCreate> rolloutGroups = Arrays.asList(
rolloutGroups.add(generateRolloutGroup(0, percentTargetsInGroup1, null)); generateRolloutGroup(0, percentTargetsInGroup1, null),
rolloutGroups.add(generateRolloutGroup(1, percentTargetsInGroup2, null)); generateRolloutGroup(1, percentTargetsInGroup2, null));
try { assertThatExceptionOfType(ConstraintViolationException.class)
rolloutManagement.createRollout(myRollout, rolloutGroups, conditions); .isThrownBy(() -> rolloutManagement.createRollout(myRollout, rolloutGroups, conditions))
fail("Was able to create a Rollout with groups that have illegal percentages"); .withMessageContaining("percentage has to be between 1 and 100");
} catch (final ConstraintViolationException e) {
// OK
}
} }
@@ -1367,59 +1367,12 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
final RolloutGroupConditions conditions = new RolloutGroupConditionBuilder().withDefaults().build(); final RolloutGroupConditions conditions = new RolloutGroupConditionBuilder().withDefaults().build();
final RolloutCreate myRollout = generateTargetsAndRollout(rolloutName, amountTargetsForRollout); final RolloutCreate myRollout = generateTargetsAndRollout(rolloutName, amountTargetsForRollout);
try { assertThatExceptionOfType(ConstraintViolationException.class)
rolloutManagement.createRollout(myRollout, illegalGroupAmount, conditions); .isThrownBy(() -> rolloutManagement.createRollout(myRollout, illegalGroupAmount, conditions))
fail("Was able to create a Rollout with too many groups"); .withMessageContaining("not be greater than " + quotaManagement.getMaxRolloutGroupsPerRollout());
} catch (final ConstraintViolationException e) {
// OK
}
} }
@Test
@Description("Verify Exception when a Rollout groups are queried for rollout that does not exist.")
public void findRolloutGroupsForRolloutThatDoesNotExist() throws Exception {
try {
rolloutGroupManagement.findAllRolloutGroupsWithDetailedStatus(1234L, pageReq);
fail("Was able to get Rollout group for rollout that does not exist.");
} catch (final EntityNotFoundException e) {
// OK
}
}
@Test
@Description("Verify Exception when targets are queried for rollout group that does not exist.")
public void findRolloutGroupTargetsForGroupThatDoesNotExist() throws Exception {
try {
rolloutGroupManagement.findRolloutGroupTargets(1234L, pageReq);
fail("Was able to get Rollout group targets for rollout group that does not exist.");
} catch (final EntityNotFoundException e) {
// OK
}
}
@Test
@Description("Verify Exception when targets are queried for rollout group that does not exist.")
public void findRolloutGroupTargetWithActionsForGroupThatDoesNotExist() throws Exception {
try {
rolloutGroupManagement.findAllTargetsWithActionStatus(pageReq, 1234L);
fail("Was able to get Rollout group targets for rollout group that does not exist.");
} catch (final EntityNotFoundException e) {
// OK
}
}
@Test
@Description("Verify Exception when targets are counted for rollout group that does not exist.")
public void countRolloutGroupTargetWithActionsForGroupThatDoesNotExist() throws Exception {
try {
rolloutGroupManagement.countTargetsOfRolloutsGroup(1234L);
fail("Was able to count Rollout group targets for rollout group that does not exist.");
} catch (final EntityNotFoundException e) {
// OK
}
}
@Test @Test
@Description("Verify the start of a Rollout does not work during creation phase.") @Description("Verify the start of a Rollout does not work during creation phase.")
public void createAndStartRolloutDuringCreationFails() throws Exception { public void createAndStartRolloutDuringCreationFails() throws Exception {
@@ -1445,12 +1398,10 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.CREATING); assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.CREATING);
try { final Long rolloutId = myRollout.getId();
rolloutManagement.startRollout(myRollout.getId()); assertThatExceptionOfType(RolloutIllegalStateException.class)
fail("Was able to start a Rollout in CREATING status"); .isThrownBy(() -> rolloutManagement.startRollout(rolloutId))
} catch (final RolloutIllegalStateException e) { .withMessageContaining("can only be started in state ready");
// OK
}
} }
@@ -1506,7 +1457,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
rolloutManagement.handleRollouts(); rolloutManagement.handleRollouts();
// verify we have running actions // verify we have running actions
assertThat(actionRepository.findByRolloutIdAndStatus(pageReq, createdRollout.getId(), Status.RUNNING) assertThat(actionRepository.findByRolloutIdAndStatus(PAGE, createdRollout.getId(), Status.RUNNING)
.getNumberOfElements()).isEqualTo(2); .getNumberOfElements()).isEqualTo(2);
// test // test
@@ -1523,16 +1474,16 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest {
.updateRollout(entityFactory.rollout().update(createdRollout.getId()).description("test"))) .updateRollout(entityFactory.rollout().update(createdRollout.getId()).description("test")))
.withMessageContaining("" + createdRollout.getId()); .withMessageContaining("" + createdRollout.getId());
assertThat(rolloutManagement.findAll(pageReq, true).getContent()).hasSize(1); assertThat(rolloutManagement.findAll(PAGE, true).getContent()).hasSize(1);
assertThat(rolloutManagement.findAll(pageReq, false).getContent()).hasSize(0); assertThat(rolloutManagement.findAll(PAGE, false).getContent()).hasSize(0);
assertThat(rolloutGroupManagement.findAllRolloutGroupsWithDetailedStatus(createdRollout.getId(), pageReq) assertThat(rolloutGroupManagement.findAllRolloutGroupsWithDetailedStatus(createdRollout.getId(), PAGE)
.getContent()).hasSize(amountGroups); .getContent()).hasSize(amountGroups);
// verify that all scheduled actions are deleted // verify that all scheduled actions are deleted
assertThat(actionRepository.findByRolloutIdAndStatus(pageReq, deletedRollout.getId(), Status.SCHEDULED) assertThat(actionRepository.findByRolloutIdAndStatus(PAGE, deletedRollout.getId(), Status.SCHEDULED)
.getNumberOfElements()).isEqualTo(0); .getNumberOfElements()).isEqualTo(0);
// verify that all running actions keep running // verify that all running actions keep running
assertThat(actionRepository.findByRolloutIdAndStatus(pageReq, deletedRollout.getId(), Status.RUNNING) assertThat(actionRepository.findByRolloutIdAndStatus(PAGE, deletedRollout.getId(), Status.RUNNING)
.getNumberOfElements()).isEqualTo(2); .getNumberOfElements()).isEqualTo(2);
} }

View File

@@ -112,7 +112,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
verifyThrownExceptionBy(() -> softwareManagement.deleteSoftwareModuleType(NOT_EXIST_IDL), "SoftwareModuleType"); verifyThrownExceptionBy(() -> softwareManagement.deleteSoftwareModuleType(NOT_EXIST_IDL), "SoftwareModuleType");
verifyThrownExceptionBy(() -> softwareManagement.findSoftwareModuleByAssignedTo(pageReq, NOT_EXIST_IDL), verifyThrownExceptionBy(() -> softwareManagement.findSoftwareModuleByAssignedTo(PAGE, NOT_EXIST_IDL),
"DistributionSet"); "DistributionSet");
verifyThrownExceptionBy( verifyThrownExceptionBy(
@@ -122,11 +122,12 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
verifyThrownExceptionBy(() -> softwareManagement.findSoftwareModuleMetadata(NOT_EXIST_IDL, NOT_EXIST_ID), verifyThrownExceptionBy(() -> softwareManagement.findSoftwareModuleMetadata(NOT_EXIST_IDL, NOT_EXIST_ID),
"SoftwareModule"); "SoftwareModule");
verifyThrownExceptionBy(() -> softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(NOT_EXIST_IDL), verifyThrownExceptionBy(
() -> softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(PAGE, NOT_EXIST_IDL),
"SoftwareModule"); "SoftwareModule");
verifyThrownExceptionBy(() -> softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(NOT_EXIST_IDL, verifyThrownExceptionBy(() -> softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(NOT_EXIST_IDL,
"name==*", pageReq), "SoftwareModule"); "name==*", PAGE), "SoftwareModule");
verifyThrownExceptionBy(() -> softwareManagement.findSoftwareModulesByType(pageReq, NOT_EXIST_IDL), verifyThrownExceptionBy(() -> softwareManagement.findSoftwareModulesByType(PAGE, NOT_EXIST_IDL),
"SoftwareModule"); "SoftwareModule");
verifyThrownExceptionBy( verifyThrownExceptionBy(
@@ -241,29 +242,29 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
ds = (JpaDistributionSet) assignSet(target, ds).getDistributionSet(); ds = (JpaDistributionSet) assignSet(target, ds).getDistributionSet();
// standard searches // standard searches
assertThat(softwareManagement.findSoftwareModuleByFilters(pageReq, "poky", osType.getId()).getContent()) assertThat(softwareManagement.findSoftwareModuleByFilters(PAGE, "poky", osType.getId()).getContent())
.hasSize(1); .hasSize(1);
assertThat(softwareManagement.findSoftwareModuleByFilters(pageReq, "poky", osType.getId()).getContent().get(0)) assertThat(softwareManagement.findSoftwareModuleByFilters(PAGE, "poky", osType.getId()).getContent().get(0))
.isEqualTo(os); .isEqualTo(os);
assertThat(softwareManagement.findSoftwareModuleByFilters(pageReq, "oracle%", runtimeType.getId()).getContent()) assertThat(softwareManagement.findSoftwareModuleByFilters(PAGE, "oracle%", runtimeType.getId()).getContent())
.hasSize(1); .hasSize(1);
assertThat(softwareManagement.findSoftwareModuleByFilters(pageReq, "oracle%", runtimeType.getId()).getContent() assertThat(softwareManagement.findSoftwareModuleByFilters(PAGE, "oracle%", runtimeType.getId()).getContent()
.get(0)).isEqualTo(jvm); .get(0)).isEqualTo(jvm);
assertThat(softwareManagement.findSoftwareModuleByFilters(pageReq, "1.0.1", appType.getId()).getContent()) assertThat(softwareManagement.findSoftwareModuleByFilters(PAGE, "1.0.1", appType.getId()).getContent())
.hasSize(1); .hasSize(1);
assertThat( assertThat(
softwareManagement.findSoftwareModuleByFilters(pageReq, "1.0.1", appType.getId()).getContent().get(0)) softwareManagement.findSoftwareModuleByFilters(PAGE, "1.0.1", appType.getId()).getContent().get(0))
.isEqualTo(ah); .isEqualTo(ah);
assertThat(softwareManagement.findSoftwareModuleByFilters(pageReq, "1.0%", appType.getId()).getContent()) assertThat(softwareManagement.findSoftwareModuleByFilters(PAGE, "1.0%", appType.getId()).getContent())
.hasSize(2); .hasSize(2);
// no we search with on entity marked as deleted // no we search with on entity marked as deleted
softwareManagement.deleteSoftwareModule( softwareManagement.deleteSoftwareModule(
softwareModuleRepository.findByAssignedToAndType(pageReq, ds, appType).getContent().get(0).getId()); softwareModuleRepository.findByAssignedToAndType(PAGE, ds, appType).getContent().get(0).getId());
assertThat(softwareManagement.findSoftwareModuleByFilters(pageReq, "1.0%", appType.getId()).getContent()) assertThat(softwareManagement.findSoftwareModuleByFilters(PAGE, "1.0%", appType.getId()).getContent())
.hasSize(1); .hasSize(1);
assertThat(softwareManagement.findSoftwareModuleByFilters(pageReq, "1.0%", appType.getId()).getContent().get(0)) assertThat(softwareManagement.findSoftwareModuleByFilters(PAGE, "1.0%", appType.getId()).getContent().get(0))
.isEqualTo(ah); .isEqualTo(ah);
} }
@@ -272,7 +273,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetManagement.findTargetByControllerID(target.getControllerId()).get().getUpdateStatus()) assertThat(targetManagement.findTargetByControllerID(target.getControllerId()).get().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.PENDING); .isEqualTo(TargetUpdateStatus.PENDING);
assertThat(deploymentManagement.getAssignedDistributionSet(target.getControllerId()).get()).isEqualTo(ds); assertThat(deploymentManagement.getAssignedDistributionSet(target.getControllerId()).get()).isEqualTo(ds);
final Action action = actionRepository.findByTargetAndDistributionSet(pageReq, target, ds).getContent().get(0); final Action action = actionRepository.findByTargetAndDistributionSet(PAGE, target, ds).getContent().get(0);
assertThat(action).isNotNull(); assertThat(action).isNotNull();
return action; return action;
} }
@@ -297,7 +298,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
softwareManagement.deleteSoftwareModule(testdataFactory.createSoftwareModuleOs("deleted").getId()); softwareManagement.deleteSoftwareModule(testdataFactory.createSoftwareModuleOs("deleted").getId());
testdataFactory.createSoftwareModuleApp(); testdataFactory.createSoftwareModuleApp();
assertThat(softwareManagement.findSoftwareModulesByType(pageReq, osType.getId()).getContent()) assertThat(softwareManagement.findSoftwareModulesByType(PAGE, osType.getId()).getContent())
.as("Expected to find the following number of modules:").hasSize(2).as("with the following elements") .as("Expected to find the following number of modules:").hasSize(2).as("with the following elements")
.contains(two, one); .contains(two, one);
} }
@@ -319,18 +320,18 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Tests the successfull deletion of software module types. Both unused (hard delete) and used ones (soft delete).") @Description("Tests the successfull deletion of software module types. Both unused (hard delete) and used ones (soft delete).")
public void deleteAssignedAndUnassignedSoftwareModuleTypes() { public void deleteAssignedAndUnassignedSoftwareModuleTypes() {
assertThat(softwareManagement.findSoftwareModuleTypesAll(pageReq)).hasSize(3).contains(osType, runtimeType, assertThat(softwareManagement.findSoftwareModuleTypesAll(PAGE)).hasSize(3).contains(osType, runtimeType,
appType); appType);
SoftwareModuleType type = softwareManagement.createSoftwareModuleType( SoftwareModuleType type = softwareManagement.createSoftwareModuleType(
entityFactory.softwareModuleType().create().key("bundle").name("OSGi Bundle")); entityFactory.softwareModuleType().create().key("bundle").name("OSGi Bundle"));
assertThat(softwareManagement.findSoftwareModuleTypesAll(pageReq)).hasSize(4).contains(osType, runtimeType, assertThat(softwareManagement.findSoftwareModuleTypesAll(PAGE)).hasSize(4).contains(osType, runtimeType,
appType, type); appType, type);
// delete unassigned // delete unassigned
softwareManagement.deleteSoftwareModuleType(type.getId()); softwareManagement.deleteSoftwareModuleType(type.getId());
assertThat(softwareManagement.findSoftwareModuleTypesAll(pageReq)).hasSize(3).contains(osType, runtimeType, assertThat(softwareManagement.findSoftwareModuleTypesAll(PAGE)).hasSize(3).contains(osType, runtimeType,
appType); appType);
assertThat(softwareModuleTypeRepository.findAll()).hasSize(3).contains((JpaSoftwareModuleType) osType, assertThat(softwareModuleTypeRepository.findAll()).hasSize(3).contains((JpaSoftwareModuleType) osType,
(JpaSoftwareModuleType) runtimeType, (JpaSoftwareModuleType) appType); (JpaSoftwareModuleType) runtimeType, (JpaSoftwareModuleType) appType);
@@ -338,7 +339,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
type = softwareManagement.createSoftwareModuleType( type = softwareManagement.createSoftwareModuleType(
entityFactory.softwareModuleType().create().key("bundle2").name("OSGi Bundle2")); entityFactory.softwareModuleType().create().key("bundle2").name("OSGi Bundle2"));
assertThat(softwareManagement.findSoftwareModuleTypesAll(pageReq)).hasSize(4).contains(osType, runtimeType, assertThat(softwareManagement.findSoftwareModuleTypesAll(PAGE)).hasSize(4).contains(osType, runtimeType,
appType, type); appType, type);
softwareManagement.createSoftwareModule( softwareManagement.createSoftwareModule(
@@ -346,7 +347,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
// delete assigned // delete assigned
softwareManagement.deleteSoftwareModuleType(type.getId()); softwareManagement.deleteSoftwareModuleType(type.getId());
assertThat(softwareManagement.findSoftwareModuleTypesAll(pageReq)).hasSize(3).contains(osType, runtimeType, assertThat(softwareManagement.findSoftwareModuleTypesAll(PAGE)).hasSize(3).contains(osType, runtimeType,
appType); appType);
assertThat(softwareModuleTypeRepository.findAll()).hasSize(4).contains((JpaSoftwareModuleType) osType, assertThat(softwareModuleTypeRepository.findAll()).hasSize(4).contains((JpaSoftwareModuleType) osType,
@@ -397,7 +398,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
// verify: assignedModule is marked as deleted // verify: assignedModule is marked as deleted
assignedModule = softwareManagement.findSoftwareModuleById(assignedModule.getId()).get(); assignedModule = softwareManagement.findSoftwareModuleById(assignedModule.getId()).get();
assertTrue("The module should be flagged as deleted", assignedModule.isDeleted()); assertTrue("The module should be flagged as deleted", assignedModule.isDeleted());
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).hasSize(0);
assertThat(softwareModuleRepository.findAll()).hasSize(1); assertThat(softwareModuleRepository.findAll()).hasSize(1);
// verify: binary data is deleted // verify: binary data is deleted
@@ -437,7 +438,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
// verify: assignedModule is marked as deleted // verify: assignedModule is marked as deleted
assignedModule = softwareManagement.findSoftwareModuleById(assignedModule.getId()).get(); assignedModule = softwareManagement.findSoftwareModuleById(assignedModule.getId()).get();
assertTrue("The found module should be flagged deleted", assignedModule.isDeleted()); assertTrue("The found module should be flagged deleted", assignedModule.isDeleted());
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).hasSize(0);
assertThat(softwareModuleRepository.findAll()).hasSize(1); assertThat(softwareModuleRepository.findAll()).hasSize(1);
// verify: binary data is deleted // verify: binary data is deleted
@@ -538,7 +539,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
assertThat(moduleY).isNotNull(); assertThat(moduleY).isNotNull();
assertTrue("The module should be flagged deleted", moduleX.isDeleted()); assertTrue("The module should be flagged deleted", moduleX.isDeleted());
assertTrue("The module should be flagged deleted", moduleY.isDeleted()); assertTrue("The module should be flagged deleted", moduleY.isDeleted());
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); assertThat(softwareManagement.findSoftwareModulesAll(PAGE)).hasSize(0);
assertThat(softwareModuleRepository.findAll()).hasSize(2); assertThat(softwareModuleRepository.findAll()).hasSize(2);
// verify: binary data of artifact is deleted // verify: binary data of artifact is deleted
@@ -621,21 +622,21 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
softwareManagement.deleteSoftwareModule(deleted.getId()); softwareManagement.deleteSoftwareModule(deleted.getId());
// with filter on name, version and module type // with filter on name, version and module type
assertThat(softwareManagement.findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(pageReq, assertThat(softwareManagement.findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(PAGE,
set.getId(), "%found%", testType.getId()).getContent()) set.getId(), "%found%", testType.getId()).getContent())
.as("Found modules with given name, given module type and the assigned ones first") .as("Found modules with given name, given module type and the assigned ones first")
.containsExactly(new AssignedSoftwareModule(one, true), new AssignedSoftwareModule(two, true), .containsExactly(new AssignedSoftwareModule(one, true), new AssignedSoftwareModule(two, true),
new AssignedSoftwareModule(unassigned, false)); new AssignedSoftwareModule(unassigned, false));
// with filter on module type only // with filter on module type only
assertThat(softwareManagement.findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(pageReq, assertThat(softwareManagement.findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(PAGE,
set.getId(), null, testType.getId()).getContent()) set.getId(), null, testType.getId()).getContent())
.as("Found modules with given module type and the assigned ones first").containsExactly( .as("Found modules with given module type and the assigned ones first").containsExactly(
new AssignedSoftwareModule(differentName, true), new AssignedSoftwareModule(one, true), new AssignedSoftwareModule(differentName, true), new AssignedSoftwareModule(one, true),
new AssignedSoftwareModule(two, true), new AssignedSoftwareModule(unassigned, false)); new AssignedSoftwareModule(two, true), new AssignedSoftwareModule(unassigned, false));
// without any filter // without any filter
assertThat(softwareManagement.findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(pageReq, assertThat(softwareManagement.findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(PAGE,
set.getId(), null, null).getContent()).as("Found modules with the assigned ones first").containsExactly( set.getId(), null, null).getContent()).as("Found modules with the assigned ones first").containsExactly(
new AssignedSoftwareModule(differentName, true), new AssignedSoftwareModule(one, true), new AssignedSoftwareModule(differentName, true), new AssignedSoftwareModule(one, true),
new AssignedSoftwareModule(two, true), new AssignedSoftwareModule(four, true), new AssignedSoftwareModule(two, true), new AssignedSoftwareModule(four, true),
@@ -773,7 +774,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
.create().name("set").version("1").modules(Lists.newArrayList(one.getId(), deleted.getId()))); .create().name("set").version("1").modules(Lists.newArrayList(one.getId(), deleted.getId())));
softwareManagement.deleteSoftwareModule(deleted.getId()); softwareManagement.deleteSoftwareModule(deleted.getId());
assertThat(softwareManagement.findSoftwareModuleByAssignedTo(pageReq, set.getId()).getContent()) assertThat(softwareManagement.findSoftwareModuleByAssignedTo(PAGE, set.getId()).getContent())
.as("Found this number of modules").hasSize(2); .as("Found this number of modules").hasSize(2);
} }
@@ -882,13 +883,13 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest {
.createSoftwareModuleMetadata(ah.getId(), entityFactory.generateMetadata(knownKey1, knownValue1)) .createSoftwareModuleMetadata(ah.getId(), entityFactory.generateMetadata(knownKey1, knownValue1))
.getSoftwareModule(); .getSoftwareModule();
assertThat(softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(ah.getId())) assertThat(softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(new PageRequest(0, 100), ah.getId())
.as("Contains the created metadata element") .getContent()).as("Contains the created metadata element")
.containsExactly(new JpaSoftwareModuleMetadata(knownKey1, ah, knownValue1)); .containsExactly(new JpaSoftwareModuleMetadata(knownKey1, ah, knownValue1));
softwareManagement.deleteSoftwareModuleMetadata(ah.getId(), knownKey1); softwareManagement.deleteSoftwareModuleMetadata(ah.getId(), knownKey1);
assertThat(softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(ah.getId())) assertThat(softwareManagement.findSoftwareModuleMetadataBySoftwareModuleId(new PageRequest(0, 100), ah.getId())
.as("Metadata elemenets are").isEmpty(); .getContent()).as("Metadata elemenets are").isEmpty();
} }
@Test @Test

View File

@@ -33,11 +33,11 @@ public class SystemManagementTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Ensures that findTenants returns all tenants and not only restricted to the tenant which currently is logged in") @Description("Ensures that findTenants returns all tenants and not only restricted to the tenant which currently is logged in")
public void findTenantsReturnsAllTenantsNotOnlyWhichLoggedIn() throws Exception { public void findTenantsReturnsAllTenantsNotOnlyWhichLoggedIn() throws Exception {
assertThat(systemManagement.findTenants()).hasSize(1); assertThat(systemManagement.findTenants(PAGE).getContent()).hasSize(1);
createTestTenantsForSystemStatistics(2, 0, 0, 0); createTestTenantsForSystemStatistics(2, 0, 0, 0);
assertThat(systemManagement.findTenants()).hasSize(3); assertThat(systemManagement.findTenants(PAGE).getContent()).hasSize(3);
} }
@Test @Test

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