From 804522f9660d586729799dda8c2d38ba78272d3c Mon Sep 17 00:00:00 2001
From: Kai Zimmermann
Date: Thu, 16 Feb 2017 10:09:14 +0100
Subject: [PATCH] hawkBit repository uses Optional on single entity find/get
requests (#435)
* Repo returns optionals.
* Improved exception handling for collection usage in repo queries.
Signed-off-by: kaizimmerm
---
.../pom.xml | 18 +-
.../repository/MongoDBArtifactStoreTest.java | 2 +-
.../pom.xml | 16 +-
.../artifact/repository/S3RepositoryTest.java | 4 +-
extensions/hawkbit-extension-uaa/pom.xml | 1 +
.../pom.xml | 14 +-
.../ArtifactFilesystemRepositoryTest.java | 4 +-
.../repository/ArtifactFilesystemTest.java | 4 +-
hawkbit-core/pom.xml | 20 --
.../hawkbit/exception/SpServerError.java | 2 +-
.../TenantConfigurationProperties.java | 2 +-
.../eclipse/hawkbit/api/Base62UtilTest.java | 2 +-
.../PropertyBasedArtifactUrlHandlerTest.java | 2 +-
.../cache/DefaultDownloadIdCacheTest.java | 2 +-
hawkbit-ddi-resource/pom.xml | 10 -
.../resource/DdiArtifactStoreController.java | 28 ++-
.../ddi/rest/resource/DdiRootController.java | 31 ++-
.../resource/DdiArtifactDownloadTest.java | 6 +-
.../rest/resource/DdiCancelActionTest.java | 110 +++++----
.../ddi/rest/resource/DdiConfigDataTest.java | 24 +-
.../rest/resource/DdiDeploymentBaseTest.java | 194 ++++++++--------
.../rest/resource/DdiRootControllerTest.java | 25 +-
.../ddi/rest/resource/DosFilterTest.java | 2 +-
hawkbit-dmf-amqp/pom.xml | 15 --
.../AmqpAuthenticationMessageHandler.java | 47 ++--
.../amqp/AmqpMessageDispatcherService.java | 4 +-
.../amqp/AmqpMessageHandlerService.java | 17 +-
.../AmqpControllerAuthenticationTest.java | 11 +-
.../AmqpMessageDispatcherServiceTest.java | 12 +-
.../amqp/AmqpMessageHandlerServiceTest.java | 25 +-
.../hawkbit/amqp/BaseAmqpServiceTest.java | 4 +-
hawkbit-http-security/pom.xml | 10 -
...SourceTrustAuthenticationProviderTest.java | 2 +-
hawkbit-mgmt-api/pom.xml | 4 +-
.../mgmt/json/model/PagedListTest.java | 2 +-
hawkbit-mgmt-resource/pom.xml | 10 -
.../resource/MgmtDistributionSetResource.java | 28 +--
.../MgmtDistributionSetTagResource.java | 11 +-
.../MgmtDistributionSetTypeResource.java | 27 +--
.../MgmtDownloadArtifactResource.java | 9 +-
.../rest/resource/MgmtRolloutResource.java | 45 ++--
.../resource/MgmtSoftwareModuleResource.java | 14 +-
.../MgmtSoftwareModuleTypeResource.java | 8 +-
.../MgmtTargetFilterQueryResource.java | 8 +-
.../rest/resource/MgmtTargetResource.java | 25 +-
.../rest/resource/MgmtTargetTagResource.java | 7 +-
.../MgmtDistributionSetResourceTest.java | 178 ++++++++-------
.../MgmtDistributionSetTypeResourceTest.java | 42 ++--
.../resource/MgmtDownloadResourceTest.java | 4 +-
.../resource/MgmtRolloutResourceTest.java | 6 +-
.../MgmtSoftwareModuleResourceTest.java | 88 +++++---
.../MgmtSoftwareModuleTypeResourceTest.java | 20 +-
.../MgmtTargetFilterQueryResourceTest.java | 24 +-
.../rest/resource/MgmtTargetResourceTest.java | 49 ++--
.../hawkbit-repository-api/pom.xml | 9 +-
.../repository/ArtifactManagement.java | 20 +-
.../repository/ControllerManagement.java | 24 +-
.../repository/DeploymentManagement.java | 25 +-
.../repository/DistributionSetManagement.java | 72 +++---
.../repository/RolloutGroupManagement.java | 8 +-
.../hawkbit/repository/RolloutManagement.java | 36 ++-
.../repository/SoftwareManagement.java | 70 ++++--
.../hawkbit/repository/TagManagement.java | 30 +--
.../TargetFilterQueryManagement.java | 11 +-
.../hawkbit/repository/TargetManagement.java | 61 ++++-
.../exception/EntityNotFoundException.java | 58 ++++-
...areModuleNotAssignedToTargetException.java | 39 ++++
...TypeNotInDistributionSetTypeException.java | 40 ++++
.../hawkbit/repository/model/Action.java | 5 +-
.../repository/model/DistributionSet.java | 7 +-
.../repository/model/DistributionSetType.java | 4 +-
.../repository/model/SoftwareModule.java | 12 +-
...gementMethodPreAuthorizeAnnotatedTest.java | 2 +-
.../hawkbit-repository-core/pom.xml | 19 +-
.../org/eclipse/hawkbit/event/EventType.java | 2 +-
.../BusProtoStuffMessageConverterTest.java | 4 +-
.../hawkbit-repository-jpa/pom.xml | 10 -
.../repository/jpa/ActionRepository.java | 9 +-
.../repository/jpa/BaseEntityRepository.java | 11 +
.../jpa/DistributionSetRepository.java | 4 +-
.../jpa/DistributionSetTagRepository.java | 3 +-
.../repository/jpa/JpaArtifactManagement.java | 30 ++-
.../jpa/JpaControllerManagement.java | 48 ++--
.../jpa/JpaDeploymentManagement.java | 33 ++-
.../jpa/JpaDistributionSetManagement.java | 213 ++++++++++--------
.../jpa/JpaRolloutGroupManagement.java | 24 +-
.../repository/jpa/JpaRolloutManagement.java | 110 ++++-----
.../repository/jpa/JpaSoftwareManagement.java | 129 +++++++----
.../repository/jpa/JpaTagManagement.java | 36 ++-
.../jpa/JpaTargetFilterQueryManagement.java | 24 +-
.../repository/jpa/JpaTargetManagement.java | 130 +++++++----
.../jpa/LocalArtifactRepository.java | 6 +-
.../repository/jpa/RolloutRepository.java | 3 +-
.../jpa/SoftwareModuleRepository.java | 3 +-
.../jpa/SoftwareModuleTypeRepository.java | 5 +-
.../jpa/TargetFilterQueryRepository.java | 4 +-
.../repository/jpa/TargetRepository.java | 3 +-
.../repository/jpa/TargetTagRepository.java | 3 +-
.../jpa/builder/JpaDistributionSetCreate.java | 13 +-
.../builder/JpaDistributionSetTypeCreate.java | 3 +-
.../jpa/builder/JpaRolloutCreate.java | 8 +-
.../jpa/builder/JpaSoftwareModuleCreate.java | 9 +-
.../builder/JpaTargetFilterQueryCreate.java | 8 +-
.../repository/jpa/model/JpaAction.java | 1 +
.../jpa/model/JpaDistributionSet.java | 6 +-
.../jpa/model/JpaDistributionSetType.java | 4 +-
.../repository/jpa/rsql/RSQLUtility.java | 2 +-
.../event/remote/RemoteIdEventTest.java | 2 +-
.../remote/RemoteTenantAwareEventTest.java | 2 +-
.../entity/AbstractRemoteEntityEventTest.java | 2 +-
.../event/remote/entity/ActionEventTest.java | 1 +
.../remote/entity/RolloutGroupEventTest.java | 4 +-
.../event/remote/entity/TargetEventTest.java | 2 +-
.../hawkbit/repository/jpa/ActionTest.java | 2 +-
.../jpa/ArtifactManagementTest.java | 38 ++--
.../jpa/ControllerManagementTest.java | 30 +--
.../jpa/DeploymentManagementTest.java | 165 ++++++++------
.../jpa/DistributionSetManagementTest.java | 96 ++++----
.../repository/jpa/ReportManagementTest.java | 4 +-
.../repository/jpa/RolloutManagementTest.java | 74 +++---
.../jpa/SoftwareManagementTest.java | 50 ++--
.../repository/jpa/SystemManagementTest.java | 8 +-
.../repository/jpa/TagManagementTest.java | 43 ++--
.../jpa/TargetFilterQueryManagementTest.java | 23 +-
.../jpa/TargetManagementSearchTest.java | 17 +-
.../repository/jpa/TargetManagementTest.java | 27 +--
.../TenantConfigurationManagementTest.java | 4 +-
.../jpa/autoassign/AutoAssignCheckerTest.java | 2 +-
.../jpa/event/RepositoryEntityEventTest.java | 4 +-
.../model/EntityInterceptorListenerTest.java | 5 +-
.../jpa/model/ModelEqualsHashcodeTest.java | 2 +-
.../jpa/rsql/RSQLActionFieldsTest.java | 2 +-
.../rsql/RSQLDistributionSetFieldTest.java | 2 +-
...RSQLDistributionSetMetadataFieldsTest.java | 2 +-
.../jpa/rsql/RSQLRolloutGroupFields.java | 6 +-
.../jpa/rsql/RSQLSoftwareModuleFieldTest.java | 2 +-
.../RSQLSoftwareModuleMetadataFieldsTest.java | 2 +-
.../RSQLSoftwareModuleTypeFieldsTest.java | 2 +-
.../jpa/rsql/RSQLTagFieldsTest.java | 2 +-
.../jpa/rsql/RSQLTargetFieldTest.java | 2 +-
.../rsql/RsqlParserValidationOracleTest.java | 2 +-
.../SpecificationsBuilderTest.java | 2 +-
.../jpa/tenancy/MultiTenancyEntityTest.java | 12 +-
.../hawkbit-repository-test/pom.xml | 5 -
.../test/util/AbstractIntegrationTest.java | 4 +-
.../repository/test/util/TestdataFactory.java | 41 ++--
hawkbit-rest-core/pom.xml | 5 -
.../rest/json/model/ExceptionInfoTest.java | 2 +-
.../hawkbit/rest/util/SortUtilityTest.java | 2 +-
hawkbit-security-core/pom.xml | 10 -
.../im/authentication/PermissionTest.java | 2 +-
...ExcludePathAwareShallowETagFilterTest.java | 2 +-
.../org/eclipse/hawkbit/util/IpUtilTest.java | 2 +-
hawkbit-security-integration/pom.xml | 19 +-
...lerPreAuthenticateSecurityTokenFilter.java | 15 +-
...PreAuthenticatedAnonymousDownloadTest.java | 2 +-
...AuthenticatedSecurityHeaderFilterTest.java | 2 +-
hawkbit-ui/pom.xml | 14 +-
.../hawkbit/ui/DispatcherRunnable.java | 57 -----
.../ui/artifacts/event/UploadStatusEvent.java | 4 +-
.../UploadViewConfirmationWindowLayout.java | 2 +-
.../SoftwareModuleAddUpdateWindow.java | 9 +-
.../smtable/SoftwareModuleDetails.java | 2 +-
.../smtable/SoftwareModuleTable.java | 5 +-
.../CreateUpdateSoftwareTypeLayout.java | 18 +-
.../smtype/SMTypeFilterButtonClick.java | 2 +-
.../artifacts/smtype/SMTypeFilterButtons.java | 2 +-
.../upload/UploadConfirmationWindow.java | 9 +-
.../common/AbstractMetadataPopupLayout.java | 13 +-
.../DistributionSetMetadatadetailslayout.java | 15 +-
.../SoftwareModuleMetadatadetailslayout.java | 2 +-
.../ui/common/table/AbstractTable.java | 13 +-
.../common/tagdetails/AbstractTagToken.java | 2 +-
.../ui/common/tagdetails/TargetTagToken.java | 5 +-
.../components/SPUITableHorizonatlLayout.java | 42 ----
.../ui/components/SPUIUpdateLogLayout.java | 83 -------
.../client/HtmlButtonRendererConnector.java | 2 +-
.../client/RolloutRendererConnector.java | 2 +-
.../renderers/HtmlLabelRenderer.java | 3 +-
.../DistributionsViewClientCriterion.java | 9 +-
.../ui/decorators/SPUIButtonDecorator.java | 3 -
.../SPUIButtonStyleSmallNoBorder.java | 6 -
.../SPUIButtonStyleSmallNoBorderUH.java | 42 ----
.../hawkbit/ui/decorators/SPUIEmbedValue.java | 179 ---------------
.../CreateUpdateDistSetTypeLayout.java | 35 ++-
.../disttype/DSTypeFilterButtonClick.java | 6 +-
.../disttype/DSTypeFilterButtons.java | 2 +-
.../dstable/DistributionSetDetails.java | 6 +-
.../dstable/DistributionSetTable.java | 18 +-
.../dstable/DsMetadataPopupLayout.java | 20 +-
...DistributionsConfirmationWindowLayout.java | 11 +-
.../smtable/SwMetadataPopupLayout.java | 4 +-
.../smtable/SwModuleDetails.java | 2 +-
.../distributions/smtable/SwModuleTable.java | 7 +-
.../smtype/DistSMTypeFilterButtonClick.java | 2 +-
.../smtype/DistSMTypeFilterButtons.java | 4 +-
.../CreateOrUpdateFilterHeader.java | 2 +-
.../DistributionSetSelectWindow.java | 10 +-
.../filtermanagement/TargetFilterTable.java | 4 +-
.../AutoCompleteTextFieldConnector.java | 1 -
.../client/SuggestTokenDto.java | 2 +-
.../AbstractCreateUpdateTagLayout.java | 28 +--
.../ui/layouts/CreateUpdateTypeLayout.java | 14 +-
.../actionhistory/ActionHistoryTable.java | 2 +-
.../DistributionAddUpdateWindowLayout.java | 37 +--
.../dstable/DistributionDetails.java | 9 +-
.../management/dstable/DistributionTable.java | 28 +--
...eateUpdateDistributionTagLayoutWindow.java | 20 +-
.../footer/DeleteActionsLayout.java | 8 +-
.../targettable/BulkUploadHandler.java | 4 +-
.../TargetAddUpdateWindowLayout.java | 12 +-
.../targettable/TargetBeanQuery.java | 3 +-
.../targettable/TargetBulkTokenTags.java | 7 +-
.../management/targettable/TargetTable.java | 13 +-
.../targettable/TargetTableHeader.java | 7 +-
.../CreateUpdateTargetTagLayoutWindow.java | 23 +-
.../CustomTargetTagFilterButtonClick.java | 2 +-
.../hawkbit/ui/menu/DashboardMenu.java | 2 +-
.../rollout/groupschart/GroupsPieChart.java | 7 +-
.../client/GroupsPieChartConnector.java | 3 +-
.../client/GroupsPieChartState.java | 4 +-
.../rollout/AddUpdateRolloutWindowLayout.java | 7 +-
.../rollout/rollout/DefineGroupsLayout.java | 13 +-
.../rollout/rollout/GroupsLegendLayout.java | 18 +-
.../ui/rollout/rollout/RolloutListGrid.java | 3 +-
.../rolloutgroup/RolloutGroupListGrid.java | 2 +-
...ringSecurityAtmosphereInterceptorTest.java | 2 +-
.../criteria/ItemIdClientCriterionTest.java | 2 +-
.../criteria/ViewClientCriterionTest.java | 2 +-
.../ViewComponentClientCriterionTest.java | 2 +-
.../ui/utils/SPUIComponentProviderTest.java | 12 +-
pom.xml | 14 --
232 files changed, 2104 insertions(+), 2377 deletions(-)
create mode 100644 hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/SoftwareModuleNotAssignedToTargetException.java
create mode 100644 hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/SoftwareModuleTypeNotInDistributionSetTypeException.java
delete mode 100644 hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/DispatcherRunnable.java
delete mode 100644 hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/SPUITableHorizonatlLayout.java
delete mode 100644 hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/SPUIUpdateLogLayout.java
delete mode 100644 hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/decorators/SPUIButtonStyleSmallNoBorderUH.java
delete mode 100644 hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/decorators/SPUIEmbedValue.java
diff --git a/extensions/hawkbit-extension-artifact-repository-mongo/pom.xml b/extensions/hawkbit-extension-artifact-repository-mongo/pom.xml
index 726efd3bf..e4aa90a2c 100644
--- a/extensions/hawkbit-extension-artifact-repository-mongo/pom.xml
+++ b/extensions/hawkbit-extension-artifact-repository-mongo/pom.xml
@@ -17,7 +17,7 @@
hawkbit-extensions-parenthawkbit-extension-artifact-repository-mongo
- hawkBit :: Artifact Repository Mongo
+ hawkBit :: Extensions :: Artifact Repository Mongo
@@ -49,16 +49,6 @@
spring-boot-starter-testtest
-
- org.springframework
- spring-test
- test
-
-
- org.easytesting
- fest-assert-core
- test
- ru.yandex.qatools.allureallure-junit-adaptor
@@ -70,12 +60,6 @@
de.flapdoodle.embed.mongotest
-
-
- org.mockito
- mockito-core
- test
-
\ No newline at end of file
diff --git a/extensions/hawkbit-extension-artifact-repository-mongo/src/test/java/org/eclipse/hawkbit/artifact/repository/MongoDBArtifactStoreTest.java b/extensions/hawkbit-extension-artifact-repository-mongo/src/test/java/org/eclipse/hawkbit/artifact/repository/MongoDBArtifactStoreTest.java
index 338ad62db..3e565de1c 100644
--- a/extensions/hawkbit-extension-artifact-repository-mongo/src/test/java/org/eclipse/hawkbit/artifact/repository/MongoDBArtifactStoreTest.java
+++ b/extensions/hawkbit-extension-artifact-repository-mongo/src/test/java/org/eclipse/hawkbit/artifact/repository/MongoDBArtifactStoreTest.java
@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.artifact.repository;
-import static org.fest.assertions.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import java.io.ByteArrayInputStream;
import java.security.DigestInputStream;
diff --git a/extensions/hawkbit-extension-artifact-repository-s3/pom.xml b/extensions/hawkbit-extension-artifact-repository-s3/pom.xml
index 7fae4f098..ceec22373 100644
--- a/extensions/hawkbit-extension-artifact-repository-s3/pom.xml
+++ b/extensions/hawkbit-extension-artifact-repository-s3/pom.xml
@@ -16,7 +16,7 @@
0.2.0-SNAPSHOThawkbit-extension-artifact-repository-s3
- hawkBit :: S3 Repository
+ hawkBit :: Extensions :: S3 Repository
@@ -50,18 +50,8 @@
commons-io
- org.easytesting
- fest-assert-core
- test
-
-
- org.easytesting
- fest-assert
- test
-
-
- org.mockito
- mockito-core
+ org.springframework.boot
+ spring-boot-starter-testtest
diff --git a/extensions/hawkbit-extension-artifact-repository-s3/src/test/java/org/eclipse/hawkbit/artifact/repository/S3RepositoryTest.java b/extensions/hawkbit-extension-artifact-repository-s3/src/test/java/org/eclipse/hawkbit/artifact/repository/S3RepositoryTest.java
index 20f2976bf..033e9e00e 100644
--- a/extensions/hawkbit-extension-artifact-repository-s3/src/test/java/org/eclipse/hawkbit/artifact/repository/S3RepositoryTest.java
+++ b/extensions/hawkbit-extension-artifact-repository-s3/src/test/java/org/eclipse/hawkbit/artifact/repository/S3RepositoryTest.java
@@ -8,8 +8,8 @@
*/
package org.eclipse.hawkbit.artifact.repository;
-import static org.fest.assertions.Assertions.assertThat;
-import static org.fest.assertions.api.Assertions.fail;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.never;
diff --git a/extensions/hawkbit-extension-uaa/pom.xml b/extensions/hawkbit-extension-uaa/pom.xml
index f8fd16669..b709e0dfd 100644
--- a/extensions/hawkbit-extension-uaa/pom.xml
+++ b/extensions/hawkbit-extension-uaa/pom.xml
@@ -59,4 +59,5 @@
test
+ hawkBit :: Extensions :: UAA Integration
diff --git a/hawkbit-artifact-repository-filesystem/pom.xml b/hawkbit-artifact-repository-filesystem/pom.xml
index 0d9500c07..c1dff0001 100644
--- a/hawkbit-artifact-repository-filesystem/pom.xml
+++ b/hawkbit-artifact-repository-filesystem/pom.xml
@@ -40,18 +40,8 @@
commons-io
- org.easytesting
- fest-assert-core
- test
-
-
- org.easytesting
- fest-assert
- test
-
-
- org.mockito
- mockito-core
+ org.springframework.boot
+ spring-boot-starter-testtest
diff --git a/hawkbit-artifact-repository-filesystem/src/test/java/org/eclipse/hawkbit/artifact/repository/ArtifactFilesystemRepositoryTest.java b/hawkbit-artifact-repository-filesystem/src/test/java/org/eclipse/hawkbit/artifact/repository/ArtifactFilesystemRepositoryTest.java
index 40006d086..6ecce0438 100644
--- a/hawkbit-artifact-repository-filesystem/src/test/java/org/eclipse/hawkbit/artifact/repository/ArtifactFilesystemRepositoryTest.java
+++ b/hawkbit-artifact-repository-filesystem/src/test/java/org/eclipse/hawkbit/artifact/repository/ArtifactFilesystemRepositoryTest.java
@@ -8,15 +8,15 @@
*/
package org.eclipse.hawkbit.artifact.repository;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Random;
import org.apache.commons.io.IOUtils;
+import org.assertj.core.api.Assertions;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
-import org.fest.assertions.api.Assertions;
import org.junit.Test;
import ru.yandex.qatools.allure.annotations.Description;
diff --git a/hawkbit-artifact-repository-filesystem/src/test/java/org/eclipse/hawkbit/artifact/repository/ArtifactFilesystemTest.java b/hawkbit-artifact-repository-filesystem/src/test/java/org/eclipse/hawkbit/artifact/repository/ArtifactFilesystemTest.java
index cb523577f..f9e3dcac0 100644
--- a/hawkbit-artifact-repository-filesystem/src/test/java/org/eclipse/hawkbit/artifact/repository/ArtifactFilesystemTest.java
+++ b/hawkbit-artifact-repository-filesystem/src/test/java/org/eclipse/hawkbit/artifact/repository/ArtifactFilesystemTest.java
@@ -8,14 +8,14 @@
*/
package org.eclipse.hawkbit.artifact.repository;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
-import org.fest.assertions.api.Assertions;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import ru.yandex.qatools.allure.annotations.Description;
diff --git a/hawkbit-core/pom.xml b/hawkbit-core/pom.xml
index d962aa096..f9e140d40 100644
--- a/hawkbit-core/pom.xml
+++ b/hawkbit-core/pom.xml
@@ -33,16 +33,6 @@
guava
-
- org.easytesting
- fest-assert-core
- test
-
-
- org.easytesting
- fest-assert
- test
- org.springframework.bootspring-boot-starter-test
@@ -53,16 +43,6 @@
allure-junit-adaptortest
-
- org.easytesting
- fest-assert-core
- test
-
-
- org.easytesting
- fest-assert
- test
- org.springframework.bootspring-boot-configuration-processor
diff --git a/hawkbit-core/src/main/java/org/eclipse/hawkbit/exception/SpServerError.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/exception/SpServerError.java
index 073336dd8..dbcf0a1bb 100644
--- a/hawkbit-core/src/main/java/org/eclipse/hawkbit/exception/SpServerError.java
+++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/exception/SpServerError.java
@@ -32,7 +32,7 @@ public enum SpServerError {
/**
*
*/
- SP_REPO_ENTITY_NOT_EXISTS("hawkbit.server.error.repo.entitiyNotFound", "The given entity does not exist in database"),
+ SP_REPO_ENTITY_NOT_EXISTS("hawkbit.server.error.repo.entitiyNotFound", "The given entity does not exist in the repository"),
/**
*
*/
diff --git a/hawkbit-core/src/main/java/org/eclipse/hawkbit/tenancy/configuration/TenantConfigurationProperties.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/tenancy/configuration/TenantConfigurationProperties.java
index 8a23e2b2d..f79cfde09 100644
--- a/hawkbit-core/src/main/java/org/eclipse/hawkbit/tenancy/configuration/TenantConfigurationProperties.java
+++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/tenancy/configuration/TenantConfigurationProperties.java
@@ -49,7 +49,7 @@ public class TenantConfigurationProperties {
* @return the TenantConfigurationKey with the name keyName
*/
public TenantConfigurationKey fromKeyName(final String keyName) {
- return configuration.values().stream().filter(conf -> conf.getKeyName().equals(keyName)).findFirst()
+ return configuration.values().stream().filter(conf -> conf.getKeyName().equals(keyName)).findAny()
.orElseThrow(() -> new InvalidTenantConfigurationKeyException(
"The given configuration key " + keyName + " does not exist."));
}
diff --git a/hawkbit-core/src/test/java/org/eclipse/hawkbit/api/Base62UtilTest.java b/hawkbit-core/src/test/java/org/eclipse/hawkbit/api/Base62UtilTest.java
index c9c11d10c..52aabc586 100644
--- a/hawkbit-core/src/test/java/org/eclipse/hawkbit/api/Base62UtilTest.java
+++ b/hawkbit-core/src/test/java/org/eclipse/hawkbit/api/Base62UtilTest.java
@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.api;
-import static org.fest.assertions.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
diff --git a/hawkbit-core/src/test/java/org/eclipse/hawkbit/api/PropertyBasedArtifactUrlHandlerTest.java b/hawkbit-core/src/test/java/org/eclipse/hawkbit/api/PropertyBasedArtifactUrlHandlerTest.java
index 92ca11237..8efd35596 100644
--- a/hawkbit-core/src/test/java/org/eclipse/hawkbit/api/PropertyBasedArtifactUrlHandlerTest.java
+++ b/hawkbit-core/src/test/java/org/eclipse/hawkbit/api/PropertyBasedArtifactUrlHandlerTest.java
@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.api;
-import static org.fest.assertions.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import java.net.URI;
diff --git a/hawkbit-core/src/test/java/org/eclipse/hawkbit/cache/DefaultDownloadIdCacheTest.java b/hawkbit-core/src/test/java/org/eclipse/hawkbit/cache/DefaultDownloadIdCacheTest.java
index fb1b6caa8..c0b8ad476 100644
--- a/hawkbit-core/src/test/java/org/eclipse/hawkbit/cache/DefaultDownloadIdCacheTest.java
+++ b/hawkbit-core/src/test/java/org/eclipse/hawkbit/cache/DefaultDownloadIdCacheTest.java
@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.cache;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
diff --git a/hawkbit-ddi-resource/pom.xml b/hawkbit-ddi-resource/pom.xml
index 567fe4c61..117a61346 100644
--- a/hawkbit-ddi-resource/pom.xml
+++ b/hawkbit-ddi-resource/pom.xml
@@ -128,16 +128,6 @@
spring-security-aspectstest
-
- org.easytesting
- fest-assert-core
- test
-
-
- org.easytesting
- fest-assert
- test
- ru.yandex.qatools.allureallure-junit-adaptor
diff --git a/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactStoreController.java b/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactStoreController.java
index ee9de1f01..8a9e57dcc 100644
--- a/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactStoreController.java
+++ b/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactStoreController.java
@@ -10,7 +10,7 @@ package org.eclipse.hawkbit.ddi.rest.resource;
import java.io.IOException;
import java.io.InputStream;
-import java.util.List;
+import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
@@ -21,6 +21,7 @@ import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.ControllerManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.RepositoryConstants;
+import org.eclipse.hawkbit.repository.exception.SoftwareModuleNotAssignedToTargetException;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.ActionStatus;
@@ -73,18 +74,15 @@ public class DdiArtifactStoreController implements DdiDlArtifactStoreControllerR
public ResponseEntity downloadArtifactByFilename(@PathVariable("tenant") final String tenant,
@PathVariable("fileName") final String fileName) {
final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
- final List foundArtifacts = artifactManagement.findArtifactByFilename(fileName);
+ final Optional foundArtifacts = artifactManagement.findArtifactByFilename(fileName);
- if (foundArtifacts.isEmpty()) {
+ if (!foundArtifacts.isPresent()) {
LOG.warn("Software artifact with name {} could not be found.", fileName);
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
- if (foundArtifacts.size() > 1) {
- LOG.warn("Software artifact name {} is not unique. We will use the first entry.", fileName);
- }
ResponseEntity result;
- final Artifact artifact = foundArtifacts.get(0);
+ final Artifact artifact = foundArtifacts.get();
final String ifMatch = requestResponseContextHolder.getHttpServletRequest().getHeader("If-Match");
if (ifMatch != null && !RestResourceConversionHelper.matchesHttpHeader(ifMatch, artifact.getSha1Hash())) {
@@ -116,18 +114,16 @@ public class DdiArtifactStoreController implements DdiDlArtifactStoreControllerR
@Override
public ResponseEntity downloadArtifactMD5ByFilename(@PathVariable("tenant") final String tenant,
@PathVariable("fileName") final String fileName) {
- final List foundArtifacts = artifactManagement.findArtifactByFilename(fileName);
+ final Optional foundArtifacts = artifactManagement.findArtifactByFilename(fileName);
- if (foundArtifacts.isEmpty()) {
- LOG.warn("Softeare artifact with name {} could not be found.", fileName);
+ if (!foundArtifacts.isPresent()) {
+ LOG.warn("Software artifact with name {} could not be found.", fileName);
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
- } else if (foundArtifacts.size() > 1) {
- LOG.error("Softeare artifact name {} is not unique.", fileName);
}
try {
DataConversionHelper.writeMD5FileResponse(fileName, requestResponseContextHolder.getHttpServletResponse(),
- foundArtifacts.get(0));
+ foundArtifacts.get());
} catch (final IOException e) {
LOG.error("Failed to stream MD5 File", e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
@@ -142,7 +138,10 @@ public class DdiArtifactStoreController implements DdiDlArtifactStoreControllerR
IpUtil.getClientIpFromRequest(request, securityProperties));
final Action action = controllerManagement
- .getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(), artifact.getSoftwareModule());
+ .getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(),
+ artifact.getSoftwareModule().getId())
+ .orElseThrow(() -> new SoftwareModuleNotAssignedToTargetException(artifact.getSoftwareModule().getId(),
+ target.getControllerId()));
final String range = request.getHeader("Range");
String message;
@@ -156,5 +155,4 @@ public class DdiArtifactStoreController implements DdiDlArtifactStoreControllerR
return controllerManagement.addInformationalActionStatus(
entityFactory.actionStatus().create(action.getId()).status(Status.DOWNLOAD).message(message));
}
-
}
diff --git a/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootController.java b/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootController.java
index 73610168e..83baa2557 100644
--- a/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootController.java
+++ b/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootController.java
@@ -37,6 +37,7 @@ import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.SystemManagement;
import org.eclipse.hawkbit.repository.builder.ActionStatusCreate;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
+import org.eclipse.hawkbit.repository.exception.SoftwareModuleNotAssignedToTargetException;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.ActionStatus;
@@ -112,13 +113,8 @@ public class DdiRootController implements DdiRootControllerRestApi {
final Target target = controllerManagement.updateLastTargetQuery(controllerId, IpUtil
.getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), securityProperties));
- final SoftwareModule softwareModule = softwareManagement.findSoftwareModuleById(softwareModuleId);
-
- if (softwareModule == null) {
- LOG.warn("Software module with id {} could not be found.", softwareModuleId);
- throw new EntityNotFoundException("Software module does not exist");
-
- }
+ final SoftwareModule softwareModule = softwareManagement.findSoftwareModuleById(softwareModuleId)
+ .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
return new ResponseEntity<>(
DataConversionHelper.createArtifacts(target, softwareModule, artifactUrlHandler, systemManagement,
@@ -147,7 +143,8 @@ public class DdiRootController implements DdiRootControllerRestApi {
final Target target = controllerManagement.updateLastTargetQuery(controllerId, IpUtil
.getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), securityProperties));
- final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId);
+ final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId)
+ .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
if (checkModule(fileName, module)) {
LOG.warn("Softare module with id {} could not be found.", softwareModuleId);
@@ -166,7 +163,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
result = new ResponseEntity<>(HttpStatus.PRECONDITION_FAILED);
} else {
final ActionStatus action = checkAndLogDownload(requestResponseContextHolder.getHttpServletRequest(),
- target, module);
+ target, module.getId());
result = RestResourceConversionHelper.writeFileResponse(artifact,
requestResponseContextHolder.getHttpServletResponse(),
requestResponseContextHolder.getHttpServletRequest(), file, controllerManagement,
@@ -176,10 +173,10 @@ public class DdiRootController implements DdiRootControllerRestApi {
return result;
}
- private ActionStatus checkAndLogDownload(final HttpServletRequest request, final Target target,
- final SoftwareModule module) {
+ private ActionStatus checkAndLogDownload(final HttpServletRequest request, final Target target, final Long module) {
final Action action = controllerManagement
- .getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(), module);
+ .getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(), module)
+ .orElseThrow(() -> new SoftwareModuleNotAssignedToTargetException(module, target.getControllerId()));
final String range = request.getHeader("Range");
String message;
@@ -209,7 +206,8 @@ public class DdiRootController implements DdiRootControllerRestApi {
controllerManagement.updateLastTargetQuery(controllerId, IpUtil
.getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), securityProperties));
- final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId);
+ final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId)
+ .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
if (checkModule(fileName, module)) {
LOG.warn("Software module with id {} could not be found.", softwareModuleId);
@@ -483,10 +481,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
}
private Action findActionWithExceptionIfNotFound(final Long actionId) {
- final Action findAction = controllerManagement.findActionWithDetails(actionId);
- if (findAction == null) {
- throw new EntityNotFoundException("Action with Id {" + actionId + "} does not exist");
- }
- return findAction;
+ return controllerManagement.findActionWithDetails(actionId)
+ .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
}
}
diff --git a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactDownloadTest.java b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactDownloadTest.java
index adb04f03f..95fe29bdc 100644
--- a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactDownloadTest.java
+++ b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactDownloadTest.java
@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.ddi.rest.resource;
-import static org.fest.assertions.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@@ -90,7 +90,7 @@ public class DdiArtifactDownloadTest extends AbstractDDiApiIntegrationTest {
// create artifact
final byte random[] = RandomUtils.nextBytes(5 * 1024);
final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random),
- ds.findFirstModuleByType(osType).getId(), "file1", false);
+ ds.findFirstModuleByType(osType).get().getId(), "file1", false);
// no artifact available
mvc.perform(get("/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/123455",
@@ -254,7 +254,7 @@ public class DdiArtifactDownloadTest extends AbstractDDiApiIntegrationTest {
// create artifact
final byte random[] = RandomUtils.nextBytes(ARTIFACT_SIZE);
final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random),
- ds.findFirstModuleByType(osType).getId(), "file1", false);
+ ds.findFirstModuleByType(osType).get().getId(), "file1", false);
// download fails as artifact is not yet assigned
mvc.perform(get("/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/{filename}",
diff --git a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiCancelActionTest.java b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiCancelActionTest.java
index 8cda78fea..a3e622350 100644
--- a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiCancelActionTest.java
+++ b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiCancelActionTest.java
@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.ddi.rest.resource;
-import static org.fest.assertions.api.Assertions.assertThat;
+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.startsWith;
@@ -52,7 +52,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
final Target savedTarget = testdataFactory.createTarget();
final Action updateAction = deploymentManagement.findActionWithDetails(
- assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getActions().get(0));
+ assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getActions().get(0)).get();
final Action cancelAction = deploymentManagement.cancelAction(updateAction.getId());
@@ -74,11 +74,11 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.andExpect(jsonPath("$.deployment.download", equalTo("forced")))
.andExpect(jsonPath("$.deployment.update", equalTo("forced")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==jvm)].version",
- contains(ds.findFirstModuleByType(runtimeType).getVersion())))
+ contains(ds.findFirstModuleByType(runtimeType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].version",
- contains(ds.findFirstModuleByType(osType).getVersion())))
+ contains(ds.findFirstModuleByType(osType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].version",
- contains(ds.findFirstModuleByType(appType).getVersion())));
+ contains(ds.findFirstModuleByType(appType).get().getVersion())));
// and finish it
mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/deploymentBase/"
@@ -88,12 +88,12 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
// check database after test
- assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID)
+ assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getAssignedDistributionSet().getId()).isEqualTo(ds.getId());
- assertThat(targetManagement.findTargetByControllerIDWithDetails(TestdataFactory.DEFAULT_CONTROLLER_ID)
+ assertThat(targetManagement.findTargetByControllerIDWithDetails(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getTargetInfo().getInstalledDistributionSet().getId()).isEqualTo(ds.getId());
- assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
- .getInstallationDate()).isGreaterThanOrEqualTo(current);
+ assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
+ .getTargetInfo().getInstallationDate()).isGreaterThanOrEqualTo(current);
}
@@ -104,7 +104,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
final Target savedTarget = testdataFactory.createTarget();
final Action updateAction = deploymentManagement.findActionWithDetails(
- assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getActions().get(0));
+ assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getActions().get(0)).get();
long current = System.currentTimeMillis();
mvc.perform(get("/{tenant}/controller/v1/{controller}", tenantAware.getCurrentTenant(),
@@ -118,10 +118,10 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
Thread.sleep(1); // is required: otherwise processing the next line is
// often too fast and
// the following assert will fail
- assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
- .getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
- assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
- .getLastTargetQuery()).isGreaterThanOrEqualTo(current);
+ assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
+ .getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
+ assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
+ .getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
// Retrieved is reported
@@ -150,24 +150,24 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
Thread.sleep(1); // is required: otherwise processing the next line is
// often too fast and
// the following assert will fail
- assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
- .getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
- assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
- .getLastTargetQuery()).isGreaterThanOrEqualTo(current);
+ assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
+ .getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
+ assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
+ .getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
current = System.currentTimeMillis();
- assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
- .getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
+ assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
+ .getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
+ cancelAction.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.id", equalTo(String.valueOf(cancelAction.getId()))))
.andExpect(jsonPath("$.cancelAction.stopId", equalTo(String.valueOf(updateAction.getId()))));
- assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
- .getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
- assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
- .getLastTargetQuery()).isGreaterThanOrEqualTo(current);
+ assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
+ .getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
+ assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
+ .getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
// controller confirmed cancelled action, should not be active anymore
mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
@@ -178,7 +178,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
activeActionsByTarget = deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId());
assertThat(activeActionsByTarget).hasSize(0);
- final Action canceledAction = deploymentManagement.findAction(cancelAction.getId());
+ final Action canceledAction = deploymentManagement.findAction(cancelAction.getId()).get();
assertThat(canceledAction.isActive()).isFalse();
assertThat(canceledAction.getStatus()).isEqualTo(Status.CANCELED);
@@ -221,7 +221,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
final List toAssign = new ArrayList<>();
toAssign.add(savedTarget);
final Action updateAction = deploymentManagement
- .findActionWithDetails(assignDistributionSet(ds, toAssign).getActions().get(0));
+ .findActionWithDetails(assignDistributionSet(ds, toAssign).getActions().get(0)).get();
return deploymentManagement.cancelAction(updateAction.getId());
}
@@ -234,8 +234,10 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
final Target savedTarget = testdataFactory.createTarget();
- final Action updateAction = deploymentManagement.findActionWithDetails(
- assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0));
+ final Action updateAction = deploymentManagement
+ .findActionWithDetails(
+ assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0))
+ .get();
// cancel action manually
final Action cancelAction = deploymentManagement.cancelAction(updateAction.getId());
@@ -248,8 +250,8 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "proceeding"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
- .getLastTargetQuery()).isGreaterThanOrEqualTo(current);
+ assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
+ .getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(3);
@@ -260,8 +262,8 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "resumed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
- .getLastTargetQuery()).isGreaterThanOrEqualTo(current);
+ assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
+ .getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(4);
@@ -271,8 +273,8 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "scheduled"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
- .getLastTargetQuery()).isGreaterThanOrEqualTo(current);
+ assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
+ .getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(5);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1);
@@ -284,8 +286,8 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "canceled"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
- .getLastTargetQuery()).isGreaterThanOrEqualTo(current);
+ assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
+ .getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(6);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1);
@@ -300,8 +302,8 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "rejected"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
- .getLastTargetQuery()).isGreaterThanOrEqualTo(current);
+ assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
+ .getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(7);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1);
@@ -312,8 +314,8 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo()
- .getLastTargetQuery()).isGreaterThanOrEqualTo(current);
+ assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
+ .getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(8);
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(0);
}
@@ -327,12 +329,18 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
final Target savedTarget = testdataFactory.createTarget();
- final Action updateAction = deploymentManagement.findActionWithDetails(
- assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0));
- final Action updateAction2 = deploymentManagement.findActionWithDetails(
- assignDistributionSet(ds2.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0));
- final Action updateAction3 = deploymentManagement.findActionWithDetails(
- assignDistributionSet(ds3.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0));
+ final Action updateAction = deploymentManagement
+ .findActionWithDetails(
+ assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0))
+ .get();
+ final Action updateAction2 = deploymentManagement
+ .findActionWithDetails(
+ assignDistributionSet(ds2.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0))
+ .get();
+ final Action updateAction3 = deploymentManagement
+ .findActionWithDetails(
+ assignDistributionSet(ds3.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0))
+ .get();
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(3);
@@ -395,7 +403,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(9);
- assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID)
+ assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getAssignedDistributionSet()).isEqualTo(ds3);
mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/deploymentBase/"
+ updateAction3.getId(), tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print())
@@ -410,7 +418,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
// action is in cancelling state
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget.getControllerId())).hasSize(1);
assertThat(deploymentManagement.countActionsByTarget(savedTarget.getControllerId())).isEqualTo(3);
- assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID)
+ assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get()
.getAssignedDistributionSet()).isEqualTo(ds3);
mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
@@ -440,8 +448,10 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
final Target target = testdataFactory.createTarget();
final DistributionSet ds = testdataFactory.createDistributionSet("");
- final Action action = deploymentManagement.findActionWithDetails(
- assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0));
+ final Action action = deploymentManagement
+ .findActionWithDetails(
+ assignDistributionSet(ds.getId(), TestdataFactory.DEFAULT_CONTROLLER_ID).getActions().get(0))
+ .get();
final Action cancelAction = deploymentManagement.cancelAction(action.getId());
diff --git a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiConfigDataTest.java b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiConfigDataTest.java
index 8e6cffe1b..c459ec17d 100644
--- a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiConfigDataTest.java
+++ b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiConfigDataTest.java
@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.ddi.rest.resource;
-import static org.fest.assertions.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@@ -58,9 +58,9 @@ public class DdiConfigDataTest extends AbstractDDiApiIntegrationTest {
Thread.sleep(1); // is required: otherwise processing the next line is
// often too fast and
// the following assert will fail
- assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
+ assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isLessThanOrEqualTo(System.currentTimeMillis());
- assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
+ assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current);
savedTarget.getTargetInfo().getControllerAttributes().put("dsafsdf", "sdsds");
@@ -97,13 +97,12 @@ public class DdiConfigDataTest extends AbstractDDiApiIntegrationTest {
Thread.sleep(1); // is required: otherwise processing the next line is
// often too fast and
// the following assert will fail
- assertThat(targetManagement.findTargetByControllerID("4717").getTargetInfo().getLastTargetQuery())
+ assertThat(targetManagement.findTargetByControllerID("4717").get().getTargetInfo().getLastTargetQuery())
.isLessThanOrEqualTo(System.currentTimeMillis());
- assertThat(targetManagement.findTargetByControllerID("4717").getTargetInfo().getLastTargetQuery())
+ assertThat(targetManagement.findTargetByControllerID("4717").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current);
- assertThat(
- targetManagement.findTargetByControllerIDWithDetails("4717").getTargetInfo().getControllerAttributes())
- .isEqualTo(attributes);
+ assertThat(targetManagement.findTargetByControllerIDWithDetails("4717").get().getTargetInfo()
+ .getControllerAttributes()).isEqualTo(attributes);
// update
attributes.put("sdsds", "123412");
@@ -114,13 +113,12 @@ public class DdiConfigDataTest extends AbstractDDiApiIntegrationTest {
Thread.sleep(1); // is required: otherwise processing the next line is
// often too fast and
// the following assert will fail
- assertThat(targetManagement.findTargetByControllerID("4717").getTargetInfo().getLastTargetQuery())
+ assertThat(targetManagement.findTargetByControllerID("4717").get().getTargetInfo().getLastTargetQuery())
.isLessThanOrEqualTo(System.currentTimeMillis());
- assertThat(targetManagement.findTargetByControllerID("4717").getTargetInfo().getLastTargetQuery())
+ assertThat(targetManagement.findTargetByControllerID("4717").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current);
- assertThat(
- targetManagement.findTargetByControllerIDWithDetails("4717").getTargetInfo().getControllerAttributes())
- .isEqualTo(attributes);
+ assertThat(targetManagement.findTargetByControllerIDWithDetails("4717").get().getTargetInfo()
+ .getControllerAttributes()).isEqualTo(attributes);
}
@Test
diff --git a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiDeploymentBaseTest.java b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiDeploymentBaseTest.java
index 888679242..951e7434f 100644
--- a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiDeploymentBaseTest.java
+++ b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiDeploymentBaseTest.java
@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.ddi.rest.resource;
-import static org.fest.assertions.api.Assertions.assertThat;
+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;
@@ -27,6 +27,7 @@ import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.RandomUtils;
+import org.assertj.core.api.Condition;
import org.eclipse.hawkbit.repository.event.remote.TargetAssignDistributionSetEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.ActionCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetCreatedEvent;
@@ -47,7 +48,6 @@ 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.fest.assertions.core.Condition;
import org.junit.Test;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
@@ -88,7 +88,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
assignDistributionSet(distributionSet.getId(), target.getName());
- final Long softwareModuleId = distributionSet.getModules().stream().findFirst().get().getId();
+ final Long softwareModuleId = distributionSet.getModules().stream().findAny().get().getId();
mvc.perform(get("/{tenant}/controller/v1/{targetNotExist}/softwaremodules/{softwareModuleId}/artifacts",
tenantAware.getCurrentTenant(), target.getName(), softwareModuleId)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()).andExpect(jsonPath("$", hasSize(0)));
@@ -146,16 +146,16 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00")))
.andExpect(jsonPath("$._links.deploymentBase.href", startsWith("http://localhost/"
+ tenantAware.getCurrentTenant() + "/controller/v1/4712/deploymentBase/" + uaction.getId())));
- assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
+ assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current);
- assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
+ assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2);
current = System.currentTimeMillis();
final DistributionSet findDistributionSetByAction = distributionSetManagement
- .findDistributionSetByAction(action.getId());
+ .findDistributionSetByAction(action.getId()).get();
mvc.perform(
get("/{tenant}/controller/v1/4712/deploymentBase/" + uaction.getId(), tenantAware.getCurrentTenant())
@@ -166,31 +166,28 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.andExpect(jsonPath("$.deployment.download", equalTo("forced")))
.andExpect(jsonPath("$.deployment.update", equalTo("forced")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==jvm)].name",
- contains(ds.findFirstModuleByType(runtimeType).getName())))
+ contains(ds.findFirstModuleByType(runtimeType).get().getName())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==jvm)].version",
- contains(ds.findFirstModuleByType(runtimeType).getVersion())))
+ contains(ds.findFirstModuleByType(runtimeType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].name",
- contains(ds.findFirstModuleByType(osType).getName())))
+ contains(ds.findFirstModuleByType(osType).get().getName())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].version",
- contains(ds.findFirstModuleByType(osType).getVersion())))
+ contains(ds.findFirstModuleByType(osType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].size", contains(5 * 1024)))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].filename", contains("test1")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.md5",
contains(artifact.getMd5Hash())))
- .andExpect(
- jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.sha1",
- contains(artifact.getSha1Hash())))
- .andExpect(
- jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.download.href",
- contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant()
- + "/controller/v1/4712/softwaremodules/"
- + findDistributionSetByAction.findFirstModuleByType(osType).getId()
+ .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.sha1",
+ contains(artifact.getSha1Hash())))
+ .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.download.href",
+ contains(
+ HTTP_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/"
+ + findDistributionSetByAction.findFirstModuleByType(osType).get().getId()
+ "/artifacts/test1")))
- .andExpect(
- jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.md5sum.href",
- contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant()
- + "/controller/v1/4712/softwaremodules/"
- + findDistributionSetByAction.findFirstModuleByType(osType).getId()
+ .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.md5sum.href",
+ contains(
+ HTTP_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/"
+ + findDistributionSetByAction.findFirstModuleByType(osType).get().getId()
+ "/artifacts/test1.MD5SUM")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].size", contains(5 * 1024)))
@@ -205,19 +202,18 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.download.href",
contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant()
+ "/controller/v1/4712/softwaremodules/"
- + findDistributionSetByAction.findFirstModuleByType(osType).getId()
+ + findDistributionSetByAction.findFirstModuleByType(osType).get().getId()
+ "/artifacts/test1.signature")))
- .andExpect(
- jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.md5sum.href",
- contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant()
- + "/controller/v1/4712/softwaremodules/"
- + findDistributionSetByAction.findFirstModuleByType(osType).getId()
+ .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.md5sum.href",
+ contains(
+ HTTP_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/"
+ + findDistributionSetByAction.findFirstModuleByType(osType).get().getId()
+ "/artifacts/test1.signature.MD5SUM")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].version",
- contains(ds.findFirstModuleByType(appType).getVersion())))
+ contains(ds.findFirstModuleByType(appType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].name",
- contains(ds.findFirstModuleByType(appType).getName())));
- assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
+ contains(ds.findFirstModuleByType(appType).get().getName())));
+ assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current);
// Retrieved is reported
@@ -312,16 +308,16 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00")))
.andExpect(jsonPath("$._links.deploymentBase.href", startsWith("http://localhost/"
+ tenantAware.getCurrentTenant() + "/controller/v1/4712/deploymentBase/" + uaction.getId())));
- assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
+ assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current);
- assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
+ assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2);
current = System.currentTimeMillis();
final DistributionSet findDistributionSetByAction = distributionSetManagement
- .findDistributionSetByAction(action.getId());
+ .findDistributionSetByAction(action.getId()).get();
mvc.perform(
get("/{tenant}/controller/v1/4712/deploymentBase/" + uaction.getId(), tenantAware.getCurrentTenant())
@@ -332,13 +328,13 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.andExpect(jsonPath("$.deployment.download", equalTo("attempt")))
.andExpect(jsonPath("$.deployment.update", equalTo("attempt")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==jvm)].name",
- contains(ds.findFirstModuleByType(runtimeType).getName())))
+ contains(ds.findFirstModuleByType(runtimeType).get().getName())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==jvm)].version",
- contains(ds.findFirstModuleByType(runtimeType).getVersion())))
+ contains(ds.findFirstModuleByType(runtimeType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].name",
- contains(ds.findFirstModuleByType(osType).getName())))
+ contains(ds.findFirstModuleByType(osType).get().getName())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].version",
- contains(ds.findFirstModuleByType(osType).getVersion())))
+ contains(ds.findFirstModuleByType(osType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].size", contains(5 * 1024)))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].filename", contains("test1")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.md5",
@@ -372,10 +368,10 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
+ "/controller/v1/4712/softwaremodules/" + getOsModule(findDistributionSetByAction)
+ "/artifacts/test1.signature.MD5SUM")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].version",
- contains(ds.findFirstModuleByType(appType).getVersion())))
+ contains(ds.findFirstModuleByType(appType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].name",
- contains(ds.findFirstModuleByType(appType).getName())));
- assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
+ contains(ds.findFirstModuleByType(appType).get().getName())));
+ assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current);
// Retrieved is reported
@@ -428,16 +424,16 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00")))
.andExpect(jsonPath("$._links.deploymentBase.href", startsWith("http://localhost/"
+ tenantAware.getCurrentTenant() + "/controller/v1/4712/deploymentBase/" + uaction.getId())));
- assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
+ assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current);
- assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
+ assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(2);
current = System.currentTimeMillis();
final DistributionSet findDistributionSetByAction = distributionSetManagement
- .findDistributionSetByAction(action.getId());
+ .findDistributionSetByAction(action.getId()).get();
mvc.perform(get("/{tenant}/controller/v1/4712/deploymentBase/{actionId}", tenantAware.getCurrentTenant(),
uaction.getId()).accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
@@ -446,31 +442,28 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.andExpect(jsonPath("$.deployment.download", equalTo("forced")))
.andExpect(jsonPath("$.deployment.update", equalTo("forced")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==jvm)].name",
- contains(ds.findFirstModuleByType(runtimeType).getName())))
+ contains(ds.findFirstModuleByType(runtimeType).get().getName())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==jvm)].version",
- contains(ds.findFirstModuleByType(runtimeType).getVersion())))
+ contains(ds.findFirstModuleByType(runtimeType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].name",
- contains(ds.findFirstModuleByType(osType).getName())))
+ contains(ds.findFirstModuleByType(osType).get().getName())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].version",
- contains(ds.findFirstModuleByType(osType).getVersion())))
+ contains(ds.findFirstModuleByType(osType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].size", contains(5 * 1024)))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].filename", contains("test1")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.md5",
contains(artifact.getMd5Hash())))
- .andExpect(
- jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.sha1",
- contains(artifact.getSha1Hash())))
- .andExpect(
- jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.download.href",
- contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant()
- + "/controller/v1/4712/softwaremodules/"
- + findDistributionSetByAction.findFirstModuleByType(osType).getId()
+ .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0].hashes.sha1",
+ contains(artifact.getSha1Hash())))
+ .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.download.href",
+ contains(
+ HTTP_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/"
+ + findDistributionSetByAction.findFirstModuleByType(osType).get().getId()
+ "/artifacts/test1")))
- .andExpect(
- jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.md5sum.href",
- contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant()
- + "/controller/v1/4712/softwaremodules/"
- + findDistributionSetByAction.findFirstModuleByType(osType).getId()
+ .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[0]._links.md5sum.href",
+ contains(
+ HTTP_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/"
+ + findDistributionSetByAction.findFirstModuleByType(osType).get().getId()
+ "/artifacts/test1.MD5SUM")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].size", contains(5 * 1024)))
@@ -478,27 +471,24 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
contains("test1.signature")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].hashes.md5",
contains(artifactSignature.getMd5Hash())))
- .andExpect(
- jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].hashes.sha1",
- contains(artifactSignature.getSha1Hash())))
- .andExpect(
- jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.download.href",
- contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant()
- + "/controller/v1/4712/softwaremodules/"
- + findDistributionSetByAction.findFirstModuleByType(osType).getId()
+ .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1].hashes.sha1",
+ contains(artifactSignature.getSha1Hash())))
+ .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.download.href",
+ contains(
+ HTTP_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/"
+ + findDistributionSetByAction.findFirstModuleByType(osType).get().getId()
+ "/artifacts/test1.signature")))
- .andExpect(
- jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.md5sum.href",
- contains(HTTP_LOCALHOST + tenantAware.getCurrentTenant()
- + "/controller/v1/4712/softwaremodules/"
- + findDistributionSetByAction.findFirstModuleByType(osType).getId()
+ .andExpect(jsonPath("$.deployment.chunks[?(@.part==os)].artifacts[1]._links.md5sum.href",
+ contains(
+ HTTP_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/4712/softwaremodules/"
+ + findDistributionSetByAction.findFirstModuleByType(osType).get().getId()
+ "/artifacts/test1.signature.MD5SUM")))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].version",
- contains(ds.findFirstModuleByType(appType).getVersion())))
+ contains(ds.findFirstModuleByType(appType).get().getVersion())))
.andExpect(jsonPath("$.deployment.chunks[?(@.part==bApp)].name",
- contains(ds.findFirstModuleByType(appType).getName())));
- assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
+ contains(ds.findFirstModuleByType(appType).get().getName())));
+ assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current);
// Retrieved is reported
@@ -538,7 +528,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
final DistributionSet savedSet = testdataFactory.createDistributionSet("");
final Action action1 = deploymentManagement
- .findActionWithDetails(assignDistributionSet(savedSet, toAssign).getActions().get(0));
+ .findActionWithDetails(assignDistributionSet(savedSet, toAssign).getActions().get(0)).get();
mvc.perform(
get("/{tenant}/controller/v1/4712/deploymentBase/" + action1.getId(), tenantAware.getCurrentTenant()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
@@ -589,13 +579,13 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
toAssign.add(savedTarget1);
final Action action1 = deploymentManagement
- .findActionWithDetails(assignDistributionSet(ds1.getId(), "4712").getActions().get(0));
+ .findActionWithDetails(assignDistributionSet(ds1.getId(), "4712").getActions().get(0)).get();
final Action action2 = deploymentManagement
- .findActionWithDetails(assignDistributionSet(ds2.getId(), "4712").getActions().get(0));
+ .findActionWithDetails(assignDistributionSet(ds2.getId(), "4712").getActions().get(0)).get();
final Action action3 = deploymentManagement
- .findActionWithDetails(assignDistributionSet(ds3.getId(), "4712").getActions().get(0));
+ .findActionWithDetails(assignDistributionSet(ds3.getId(), "4712").getActions().get(0)).get();
- Target myT = targetManagement.findTargetByControllerID("4712");
+ Target myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(3);
assertThat(myT.getAssignedDistributionSet()).isEqualTo(ds3);
@@ -611,7 +601,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.deploymentActionFeedback(action1.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- myT = targetManagement.findTargetByControllerIDWithDetails("4712");
+ myT = targetManagement.findTargetByControllerIDWithDetails("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
@@ -631,7 +621,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.deploymentActionFeedback(action2.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- myT = targetManagement.findTargetByControllerIDWithDetails("4712");
+ myT = targetManagement.findTargetByControllerIDWithDetails("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
@@ -651,7 +641,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.deploymentActionFeedback(action3.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- myT = targetManagement.findTargetByControllerID("4712");
+ myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC);
@@ -671,10 +661,10 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
DistributionSet ds = testdataFactory.createDistributionSet("");
final Target savedTarget = testdataFactory.createTarget("4712");
- List toAssign = new ArrayList<>();
+ final List toAssign = new ArrayList<>();
toAssign.add(savedTarget);
- assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus())
+ assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.UNKNOWN);
assignDistributionSet(ds, toAssign);
final Action action = deploymentManagement.findActionsByDistributionSet(pageReq, ds.getId()).getContent()
@@ -687,10 +677,10 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
"error message"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- Target myT = targetManagement.findTargetByControllerID("4712");
+ Target myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
- assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus())
+ assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.ERROR);
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.PENDING))
.hasSize(0);
@@ -706,10 +696,8 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
assertThat(actionStatusMessages).haveAtLeast(1, new ActionStatusCondition(Status.ERROR));
// redo
- toAssign = new ArrayList<>();
- toAssign.add(targetManagement.findTargetByControllerID("4712"));
- ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId());
- assignDistributionSet(ds, toAssign);
+ ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId()).get();
+ assignDistributionSet(ds, Lists.newArrayList(targetManagement.findTargetByControllerID("4712").get()));
final Action action2 = deploymentManagement.findActiveActionsByTarget(myT.getControllerId()).get(0);
current = System.currentTimeMillis();
@@ -719,7 +707,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- myT = targetManagement.findTargetByControllerID("4712");
+ myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC);
@@ -748,13 +736,13 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
final List toAssign = Lists.newArrayList(savedTarget);
- Target myT = targetManagement.findTargetByControllerID("4712");
+ Target myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.UNKNOWN);
assignDistributionSet(ds, toAssign);
final Action action = deploymentManagement.findActionsByDistributionSet(pageReq, ds.getId()).getContent()
.get(0);
- myT = targetManagement.findTargetByControllerID("4712");
+ myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(targetManagement.findTargetByInstalledDistributionSet(ds.getId(), pageReq)).hasSize(0);
assertThat(targetManagement.findTargetByAssignedDistributionSet(ds.getId(), pageReq)).hasSize(1);
@@ -771,7 +759,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
}
- myT = targetManagement.findTargetByControllerID("4712");
+ myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.PENDING))
@@ -791,7 +779,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "scheduled"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- myT = targetManagement.findTargetByControllerID("4712");
+ myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.PENDING))
@@ -811,7 +799,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "resumed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- myT = targetManagement.findTargetByControllerID("4712");
+ myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.PENDING))
@@ -831,7 +819,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "canceled"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- myT = targetManagement.findTargetByControllerID("4712");
+ myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(1);
@@ -854,7 +842,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "rejected"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- myT = targetManagement.findTargetByControllerID("4712");
+ myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(1);
@@ -872,7 +860,7 @@ public class DdiDeploymentBaseTest extends AbstractDDiApiIntegrationTest {
.content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "closed"))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- myT = targetManagement.findTargetByControllerID("4712");
+ myT = targetManagement.findTargetByControllerID("4712").get();
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC);
assertThat(deploymentManagement.findActiveActionsByTarget(myT.getControllerId())).hasSize(0);
diff --git a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootControllerTest.java b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootControllerTest.java
index e7f84f88c..f12d8ec25 100644
--- a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootControllerTest.java
+++ b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootControllerTest.java
@@ -8,11 +8,11 @@
*/
package org.eclipse.hawkbit.ddi.rest.resource;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions.CONTROLLER_ROLE;
import static org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions.CONTROLLER_ROLE_ANONYMOUS;
import static org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions.HAS_AUTH_TENANT_CONFIGURATION;
import static org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions.SYSTEM_ROLE;
-import static org.fest.assertions.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
@@ -99,7 +99,8 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
final String knownTargetControllerId = "target1";
final String knownCreatedBy = "knownPrincipal";
testdataFactory.createTarget(knownTargetControllerId);
- final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownTargetControllerId);
+ final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownTargetControllerId)
+ .get();
assertThat(findTargetByControllerID.getCreatedBy()).isEqualTo(knownCreatedBy);
assertThat(findTargetByControllerID.getCreatedAt()).isNotNull();
@@ -112,7 +113,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
});
// verify that audit information has not changed
- final Target targetVerify = targetManagement.findTargetByControllerID(knownTargetControllerId);
+ final Target targetVerify = targetManagement.findTargetByControllerID(knownTargetControllerId).get();
assertThat(targetVerify.getCreatedBy()).isEqualTo(findTargetByControllerID.getCreatedBy());
assertThat(targetVerify.getCreatedAt()).isEqualTo(findTargetByControllerID.getCreatedAt());
assertThat(targetVerify.getLastModifiedBy()).isEqualTo(findTargetByControllerID.getLastModifiedBy());
@@ -137,10 +138,10 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
mvc.perform(get("/default-tenant/controller/v1/4711")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()).andExpect(content().contentType(APPLICATION_JSON_HAL_UTF))
.andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00")));
- assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getLastTargetQuery())
+ assertThat(targetManagement.findTargetByControllerID("4711").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current);
- assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getUpdateStatus())
+ assertThat(targetManagement.findTargetByControllerID("4711").get().getTargetInfo().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.REGISTERED);
// not allowed methods
@@ -194,7 +195,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant()).header("If-None-Match", etag))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotModified());
- final Target target = targetManagement.findTargetByControllerID("4711");
+ final Target target = targetManagement.findTargetByControllerID("4711").get();
final DistributionSet ds = testdataFactory.createDistributionSet("");
assignDistributionSet(ds.getId(), "4711");
@@ -253,7 +254,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
public void rootRsPrecommissioned() throws Exception {
final Target target = testdataFactory.createTarget("4711");
- assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getUpdateStatus())
+ assertThat(targetManagement.findTargetByControllerID("4711").get().getTargetInfo().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.UNKNOWN);
final long current = System.currentTimeMillis();
@@ -262,12 +263,12 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
.andExpect(content().contentType(APPLICATION_JSON_HAL_UTF))
.andExpect(jsonPath("$.config.polling.sleep", equalTo("00:01:00")));
- assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getLastTargetQuery())
+ assertThat(targetManagement.findTargetByControllerID("4711").get().getTargetInfo().getLastTargetQuery())
.isLessThanOrEqualTo(System.currentTimeMillis());
- assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getLastTargetQuery())
+ assertThat(targetManagement.findTargetByControllerID("4711").get().getTargetInfo().getLastTargetQuery())
.isGreaterThanOrEqualTo(current);
- assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getUpdateStatus())
+ assertThat(targetManagement.findTargetByControllerID("4711").get().getTargetInfo().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.REGISTERED);
}
@@ -282,7 +283,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
// verify
- final Target target = targetManagement.findTargetByControllerID(knownControllerId1);
+ final Target target = targetManagement.findTargetByControllerID(knownControllerId1).get();
assertThat(target.getTargetInfo().getAddress()).isEqualTo(IpUtil.createHttpUri("127.0.0.1"));
}
@@ -300,7 +301,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
// verify
- final Target target = targetManagement.findTargetByControllerID(knownControllerId1);
+ final Target target = targetManagement.findTargetByControllerID(knownControllerId1).get();
assertThat(target.getTargetInfo().getAddress()).isEqualTo(IpUtil.createHttpUri("***"));
securityProperties.getClients().setTrackRemoteIp(true);
diff --git a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DosFilterTest.java b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DosFilterTest.java
index d2d4c5c80..c1f4e2424 100644
--- a/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DosFilterTest.java
+++ b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DosFilterTest.java
@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.ddi.rest.resource;
-import static org.fest.assertions.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
diff --git a/hawkbit-dmf-amqp/pom.xml b/hawkbit-dmf-amqp/pom.xml
index 540b4d53d..9547797f7 100644
--- a/hawkbit-dmf-amqp/pom.xml
+++ b/hawkbit-dmf-amqp/pom.xml
@@ -122,21 +122,6 @@
spring-boot-starter-testtest
-
- org.springframework
- spring-test
- test
-
-
- org.easytesting
- fest-assert-core
- test
-
-
- org.easytesting
- fest-assert
- test
- org.springframework.securityspring-security-config
diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpAuthenticationMessageHandler.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpAuthenticationMessageHandler.java
index 11b20b726..edb493116 100644
--- a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpAuthenticationMessageHandler.java
+++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpAuthenticationMessageHandler.java
@@ -155,21 +155,26 @@ public class AmqpAuthenticationMessageHandler extends BaseAmqpService {
LOG.info("download security check for target {} and artifact {} granted", controllerId, sha1Hash);
}
- private Optional findArtifactByFileResource(final FileResource fileResource) {
+ private Optional findArtifactByFileResource(
+ final FileResource fileResource) {
if (fileResource.getSha1() != null) {
- return Optional.ofNullable(fileResource.getSha1());
- } else if (fileResource.getFilename() != null) {
- return artifactManagement.findArtifactByFilename(fileResource.getFilename()).stream().findFirst()
- .map(org.eclipse.hawkbit.repository.model.Artifact::getSha1Hash);
- } else if (fileResource.getArtifactId() != null) {
- return Optional.ofNullable(artifactManagement.findArtifact(fileResource.getArtifactId()))
- .map(org.eclipse.hawkbit.repository.model.Artifact::getSha1Hash);
- } else if (fileResource.getSoftwareModuleFilenameResource() != null) {
- return artifactManagement
- .findByFilenameAndSoftwareModule(fileResource.getSoftwareModuleFilenameResource().getFilename(),
- fileResource.getSoftwareModuleFilenameResource().getSoftwareModuleId())
- .stream().findFirst().map(org.eclipse.hawkbit.repository.model.Artifact::getSha1Hash);
+ return artifactManagement.findFirstArtifactBySHA1(fileResource.getSha1());
}
+
+ if (fileResource.getFilename() != null) {
+ return artifactManagement.findArtifactByFilename(fileResource.getFilename());
+ }
+
+ if (fileResource.getArtifactId() != null) {
+ return artifactManagement.findArtifact(fileResource.getArtifactId());
+ }
+
+ if (fileResource.getSoftwareModuleFilenameResource() != null) {
+ return artifactManagement.findByFilenameAndSoftwareModule(
+ fileResource.getSoftwareModuleFilenameResource().getFilename(),
+ fileResource.getSoftwareModuleFilenameResource().getSoftwareModuleId());
+ }
+
return Optional.empty();
}
@@ -190,24 +195,20 @@ public class AmqpAuthenticationMessageHandler extends BaseAmqpService {
try {
SecurityContextHolder.getContext().setAuthentication(authenticationManager.doAuthenticate(secruityToken));
- final Optional sha1Hash = findArtifactByFileResource(fileResource);
+ final String sha1Hash = findArtifactByFileResource(fileResource)
+ .map(org.eclipse.hawkbit.repository.model.Artifact::getSha1Hash)
+ .orElseThrow(() -> new EntityNotFoundException());
- if (!sha1Hash.isPresent()) {
- LOG.info("target {} requested file resource {} which does not exists to download",
- secruityToken.getControllerId(), fileResource);
- throw new EntityNotFoundException();
- }
+ checkIfArtifactIsAssignedToTarget(secruityToken, sha1Hash);
- checkIfArtifactIsAssignedToTarget(secruityToken, sha1Hash.get());
-
- final Artifact artifact = convertDbArtifact(artifactManagement.loadArtifactBinary(sha1Hash.get()));
+ final Artifact artifact = convertDbArtifact(artifactManagement.loadArtifactBinary(sha1Hash));
if (artifact == null) {
throw new EntityNotFoundException();
}
authentificationResponse.setArtifact(artifact);
final String downloadId = UUID.randomUUID().toString();
// SHA1 key is set, download by SHA1
- final DownloadArtifactCache downloadCache = new DownloadArtifactCache(DownloadType.BY_SHA1, sha1Hash.get());
+ final DownloadArtifactCache downloadCache = new DownloadArtifactCache(DownloadType.BY_SHA1, sha1Hash);
cache.put(downloadId, downloadCache);
authentificationResponse
.setDownloadUrl(UriComponentsBuilder.fromUri(hostnameResolver.resolveHostname().toURI())
diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherService.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherService.java
index 6a22fa0ab..db35bb89f 100644
--- a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherService.java
+++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherService.java
@@ -103,8 +103,8 @@ public class AmqpMessageDispatcherService extends BaseAmqpService {
}
sendUpdateMessageToTarget(assignedEvent.getTenant(),
- targetManagement.findTargetByControllerID(assignedEvent.getControllerId()), assignedEvent.getActionId(),
- assignedEvent.getModules());
+ targetManagement.findTargetByControllerID(assignedEvent.getControllerId()).get(),
+ assignedEvent.getActionId(), assignedEvent.getModules());
}
void sendUpdateMessageToTarget(final String tenant, final Target target, final Long actionId,
diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerService.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerService.java
index a56be2088..9cb9f5118 100644
--- a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerService.java
+++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerService.java
@@ -28,7 +28,6 @@ import org.eclipse.hawkbit.repository.ControllerManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.RepositoryConstants;
import org.eclipse.hawkbit.repository.builder.ActionStatusCreate;
-import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.Target;
@@ -317,6 +316,9 @@ public class AmqpMessageHandlerService extends BaseAmqpService {
return controllerManagement.addUpdateActionStatus(actionStatus);
}
+ // Exception squid:S3655 - logAndThrowMessageError throws exception, i.e.
+ // get will not be called
+ @SuppressWarnings("squid:S3655")
private Action checkActionExist(final Message message, final ActionUpdateStatus actionUpdateStatus) {
final Long actionId = actionUpdateStatus.getActionId();
LOG.debug("Target notifies intermediate about action {} with status {}.", actionId,
@@ -326,17 +328,12 @@ public class AmqpMessageHandlerService extends BaseAmqpService {
logAndThrowMessageError(message, "Invalid message no action id");
}
- try {
- final Action findActionWithDetails = controllerManagement.findActionWithDetails(actionId);
- if (findActionWithDetails == null) {
- logAndThrowMessageError(message,
- "Got intermediate notification about action " + actionId + " but action does not exist");
- }
- return findActionWithDetails;
- } catch (@SuppressWarnings("squid:S1166") final EntityNotFoundException e) {
+ final Optional findActionWithDetails = controllerManagement.findActionWithDetails(actionId);
+ if (!findActionWithDetails.isPresent()) {
logAndThrowMessageError(message,
"Got intermediate notification about action " + actionId + " but action does not exist");
}
- return null;
+
+ return findActionWithDetails.get();
}
}
diff --git a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthenticationTest.java b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthenticationTest.java
index e8ff41d93..659537fed 100644
--- a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthenticationTest.java
+++ b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpControllerAuthenticationTest.java
@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.amqp;
-import static org.fest.assertions.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
@@ -17,6 +17,7 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.net.URL;
+import java.util.Optional;
import org.eclipse.hawkbit.api.HostnameResolver;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
@@ -134,8 +135,8 @@ public class AmqpControllerAuthenticationTest {
.thenReturn(CONFIG_VALUE_FALSE);
final ControllerManagement controllerManagement = mock(ControllerManagement.class);
- when(controllerManagement.findByControllerId(anyString())).thenReturn(targteMock);
- when(controllerManagement.findByTargetId(any(Long.class))).thenReturn(targteMock);
+ when(controllerManagement.findByControllerId(anyString())).thenReturn(Optional.of(targteMock));
+ when(controllerManagement.findByTargetId(any(Long.class))).thenReturn(Optional.of(targteMock));
when(targteMock.getSecurityToken()).thenReturn(CONTROLLER_ID);
when(targteMock.getControllerId()).thenReturn(CONTROLLER_ID);
@@ -156,8 +157,8 @@ public class AmqpControllerAuthenticationTest {
new JpaSoftwareModuleType("a key", "a name", null, 1), "a name", null, null, null));
testArtifact.setId(1L);
- when(artifactManagementMock.findArtifact(ARTIFACT_ID)).thenReturn(testArtifact);
- when(artifactManagementMock.findFirstArtifactBySHA1(SHA1)).thenReturn(testArtifact);
+ when(artifactManagementMock.findArtifact(ARTIFACT_ID)).thenReturn(Optional.of(testArtifact));
+ when(artifactManagementMock.findFirstArtifactBySHA1(SHA1)).thenReturn(Optional.of(testArtifact));
final DbArtifact artifact = new DbArtifact();
artifact.setSize(ARTIFACT_SIZE);
diff --git a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherServiceTest.java b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherServiceTest.java
index 38406fb00..96d5eaf87 100644
--- a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherServiceTest.java
+++ b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherServiceTest.java
@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.amqp;
-import static org.fest.assertions.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@@ -126,13 +126,13 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest {
private Message getCaptureAdressEvent(final TargetAssignDistributionSetEvent targetAssignDistributionSetEvent) {
final Target target = targetManagement
- .findTargetByControllerID(targetAssignDistributionSetEvent.getControllerId());
+ .findTargetByControllerID(targetAssignDistributionSetEvent.getControllerId()).get();
final Message sendMessage = createArgumentCapture(target.getTargetInfo().getAddress());
return sendMessage;
}
private Action createAction(final DistributionSet testDs) {
- return deploymentManagement.findAction(assignDistributionSet(testDs, testTarget).getActions().get(0));
+ return deploymentManagement.findAction(assignDistributionSet(testDs, testTarget).getActions().get(0)).get();
}
@Test
@@ -177,8 +177,8 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest {
for (final Artifact artifact : testdataFactory.createArtifacts(module.getId())) {
receivedList.add(new DbArtifact());
}
- module = softwareManagement.findSoftwareModuleById(module.getId());
- dsA = distributionSetManagement.findDistributionSetById(dsA.getId());
+ module = softwareManagement.findSoftwareModuleById(module.getId()).get();
+ dsA = distributionSetManagement.findDistributionSetById(dsA.getId()).get();
final Action action = createAction(dsA);
@@ -205,7 +205,7 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest {
module.getArtifacts().forEach(dbArtifact -> {
final Optional found = softwareModule.getArtifacts()
.stream().filter(dmfartifact -> dmfartifact.getFilename().equals(dbArtifact.getFilename()))
- .findFirst();
+ .findAny();
assertTrue("The artifact should exist in message", found.isPresent());
assertThat(found.get().getSize()).isEqualTo(dbArtifact.getSize());
diff --git a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerServiceTest.java b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerServiceTest.java
index beeb90b62..fc64d10c1 100644
--- a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerServiceTest.java
+++ b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerServiceTest.java
@@ -8,8 +8,9 @@
*/
package org.eclipse.hawkbit.amqp;
-import static org.fest.assertions.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
+import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
@@ -126,6 +127,8 @@ public class AmqpMessageHandlerServiceTest {
public void before() throws Exception {
messageConverter = new Jackson2JsonMessageConverter();
when(rabbitTemplate.getMessageConverter()).thenReturn(messageConverter);
+ when(artifactManagementMock.findFirstArtifactBySHA1(SHA1)).thenReturn(Optional.empty());
+
amqpMessageHandlerService = new AmqpMessageHandlerService(rabbitTemplate, amqpMessageDispatcherServiceMock,
controllerManagementMock, entityFactoryMock);
@@ -163,7 +166,7 @@ public class AmqpMessageHandlerServiceTest {
final ArgumentCaptor uriCaptor = ArgumentCaptor.forClass(URI.class);
when(controllerManagementMock.findOrRegisterTargetIfItDoesNotexist(targetIdCaptor.capture(),
uriCaptor.capture())).thenReturn(targetMock);
- when(controllerManagementMock.findOldestActiveActionByTarget(Matchers.any())).thenReturn(Optional.empty());
+ when(controllerManagementMock.findOldestActiveActionByTarget(any())).thenReturn(Optional.empty());
amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT, "vHost");
@@ -295,6 +298,8 @@ public class AmqpMessageHandlerServiceTest {
public void updateActionStatusWithoutExistActionId() {
final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT);
messageProperties.setHeader(MessageHeaderKey.TOPIC, EventTopic.UPDATE_ACTION_STATUS.name());
+ when(controllerManagementMock.findActionWithDetails(any())).thenReturn(Optional.empty());
+
final ActionUpdateStatus actionUpdateStatus = createActionUpdateStatus(ActionStatus.DOWNLOAD);
final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(actionUpdateStatus,
messageProperties);
@@ -337,7 +342,7 @@ public class AmqpMessageHandlerServiceTest {
messageProperties);
final Artifact localArtifactMock = mock(Artifact.class);
- when(artifactManagementMock.findFirstArtifactBySHA1(anyString())).thenReturn(localArtifactMock);
+ when(artifactManagementMock.findFirstArtifactBySHA1(anyString())).thenReturn(Optional.of(localArtifactMock));
when(controllerManagementMock.getActionForDownloadByTargetAndSoftwareModule(anyObject(), anyObject()))
.thenThrow(EntityNotFoundException.class);
@@ -365,7 +370,7 @@ public class AmqpMessageHandlerServiceTest {
when(localArtifactMock.getSha1Hash()).thenReturn(SHA1);
final DbArtifact dbArtifactMock = mock(DbArtifact.class);
- when(artifactManagementMock.findFirstArtifactBySHA1(SHA1)).thenReturn(localArtifactMock);
+ when(artifactManagementMock.findFirstArtifactBySHA1(SHA1)).thenReturn(Optional.of(localArtifactMock));
when(controllerManagementMock.hasTargetArtifactAssigned(securityToken.getControllerId(), SHA1))
.thenReturn(true);
when(artifactManagementMock.loadArtifactBinary(anyString())).thenReturn(dbArtifactMock);
@@ -395,15 +400,15 @@ public class AmqpMessageHandlerServiceTest {
// Mock
final Action action = createActionWithTarget(22L, Status.FINISHED);
- when(controllerManagementMock.findActionWithDetails(Matchers.any())).thenReturn(action);
- when(controllerManagementMock.addUpdateActionStatus(Matchers.any())).thenReturn(action);
+ when(controllerManagementMock.findActionWithDetails(any())).thenReturn(Optional.of(action));
+ when(controllerManagementMock.addUpdateActionStatus(any())).thenReturn(action);
final ActionStatusBuilder builder = mock(ActionStatusBuilder.class);
final ActionStatusCreate create = mock(ActionStatusCreate.class);
when(builder.create(22L)).thenReturn(create);
- when(create.status(Matchers.any())).thenReturn(create);
+ when(create.status(any())).thenReturn(create);
when(entityFactoryMock.actionStatus()).thenReturn(builder);
// for the test the same action can be used
- when(controllerManagementMock.findOldestActiveActionByTarget(Matchers.any())).thenReturn(Optional.of(action));
+ when(controllerManagementMock.findOldestActiveActionByTarget(any())).thenReturn(Optional.of(action));
final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT);
messageProperties.setHeader(MessageHeaderKey.TOPIC, EventTopic.UPDATE_ACTION_STATUS.name());
@@ -415,14 +420,14 @@ public class AmqpMessageHandlerServiceTest {
amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, "vHost");
// verify
- verify(controllerManagementMock).updateLastTargetQuery(Matchers.any(String.class), Matchers.isNull(URI.class));
+ verify(controllerManagementMock).updateLastTargetQuery(any(String.class), Matchers.isNull(URI.class));
final ArgumentCaptor tenantCaptor = ArgumentCaptor.forClass(String.class);
final ArgumentCaptor targetCaptor = ArgumentCaptor.forClass(Target.class);
final ArgumentCaptor actionIdCaptor = ArgumentCaptor.forClass(Long.class);
verify(amqpMessageDispatcherServiceMock, times(1)).sendUpdateMessageToTarget(tenantCaptor.capture(),
- targetCaptor.capture(), actionIdCaptor.capture(), Matchers.any(Collection.class));
+ targetCaptor.capture(), actionIdCaptor.capture(), any(Collection.class));
final String tenant = tenantCaptor.getValue();
final String controllerId = targetCaptor.getValue().getControllerId();
final Long actionId = actionIdCaptor.getValue();
diff --git a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/BaseAmqpServiceTest.java b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/BaseAmqpServiceTest.java
index 582bcf130..88da037d5 100644
--- a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/BaseAmqpServiceTest.java
+++ b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/BaseAmqpServiceTest.java
@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.amqp;
-import static org.fest.assertions.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
@@ -61,7 +61,7 @@ public class BaseAmqpServiceTest {
ActionUpdateStatus.class);
assertThat(convertedActionUpdateStatus).as("Converted Action Status is wrong")
- .isEqualsToByComparingFields(actionUpdateStatus);
+ .isEqualToComparingFieldByField(actionUpdateStatus);
convertedActionUpdateStatus = baseAmqpService.convertMessage(null, ActionUpdateStatus.class);
assertThat(convertedActionUpdateStatus).as("Converted Object should be null when message is null").isNull();
diff --git a/hawkbit-http-security/pom.xml b/hawkbit-http-security/pom.xml
index 6ac1456b9..283c6e603 100644
--- a/hawkbit-http-security/pom.xml
+++ b/hawkbit-http-security/pom.xml
@@ -47,16 +47,6 @@
spring-boot-starter-testtest
-
- org.easytesting
- fest-assert-core
- test
-
-
- org.easytesting
- fest-assert
- test
- ru.yandex.qatools.allureallure-junit-adaptor
diff --git a/hawkbit-http-security/src/test/java/org/eclipse/hawkbit/security/PreAuthTokenSourceTrustAuthenticationProviderTest.java b/hawkbit-http-security/src/test/java/org/eclipse/hawkbit/security/PreAuthTokenSourceTrustAuthenticationProviderTest.java
index 28e9708ac..3f83a970c 100644
--- a/hawkbit-http-security/src/test/java/org/eclipse/hawkbit/security/PreAuthTokenSourceTrustAuthenticationProviderTest.java
+++ b/hawkbit-http-security/src/test/java/org/eclipse/hawkbit/security/PreAuthTokenSourceTrustAuthenticationProviderTest.java
@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.security;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.when;
diff --git a/hawkbit-mgmt-api/pom.xml b/hawkbit-mgmt-api/pom.xml
index b6b316f6e..2c916aa54 100644
--- a/hawkbit-mgmt-api/pom.xml
+++ b/hawkbit-mgmt-api/pom.xml
@@ -35,8 +35,8 @@
- org.easytesting
- fest-assert
+ org.springframework.boot
+ spring-boot-starter-testtest
diff --git a/hawkbit-mgmt-api/src/test/java/org/eclipse/hawkbit/mgmt/json/model/PagedListTest.java b/hawkbit-mgmt-api/src/test/java/org/eclipse/hawkbit/mgmt/json/model/PagedListTest.java
index c17acb3b1..d5b089868 100644
--- a/hawkbit-mgmt-api/src/test/java/org/eclipse/hawkbit/mgmt/json/model/PagedListTest.java
+++ b/hawkbit-mgmt-api/src/test/java/org/eclipse/hawkbit/mgmt/json/model/PagedListTest.java
@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.mgmt.json.model;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import java.util.ArrayList;
diff --git a/hawkbit-mgmt-resource/pom.xml b/hawkbit-mgmt-resource/pom.xml
index 20848b483..db23a3e18 100644
--- a/hawkbit-mgmt-resource/pom.xml
+++ b/hawkbit-mgmt-resource/pom.xml
@@ -126,16 +126,6 @@
spring-security-aspectstest
-
- org.easytesting
- fest-assert-core
- test
-
-
- org.easytesting
- fest-assert
- test
- ru.yandex.qatools.allureallure-junit-adaptor
diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResource.java
index 4b14a2e5b..52ff45fb2 100644
--- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResource.java
+++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResource.java
@@ -162,10 +162,6 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) {
- // check if distribution set exists otherwise throw exception
- // immediately
- findDistributionSetWithExceptionIfNotFound(distributionSetId);
-
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeTargetSortParam(sortParam);
@@ -256,10 +252,6 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) {
- // check if distribution set exists otherwise throw exception
- // immediately
- findDistributionSetWithExceptionIfNotFound(distributionSetId);
-
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeDistributionSetMetadataSortParam(sortParam);
@@ -288,9 +280,11 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
@PathVariable("metadataKey") final String metadataKey) {
// check if distribution set exists otherwise throw exception
// immediately
- final DistributionSetMetadata findOne = distributionSetManagement.findDistributionSetMetadata(distributionSetId,
- metadataKey);
- return ResponseEntity. ok(MgmtDistributionSetMapper.toResponseDsMetadata(findOne));
+ final DistributionSetMetadata findOne = distributionSetManagement
+ .findDistributionSetMetadata(distributionSetId, metadataKey)
+ .orElseThrow(() -> new EntityNotFoundException(DistributionSetMetadata.class, distributionSetId,
+ metadataKey));
+ return ResponseEntity.ok(MgmtDistributionSetMapper.toResponseDsMetadata(findOne));
}
@Override
@@ -347,9 +341,7 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
@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) {
- // check if distribution set exists otherwise throw exception
- // immediately
- findDistributionSetWithExceptionIfNotFound(distributionSetId);
+
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeSoftwareModuleSortParam(sortParam);
@@ -361,11 +353,7 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
}
private DistributionSet findDistributionSetWithExceptionIfNotFound(final Long distributionSetId) {
- final DistributionSet set = distributionSetManagement.findDistributionSetById(distributionSetId);
- if (set == null) {
- throw new EntityNotFoundException("DistributionSet with Id {" + distributionSetId + "} does not exist");
- }
-
- return set;
+ return distributionSetManagement.findDistributionSetById(distributionSetId)
+ .orElseThrow(() -> new EntityNotFoundException(DistributionSet.class, distributionSetId));
}
}
diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResource.java
index 28814bbbe..10da9b8d0 100644
--- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResource.java
+++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResource.java
@@ -194,16 +194,13 @@ public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRes
}
private DistributionSetTag findDistributionTagById(final Long distributionsetTagId) {
- final DistributionSetTag tag = this.tagManagement.findDistributionSetTagById(distributionsetTagId);
- if (tag == null) {
- throw new EntityNotFoundException("Distribution Tag with Id {" + distributionsetTagId + "} does not exist");
- }
- return tag;
+ return tagManagement.findDistributionSetTagById(distributionsetTagId)
+ .orElseThrow(() -> new EntityNotFoundException(DistributionSetTag.class, distributionsetTagId));
}
private static List findDistributionSetIds(
final List assignedDistributionSetRequestBodies) {
- return assignedDistributionSetRequestBodies.stream().map(request -> request.getDistributionSetId())
- .collect(Collectors.toList());
+ return assignedDistributionSetRequestBodies.stream()
+ .map(MgmtAssignedDistributionSetRequestBody::getDistributionSetId).collect(Collectors.toList());
}
}
diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResource.java
index 7a83318c5..a5a053c52 100644
--- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResource.java
+++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResource.java
@@ -29,6 +29,7 @@ import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
+import org.eclipse.hawkbit.repository.exception.SoftwareModuleTypeNotInDistributionSetTypeException;
import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
@@ -100,7 +101,6 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
@Override
public ResponseEntity deleteDistributionSetType(
@PathVariable("distributionSetTypeId") final Long distributionSetTypeId) {
-
distributionSetManagement.deleteDistributionSetType(distributionSetTypeId);
return ResponseEntity.ok().build();
@@ -127,14 +127,8 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
}
private DistributionSetType findDistributionSetTypeWithExceptionIfNotFound(final Long distributionSetTypeId) {
-
- final DistributionSetType module = distributionSetManagement.findDistributionSetTypeById(distributionSetTypeId);
- if (module == null) {
- throw new EntityNotFoundException(
- "DistributionSetType with Id {" + distributionSetTypeId + "} does not exist");
- }
-
- return module;
+ return distributionSetManagement.findDistributionSetTypeById(distributionSetTypeId)
+ .orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, distributionSetTypeId));
}
@Override
@@ -154,8 +148,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
final SoftwareModuleType foundSmType = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId);
if (!foundType.containsMandatoryModuleType(foundSmType)) {
- throw new EntityNotFoundException(
- "Software module with given ID is not part of this distribution set type!");
+ throw new SoftwareModuleTypeNotInDistributionSetTypeException(softwareModuleTypeId, distributionSetTypeId);
}
return ResponseEntity.ok(toResponse(foundSmType));
@@ -170,8 +163,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
final SoftwareModuleType foundSmType = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId);
if (!foundType.containsOptionalModuleType(foundSmType)) {
- throw new EntityNotFoundException(
- "Software module with given ID is not part of this distribution set type!");
+ throw new SoftwareModuleTypeNotInDistributionSetTypeException(softwareModuleTypeId, distributionSetTypeId);
}
return ResponseEntity.ok(toResponse(foundSmType));
@@ -224,12 +216,7 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR
private SoftwareModuleType findSoftwareModuleTypeWithExceptionIfNotFound(final Long softwareModuleTypeId) {
- final SoftwareModuleType module = softwareManagement.findSoftwareModuleTypeById(softwareModuleTypeId);
- if (module == null) {
- throw new EntityNotFoundException(
- "SoftwareModuleType with Id {" + softwareModuleTypeId + "} does not exist");
- }
-
- return module;
+ return softwareManagement.findSoftwareModuleTypeById(softwareModuleTypeId)
+ .orElseThrow(() -> new EntityNotFoundException(SoftwareModuleType.class, softwareModuleTypeId));
}
}
diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadArtifactResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadArtifactResource.java
index c567752e4..fef438cee 100644
--- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadArtifactResource.java
+++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadArtifactResource.java
@@ -81,11 +81,10 @@ public class MgmtDownloadArtifactResource implements MgmtDownloadArtifactRestApi
private SoftwareModule findSoftwareModuleWithExceptionIfNotFound(final Long softwareModuleId,
final Long artifactId) {
- final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId);
- if (module == null) {
- throw new EntityNotFoundException("SoftwareModule with Id {" + softwareModuleId + "} does not exist");
- } else if (artifactId != null && !module.getArtifact(artifactId).isPresent()) {
- throw new EntityNotFoundException("Artifact with Id {" + artifactId + "} does not exist");
+ final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId)
+ .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
+ if (artifactId != null && !module.getArtifact(artifactId).isPresent()) {
+ throw new EntityNotFoundException(Artifact.class, artifactId);
}
return module;
}
diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResource.java
index c5b80c3aa..b8e1830db 100644
--- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResource.java
+++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResource.java
@@ -50,9 +50,6 @@ import org.springframework.web.bind.annotation.RestController;
*/
@RestController
public class MgmtRolloutResource implements MgmtRolloutRestApi {
-
- private static final String DOES_NOT_EXIST = "} does not exist";
-
@Autowired
private RolloutManagement rolloutManagement;
@@ -94,7 +91,9 @@ public class MgmtRolloutResource implements MgmtRolloutRestApi {
@Override
public ResponseEntity getRollout(@PathVariable("rolloutId") final Long rolloutId) {
- final Rollout findRolloutById = findRolloutOrThrowException(rolloutId);
+ final Rollout findRolloutById = rolloutManagement.findRolloutWithDetailedStatus(rolloutId)
+ .orElseThrow(() -> new EntityNotFoundException(Rollout.class, rolloutId));
+
return new ResponseEntity<>(MgmtRolloutMapper.toResponseRollout(findRolloutById, true), HttpStatus.OK);
}
@@ -176,10 +175,18 @@ public class MgmtRolloutResource implements MgmtRolloutRestApi {
public ResponseEntity getRolloutGroup(@PathVariable("rolloutId") final Long rolloutId,
@PathVariable("groupId") final Long groupId) {
findRolloutOrThrowException(rolloutId);
- final RolloutGroup rolloutGroup = findRolloutGroupOrThrowException(groupId);
+
+ final RolloutGroup rolloutGroup = rolloutGroupManagement.findRolloutGroupWithDetailedStatus(groupId)
+ .orElseThrow(() -> new EntityNotFoundException(RolloutGroup.class, rolloutId));
return ResponseEntity.ok(MgmtRolloutMapper.toResponseRolloutGroup(rolloutGroup, true));
}
+ private void findRolloutOrThrowException(final Long rolloutId) {
+ if (!rolloutManagement.exists(rolloutId)) {
+ throw new EntityNotFoundException(Rollout.class, rolloutId);
+ }
+ }
+
@Override
public ResponseEntity> getRolloutGroupTargets(@PathVariable("rolloutId") final Long rolloutId,
@PathVariable("groupId") final Long groupId,
@@ -205,30 +212,10 @@ public class MgmtRolloutResource implements MgmtRolloutRestApi {
return new ResponseEntity<>(new PagedList<>(rest, rolloutGroupTargets.getTotalElements()), HttpStatus.OK);
}
- private Rollout findRolloutOrThrowException(final Long rolloutId) {
- final Rollout rollout = this.rolloutManagement.findRolloutWithDetailedStatus(rolloutId);
- if (rollout == null) {
- throw new EntityNotFoundException("Rollout with Id {" + rolloutId + DOES_NOT_EXIST);
- }
- return rollout;
- }
-
- private RolloutGroup findRolloutGroupOrThrowException(final Long rolloutGroupId) {
- final RolloutGroup rolloutGroup = this.rolloutGroupManagement
- .findRolloutGroupWithDetailedStatus(rolloutGroupId);
- if (rolloutGroup == null) {
- throw new EntityNotFoundException("Group with Id {" + rolloutGroupId + DOES_NOT_EXIST);
- }
- return rolloutGroup;
- }
-
private DistributionSet findDistributionSetOrThrowException(final MgmtRolloutRestRequestBody rolloutRequestBody) {
- final DistributionSet ds = this.distributionSetManagement
- .findDistributionSetById(rolloutRequestBody.getDistributionSetId());
- if (ds == null) {
- throw new EntityNotFoundException(
- "DistributionSet with Id {" + rolloutRequestBody.getDistributionSetId() + DOES_NOT_EXIST);
- }
- return ds;
+ return this.distributionSetManagement.findDistributionSetById(rolloutRequestBody.getDistributionSetId())
+ .orElseThrow(() -> new EntityNotFoundException(DistributionSet.class,
+ rolloutRequestBody.getDistributionSetId()));
+
}
}
diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResource.java
index 863f7eb5d..6f95a0f78 100644
--- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResource.java
+++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResource.java
@@ -228,8 +228,9 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
public ResponseEntity getMetadataValue(@PathVariable("softwareModuleId") final Long softwareModuleId,
@PathVariable("metadataKey") final String metadataKey) {
- final SoftwareModuleMetadata findOne = softwareManagement.findSoftwareModuleMetadata(softwareModuleId,
- metadataKey);
+ final SoftwareModuleMetadata findOne = softwareManagement
+ .findSoftwareModuleMetadata(softwareModuleId, metadataKey).orElseThrow(
+ () -> new EntityNotFoundException(SoftwareModuleMetadata.class, softwareModuleId, metadataKey));
return ResponseEntity.ok(toResponseSwMetadata(findOne));
}
@@ -265,12 +266,11 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi {
private SoftwareModule findSoftwareModuleWithExceptionIfNotFound(final Long softwareModuleId,
final Long artifactId) {
- final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId);
- if (module == null) {
- throw new EntityNotFoundException("SoftwareModule with Id {" + softwareModuleId + "} does not exist");
- }
+ final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId)
+ .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
+
if (artifactId != null && !module.getArtifact(artifactId).isPresent()) {
- throw new EntityNotFoundException("Artifact with Id {" + artifactId + "} does not exist");
+ throw new EntityNotFoundException(Artifact.class, artifactId);
}
return module;
diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResource.java
index 1c249089c..5d7fa3a6c 100644
--- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResource.java
+++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResource.java
@@ -115,12 +115,8 @@ public class MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRes
}
private SoftwareModuleType findSoftwareModuleTypeWithExceptionIfNotFound(final Long softwareModuleTypeId) {
- final SoftwareModuleType module = softwareManagement.findSoftwareModuleTypeById(softwareModuleTypeId);
- if (module == null) {
- throw new EntityNotFoundException(
- "SoftwareModuleType with Id {" + softwareModuleTypeId + "} does not exist");
- }
- return module;
+ return softwareManagement.findSoftwareModuleTypeById(softwareModuleTypeId)
+ .orElseThrow(() -> new EntityNotFoundException(SoftwareModuleType.class, softwareModuleTypeId));
}
}
diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryResource.java
index 15b375bd8..8adae8161 100644
--- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryResource.java
+++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryResource.java
@@ -111,7 +111,6 @@ public class MgmtTargetFilterQueryResource implements MgmtTargetFilterQueryRestA
@Override
public ResponseEntity deleteFilter(@PathVariable("filterId") final Long filterId) {
- findFilterWithExceptionIfNotFound(filterId);
filterManagement.deleteTargetFilterQuery(filterId);
LOG.debug("{} target filter query deleted, return status {}", filterId, HttpStatus.OK);
return new ResponseEntity<>(HttpStatus.OK);
@@ -145,11 +144,8 @@ public class MgmtTargetFilterQueryResource implements MgmtTargetFilterQueryRestA
}
private TargetFilterQuery findFilterWithExceptionIfNotFound(final Long filterId) {
- final TargetFilterQuery filter = filterManagement.findTargetFilterQueryById(filterId);
- if (filter == null) {
- throw new EntityNotFoundException("TargetFilterQuery with Id {" + filterId + "} does not exist");
- }
- return filter;
+ return filterManagement.findTargetFilterQueryById(filterId)
+ .orElseThrow(() -> new EntityNotFoundException(TargetFilterQuery.class, filterId));
}
}
diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResource.java
index a5b3e0a91..408c1c56c 100644
--- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResource.java
+++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResource.java
@@ -184,7 +184,8 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
public ResponseEntity getAction(@PathVariable("controllerId") final String controllerId,
@PathVariable("actionId") final Long actionId) {
- final Action action = findActionWithExceptionIfNotFound(actionId);
+ final Action action = deploymentManagement.findAction(actionId)
+ .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
if (!action.getTarget().getControllerId().equals(controllerId)) {
LOG.warn("given action ({}) is not assigned to given target ({}).", action.getId(), controllerId);
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
@@ -213,7 +214,8 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
public ResponseEntity cancelAction(@PathVariable("controllerId") final String controllerId,
@PathVariable("actionId") final Long actionId,
@RequestParam(value = "force", required = false, defaultValue = "false") final boolean force) {
- final Action action = findActionWithExceptionIfNotFound(actionId);
+ final Action action = deploymentManagement.findAction(actionId)
+ .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
if (!action.getTarget().getControllerId().equals(controllerId)) {
LOG.warn("given action ({}) is not assigned to given target ({}).", actionId, controllerId);
@@ -240,7 +242,9 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
final Target target = findTargetWithExceptionIfNotFound(controllerId);
- final Action action = findActionWithExceptionIfNotFound(actionId);
+ final Action action = deploymentManagement.findAction(actionId)
+ .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
+
if (!action.getTarget().getId().equals(target.getId())) {
LOG.warn("given action ({}) is not assigned to given target ({}).", action.getId(), target.getId());
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
@@ -311,19 +315,8 @@ public class MgmtTargetResource implements MgmtTargetRestApi {
}
private Target findTargetWithExceptionIfNotFound(final String controllerId) {
- final Target findTarget = this.targetManagement.findTargetByControllerID(controllerId);
- if (findTarget == null) {
- throw new EntityNotFoundException("Target with Id {" + controllerId + "} does not exist");
- }
- return findTarget;
- }
-
- private Action findActionWithExceptionIfNotFound(final Long actionId) {
- final Action findAction = this.deploymentManagement.findAction(actionId);
- if (findAction == null) {
- throw new EntityNotFoundException("Action with Id {" + actionId + "} does not exist");
- }
- return findAction;
+ return targetManagement.findTargetByControllerID(controllerId)
+ .orElseThrow(() -> new EntityNotFoundException(Target.class, controllerId));
}
}
diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResource.java
index 79a61ddc4..4c8e0dd85 100644
--- a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResource.java
+++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResource.java
@@ -173,11 +173,8 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi {
}
private TargetTag findTargetTagById(final Long targetTagId) {
- final TargetTag tag = this.tagManagement.findTargetTagById(targetTagId);
- if (tag == null) {
- throw new EntityNotFoundException("Target Tag with Id {" + targetTagId + "} does not exist");
- }
- return tag;
+ return tagManagement.findTargetTagById(targetTagId)
+ .orElseThrow(() -> new EntityNotFoundException(TargetTag.class, targetTagId));
}
private List findTargetControllerIds(
diff --git a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResourceTest.java
index 99495534f..8cc3ee00f 100644
--- a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResourceTest.java
+++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResourceTest.java
@@ -8,11 +8,10 @@
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
-import static org.fest.assertions.api.Assertions.assertThat;
+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.junit.Assert.fail;
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;
@@ -30,7 +29,6 @@ import java.util.Set;
import org.apache.commons.lang3.RandomStringUtils;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
-import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetMetadata;
@@ -42,7 +40,6 @@ import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.json.JSONArray;
-import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.springframework.context.annotation.Description;
@@ -54,6 +51,7 @@ import com.google.common.collect.Sets;
import com.jayway.jsonpath.JsonPath;
import ru.yandex.qatools.allure.annotations.Features;
+import ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.allure.annotations.Stories;
@Features("Component Tests - Management API")
@@ -427,7 +425,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.version("anotherVersion").requiredMigrationStep(true));
// load also lazy stuff
- set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId());
+ set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()).get();
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
.hasSize(1);
@@ -450,9 +448,9 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.andExpect(jsonPath("$.content.[0].lastModifiedAt", equalTo(set.getLastModifiedAt())))
.andExpect(jsonPath("$.content.[0].version", equalTo(set.getVersion())))
.andExpect(jsonPath("$.content.[0].modules.[?(@.type==" + runtimeType.getKey() + ")].id",
- contains(set.findFirstModuleByType(runtimeType).getId().intValue())))
+ contains(set.findFirstModuleByType(runtimeType).get().getId().intValue())))
.andExpect(jsonPath("$.content.[0].modules.[?(@.type==" + appType.getKey() + ")].id",
- contains(set.findFirstModuleByType(appType).getId().intValue())))
+ contains(set.findFirstModuleByType(appType).get().getId().intValue())))
.andExpect(jsonPath("$.content.[0].modules.[?(@.type==" + osType.getKey() + ")].id",
contains(getOsModule(set).intValue())));
}
@@ -481,9 +479,9 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.andExpect(jsonPath("$.lastModifiedAt", equalTo(set.getLastModifiedAt())))
.andExpect(jsonPath("$.version", equalTo(set.getVersion())))
.andExpect(jsonPath("$.modules.[?(@.type==" + runtimeType.getKey() + ")].id",
- contains(set.findFirstModuleByType(runtimeType).getId().intValue())))
+ contains(set.findFirstModuleByType(runtimeType).get().getId().intValue())))
.andExpect(jsonPath("$.modules.[?(@.type==" + appType.getKey() + ")].id",
- contains(set.findFirstModuleByType(appType).getId().intValue())))
+ contains(set.findFirstModuleByType(appType).get().getId().intValue())))
.andExpect(jsonPath("$.modules.[?(@.type==" + osType.getKey() + ")].id",
contains(getOsModule(set).intValue())));
@@ -492,7 +490,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Ensures that multipe DS posted to API are created in the repository.")
- public void createDistributionSets() throws JSONException, Exception {
+ public void createDistributionSets() throws Exception {
assertThat(distributionSetManagement.findDistributionSetsByDeletedAndOrCompleted(pageReq, false, true))
.hasSize(0);
@@ -507,61 +505,16 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
DistributionSet three = testdataFactory.generateDistributionSet("three", "three", standardDsType,
Lists.newArrayList(os, jvm, ah), true);
- final List sets = Lists.newArrayList(one, two, three);
-
final long current = System.currentTimeMillis();
- final MvcResult mvcResult = mvc
- .perform(post("/rest/v1/distributionsets/").content(JsonBuilder.distributionSets(sets))
- .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
- .andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
- .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
- .andExpect(jsonPath("[0]name", equalTo(one.getName())))
- .andExpect(jsonPath("[0]description", equalTo(one.getDescription())))
- .andExpect(jsonPath("[0]type", equalTo(standardDsType.getKey())))
- .andExpect(jsonPath("[0]createdBy", equalTo("uploadTester")))
- .andExpect(jsonPath("[0]version", equalTo(one.getVersion())))
- .andExpect(jsonPath("[0]complete", equalTo(Boolean.TRUE)))
- .andExpect(jsonPath("[0]requiredMigrationStep", equalTo(one.isRequiredMigrationStep())))
- .andExpect(jsonPath("[0].modules.[?(@.type==" + runtimeType.getKey() + ")].id",
- contains(one.findFirstModuleByType(runtimeType).getId().intValue())))
- .andExpect(jsonPath("[0].modules.[?(@.type==" + appType.getKey() + ")].id",
- contains(one.findFirstModuleByType(appType).getId().intValue())))
- .andExpect(jsonPath("[0].modules.[?(@.type==" + osType.getKey() + ")].id",
- contains(one.findFirstModuleByType(osType).getId().intValue())))
- .andExpect(jsonPath("[1]name", equalTo(two.getName())))
- .andExpect(jsonPath("[1]description", equalTo(two.getDescription())))
- .andExpect(jsonPath("[1]complete", equalTo(Boolean.TRUE)))
- .andExpect(jsonPath("[1]type", equalTo(standardDsType.getKey())))
- .andExpect(jsonPath("[1]createdBy", equalTo("uploadTester")))
- .andExpect(jsonPath("[1]version", equalTo(two.getVersion())))
- .andExpect(jsonPath("[1].modules.[?(@.type==" + runtimeType.getKey() + ")].id",
- contains(two.findFirstModuleByType(runtimeType).getId().intValue())))
- .andExpect(jsonPath("[1].modules.[?(@.type==" + appType.getKey() + ")].id",
- contains(two.findFirstModuleByType(appType).getId().intValue())))
- .andExpect(jsonPath("[1].modules.[?(@.type==" + osType.getKey() + ")].id",
- contains(two.findFirstModuleByType(osType).getId().intValue())))
- .andExpect(jsonPath("[1]requiredMigrationStep", equalTo(two.isRequiredMigrationStep())))
- .andExpect(jsonPath("[2]name", equalTo(three.getName())))
- .andExpect(jsonPath("[2]description", equalTo(three.getDescription())))
- .andExpect(jsonPath("[2]complete", equalTo(Boolean.TRUE)))
- .andExpect(jsonPath("[2]type", equalTo(standardDsType.getKey())))
- .andExpect(jsonPath("[2]createdBy", equalTo("uploadTester")))
- .andExpect(jsonPath("[2]version", equalTo(three.getVersion())))
- .andExpect(jsonPath("[2].modules.[?(@.type==" + runtimeType.getKey() + ")].id",
- contains(three.findFirstModuleByType(runtimeType).getId().intValue())))
- .andExpect(jsonPath("[2].modules.[?(@.type==" + appType.getKey() + ")].id",
- contains(three.findFirstModuleByType(appType).getId().intValue())))
- .andExpect(jsonPath("[2].modules.[?(@.type==" + osType.getKey() + ")].id",
- contains(three.findFirstModuleByType(osType).getId().intValue())))
- .andExpect(jsonPath("[2]requiredMigrationStep", equalTo(three.isRequiredMigrationStep()))).andReturn();
+ final MvcResult mvcResult = executeMgmtTargetPost(one, two, three);
- one = distributionSetManagement.findDistributionSetByIdWithDetails(
- distributionSetManagement.findDistributionSetByNameAndVersion("one", "one").getId());
- two = distributionSetManagement.findDistributionSetByIdWithDetails(
- distributionSetManagement.findDistributionSetByNameAndVersion("two", "two").getId());
- three = distributionSetManagement.findDistributionSetByIdWithDetails(
- distributionSetManagement.findDistributionSetByNameAndVersion("three", "three").getId());
+ one = distributionSetManagement.findDistributionSetByIdWithDetails(distributionSetManagement
+ .findDistributionSetsAll("name==one", pageReq, false).getContent().get(0).getId()).get();
+ two = distributionSetManagement.findDistributionSetByIdWithDetails(distributionSetManagement
+ .findDistributionSetsAll("name==two", pageReq, false).getContent().get(0).getId()).get();
+ three = distributionSetManagement.findDistributionSetByIdWithDetails(distributionSetManagement
+ .findDistributionSetsAll("name==three", pageReq, false).getContent().get(0).getId()).get();
assertThat(
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
@@ -603,6 +556,56 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
assertThat(three.getCreatedAt()).isGreaterThanOrEqualTo(current);
}
+ @Step
+ private MvcResult executeMgmtTargetPost(final DistributionSet one, final DistributionSet two,
+ final DistributionSet three) throws Exception {
+ return mvc
+ .perform(post("/rest/v1/distributionsets/")
+ .content(JsonBuilder.distributionSets(Lists.newArrayList(one, two, three)))
+ .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
+ .andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
+ .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
+ .andExpect(jsonPath("[0]name", equalTo(one.getName())))
+ .andExpect(jsonPath("[0]description", equalTo(one.getDescription())))
+ .andExpect(jsonPath("[0]type", equalTo(standardDsType.getKey())))
+ .andExpect(jsonPath("[0]createdBy", equalTo("uploadTester")))
+ .andExpect(jsonPath("[0]version", equalTo(one.getVersion())))
+ .andExpect(jsonPath("[0]complete", equalTo(Boolean.TRUE)))
+ .andExpect(jsonPath("[0]requiredMigrationStep", equalTo(one.isRequiredMigrationStep())))
+ .andExpect(jsonPath("[0].modules.[?(@.type==" + runtimeType.getKey() + ")].id",
+ contains(one.findFirstModuleByType(runtimeType).get().getId().intValue())))
+ .andExpect(jsonPath("[0].modules.[?(@.type==" + appType.getKey() + ")].id",
+ contains(one.findFirstModuleByType(appType).get().getId().intValue())))
+ .andExpect(jsonPath("[0].modules.[?(@.type==" + osType.getKey() + ")].id",
+ contains(one.findFirstModuleByType(osType).get().getId().intValue())))
+ .andExpect(jsonPath("[1]name", equalTo(two.getName())))
+ .andExpect(jsonPath("[1]description", equalTo(two.getDescription())))
+ .andExpect(jsonPath("[1]complete", equalTo(Boolean.TRUE)))
+ .andExpect(jsonPath("[1]type", equalTo(standardDsType.getKey())))
+ .andExpect(jsonPath("[1]createdBy", equalTo("uploadTester")))
+ .andExpect(jsonPath("[1]version", equalTo(two.getVersion())))
+ .andExpect(jsonPath("[1].modules.[?(@.type==" + runtimeType.getKey() + ")].id",
+ contains(two.findFirstModuleByType(runtimeType).get().getId().intValue())))
+ .andExpect(jsonPath("[1].modules.[?(@.type==" + appType.getKey() + ")].id",
+ contains(two.findFirstModuleByType(appType).get().getId().intValue())))
+ .andExpect(jsonPath("[1].modules.[?(@.type==" + osType.getKey() + ")].id",
+ contains(two.findFirstModuleByType(osType).get().getId().intValue())))
+ .andExpect(jsonPath("[1]requiredMigrationStep", equalTo(two.isRequiredMigrationStep())))
+ .andExpect(jsonPath("[2]name", equalTo(three.getName())))
+ .andExpect(jsonPath("[2]description", equalTo(three.getDescription())))
+ .andExpect(jsonPath("[2]complete", equalTo(Boolean.TRUE)))
+ .andExpect(jsonPath("[2]type", equalTo(standardDsType.getKey())))
+ .andExpect(jsonPath("[2]createdBy", equalTo("uploadTester")))
+ .andExpect(jsonPath("[2]version", equalTo(three.getVersion())))
+ .andExpect(jsonPath("[2].modules.[?(@.type==" + runtimeType.getKey() + ")].id",
+ contains(three.findFirstModuleByType(runtimeType).get().getId().intValue())))
+ .andExpect(jsonPath("[2].modules.[?(@.type==" + appType.getKey() + ")].id",
+ contains(three.findFirstModuleByType(appType).get().getId().intValue())))
+ .andExpect(jsonPath("[2].modules.[?(@.type==" + osType.getKey() + ")].id",
+ contains(three.findFirstModuleByType(osType).get().getId().intValue())))
+ .andExpect(jsonPath("[2]requiredMigrationStep", equalTo(three.isRequiredMigrationStep()))).andReturn();
+ }
+
@Test
@Description("Ensures that DS deletion request to API is reflected by the repository.")
public void deleteUnassignedistributionSet() throws Exception {
@@ -625,6 +628,13 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
assertThat(distributionSetManagement.countDistributionSetsAll()).isEqualTo(0);
}
+ @Test
+ @Description("Ensures that DS deletion request to API on an entity that does not exist results in NOT_FOUND.")
+ public void deleteDistributionSetThatDoesNotExistLeadsToNotFound() throws Exception {
+ mvc.perform(delete("/rest/v1/distributionsets/1234")).andDo(MockMvcResultPrinter.print())
+ .andExpect(status().isNotFound());
+ }
+
@Test
@Description("Ensures that assigned DS deletion request to API is reflected by the repository by means of deleted flag set.")
public void deleteAssignedDistributionSet() throws Exception {
@@ -667,7 +677,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- final DistributionSet setupdated = distributionSetManagement.findDistributionSetById(set.getId());
+ final DistributionSet setupdated = distributionSetManagement.findDistributionSetById(set.getId()).get();
assertThat(setupdated.isRequiredMigrationStep()).isEqualTo(true);
assertThat(setupdated.getVersion()).isEqualTo("anotherVersion");
@@ -693,7 +703,7 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isForbidden());
- final DistributionSet setupdated = distributionSetManagement.findDistributionSetById(set.getId());
+ final DistributionSet setupdated = distributionSetManagement.findDistributionSetById(set.getId()).get();
assertThat(setupdated.isRequiredMigrationStep()).isEqualTo(false);
assertThat(setupdated.getVersion()).isEqualTo(set.getVersion());
@@ -776,10 +786,10 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.andExpect(jsonPath("[1]key", equalTo(knownKey2)))
.andExpect(jsonPath("[1]value", equalTo(knownValue2)));
- final DistributionSetMetadata metaKey1 = distributionSetManagement.findDistributionSetMetadata(testDS.getId(),
- knownKey1);
- final DistributionSetMetadata metaKey2 = distributionSetManagement.findDistributionSetMetadata(testDS.getId(),
- knownKey2);
+ final DistributionSetMetadata metaKey1 = distributionSetManagement
+ .findDistributionSetMetadata(testDS.getId(), knownKey1).get();
+ final DistributionSetMetadata metaKey2 = distributionSetManagement
+ .findDistributionSetMetadata(testDS.getId(), knownKey2).get();
assertThat(metaKey1.getValue()).isEqualTo(knownValue1);
assertThat(metaKey2.getValue()).isEqualTo(knownValue2);
@@ -804,8 +814,8 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("key", equalTo(knownKey))).andExpect(jsonPath("value", equalTo(updateValue)));
- final DistributionSetMetadata assertDS = distributionSetManagement.findDistributionSetMetadata(testDS.getId(),
- knownKey);
+ final DistributionSetMetadata assertDS = distributionSetManagement
+ .findDistributionSetMetadata(testDS.getId(), knownKey).get();
assertThat(assertDS.getValue()).isEqualTo(updateValue);
}
@@ -823,12 +833,28 @@ public class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegr
mvc.perform(delete("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- try {
- distributionSetManagement.findDistributionSetMetadata(testDS.getId(), knownKey);
- fail("expected EntityNotFoundException but didn't throw");
- } catch (final EntityNotFoundException e) {
- // ok as expected
- }
+ assertThat(distributionSetManagement.findDistributionSetMetadata(testDS.getId(), knownKey).isPresent())
+ .isFalse();
+ }
+
+ @Test
+ @Description("Ensures that DS metadata deletion request to API on an entity that does not exist results in NOT_FOUND.")
+ public void deleteMetadataThatDoesNotExistLeadsToNotFound() throws Exception {
+ // prepare and create metadata for deletion
+ final String knownKey = "knownKey";
+ final String knownValue = "knownValue";
+
+ final DistributionSet testDS = testdataFactory.createDistributionSet("one");
+ createDistributionSetMetadata(testDS.getId(), entityFactory.generateMetadata(knownKey, knownValue));
+
+ mvc.perform(delete("/rest/v1/distributionsets/{dsId}/metadata/XXX", testDS.getId(), knownKey))
+ .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
+
+ mvc.perform(delete("/rest/v1/distributionsets/1234/metadata/{key}", knownKey))
+ .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
+
+ assertThat(distributionSetManagement.findDistributionSetMetadata(testDS.getId(), knownKey).isPresent())
+ .isTrue();
}
@Test
diff --git a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java
index 52620901f..492ef701b 100644
--- a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java
+++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java
@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
-import static org.fest.assertions.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.contains;
@@ -32,7 +32,6 @@ import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
-import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.springframework.http.MediaType;
@@ -138,7 +137,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes POST requests.")
- public void createDistributionSetTypes() throws JSONException, Exception {
+ public void createDistributionSetTypes() throws Exception {
final List types = createTestDistributionSetTestTypes();
@@ -149,9 +148,9 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Step
private void verifyCreatedDistributionSetTypes(final MvcResult mvcResult) throws UnsupportedEncodingException {
- final DistributionSetType created1 = distributionSetManagement.findDistributionSetTypeByKey("testKey1");
- final DistributionSetType created2 = distributionSetManagement.findDistributionSetTypeByKey("testKey2");
- final DistributionSetType created3 = distributionSetManagement.findDistributionSetTypeByKey("testKey3");
+ final DistributionSetType created1 = distributionSetManagement.findDistributionSetTypeByKey("testKey1").get();
+ final DistributionSetType created2 = distributionSetManagement.findDistributionSetTypeByKey("testKey2").get();
+ final DistributionSetType created3 = distributionSetManagement.findDistributionSetTypeByKey("testKey3").get();
assertThat(created1.getMandatoryModuleTypes()).containsOnly(osType);
assertThat(created1.getOptionalModuleTypes()).containsOnly(runtimeType);
@@ -231,7 +230,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes POST requests.")
- public void addMandatoryModuleToDistributionSetType() throws JSONException, Exception {
+ public void addMandatoryModuleToDistributionSetType() throws Exception {
DistributionSetType testType = distributionSetManagement
.createDistributionSetType(entityFactory.distributionSetType().create().key("test123")
.name("TestName123").description("Desc123").colour("col12"));
@@ -241,7 +240,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
.content("{\"id\":" + osType.getId() + "}").contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- testType = distributionSetManagement.findDistributionSetTypeById(testType.getId());
+ testType = distributionSetManagement.findDistributionSetTypeById(testType.getId()).get();
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
assertThat(testType.getOptLockRevision()).isEqualTo(2);
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
@@ -251,7 +250,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes POST requests.")
- public void addOptionalModuleToDistributionSetType() throws JSONException, Exception {
+ public void addOptionalModuleToDistributionSetType() throws Exception {
DistributionSetType testType = distributionSetManagement
.createDistributionSetType(entityFactory.distributionSetType().create().key("test123")
.name("TestName123").description("Desc123").colour("col12"));
@@ -261,7 +260,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
.content("{\"id\":" + osType.getId() + "}").contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- testType = distributionSetManagement.findDistributionSetTypeById(testType.getId());
+ testType = distributionSetManagement.findDistributionSetTypeById(testType.getId()).get();
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
assertThat(testType.getOptLockRevision()).isEqualTo(2);
assertThat(testType.getOptionalModuleTypes()).containsExactly(osType);
@@ -272,7 +271,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes GET requests.")
- public void getMandatoryModulesOfDistributionSetType() throws JSONException, Exception {
+ public void getMandatoryModulesOfDistributionSetType() throws Exception {
final DistributionSetType testType = generateTestType();
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes", testType.getId())
@@ -286,7 +285,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes GET requests.")
- public void getOptionalModulesOfDistributionSetType() throws JSONException, Exception {
+ public void getOptionalModulesOfDistributionSetType() throws Exception {
final DistributionSetType testType = generateTestType();
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes", testType.getId())
@@ -301,7 +300,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes/{ID} GET requests.")
- public void getMandatoryModuleOfDistributionSetType() throws JSONException, Exception {
+ public void getMandatoryModuleOfDistributionSetType() throws Exception {
final DistributionSetType testType = generateTestType();
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes/{smtId}", testType.getId(),
@@ -328,7 +327,7 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes/{ID} GET requests.")
- public void getOptionalModuleOfDistributionSetType() throws JSONException, Exception {
+ public void getOptionalModuleOfDistributionSetType() throws Exception {
final DistributionSetType testType = generateTestType();
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes/{smtId}", testType.getId(),
@@ -345,14 +344,14 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes/{ID} DELETE requests.")
- public void removeMandatoryModuleToDistributionSetType() throws JSONException, Exception {
+ public void removeMandatoryModuleToDistributionSetType() throws Exception {
DistributionSetType testType = generateTestType();
mvc.perform(delete("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes/{smtId}", testType.getId(),
osType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
- testType = distributionSetManagement.findDistributionSetTypeById(testType.getId());
+ testType = distributionSetManagement.findDistributionSetTypeById(testType.getId()).get();
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
assertThat(testType.getOptLockRevision()).isEqualTo(2);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
@@ -362,14 +361,14 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes/{ID} DELETE requests.")
- public void removeOptionalModuleToDistributionSetType() throws JSONException, Exception {
+ public void removeOptionalModuleToDistributionSetType() throws Exception {
DistributionSetType testType = generateTestType();
mvc.perform(delete("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes/{smtId}", testType.getId(),
appType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
- testType = distributionSetManagement.findDistributionSetTypeById(testType.getId());
+ testType = distributionSetManagement.findDistributionSetTypeById(testType.getId()).get();
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
assertThat(testType.getOptLockRevision()).isEqualTo(2);
assertThat(testType.getOptionalModuleTypes()).isEmpty();
@@ -413,6 +412,13 @@ public class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIn
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(DEFAULT_DS_TYPES);
}
+ @Test
+ @Description("Ensures that DS type deletion request to API on an entity that does not exist results in NOT_FOUND.")
+ public void deleteDistributionSetTypeThatDoesNotExistLeadsToNotFound() throws Exception {
+ mvc.perform(delete("/rest/v1/distributionsettypes/1234")).andDo(MockMvcResultPrinter.print())
+ .andExpect(status().isNotFound());
+ }
+
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/DistributionSetTypes/{ID} DELETE requests (soft delete scenario).")
diff --git a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadResourceTest.java
index 5bbc359ff..caae59752 100644
--- a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadResourceTest.java
+++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadResourceTest.java
@@ -42,8 +42,8 @@ public class MgmtDownloadResourceTest extends AbstractManagementApiIntegrationTe
public void setupCache() {
final DistributionSet distributionSet = testdataFactory.createDistributionSet("Test");
- final SoftwareModule softwareModule = distributionSet.getModules().stream().findFirst().get();
- final Artifact artifact = testdataFactory.createArtifacts(softwareModule.getId()).stream().findFirst().get();
+ final SoftwareModule softwareModule = distributionSet.getModules().stream().findAny().get();
+ final Artifact artifact = testdataFactory.createArtifacts(softwareModule.getId()).stream().findAny().get();
downloadIdCache.put(downloadIdSha1, new DownloadArtifactCache(DownloadType.BY_SHA1, artifact.getSha1Hash()));
}
diff --git a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java
index 5855942e7..f2ca76af4 100644
--- a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java
+++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java
@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
-import static org.fest.assertions.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.endsWith;
@@ -937,7 +937,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
// Run here, because Scheduler is disabled during tests
rolloutManagement.fillRolloutGroupsWithTargets(rollout.getId());
- return rolloutManagement.findRolloutById(rollout.getId());
+ return rolloutManagement.findRolloutById(rollout.getId()).get();
}
protected boolean success(final Rollout result) {
@@ -948,7 +948,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
}
public Rollout getRollout(final Long rolloutId) throws Exception {
- return rolloutManagement.findRolloutById(rolloutId);
+ return rolloutManagement.findRolloutById(rolloutId).get();
}
}
diff --git a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java
index 79383a8e0..3d78332b6 100644
--- a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java
+++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java
@@ -8,13 +8,12 @@
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
-import static org.fest.assertions.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@@ -37,7 +36,6 @@ import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.Constants;
-import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
@@ -48,7 +46,6 @@ import org.eclipse.hawkbit.rest.json.model.ExceptionInfo;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.json.JSONArray;
-import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
@@ -111,7 +108,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andExpect(jsonPath("$.description", equalTo(updateDescription)))
.andExpect(jsonPath("$.name", equalTo(knownSWName))).andReturn();
- sm = softwareManagement.findSoftwareModuleById(sm.getId());
+ sm = softwareManagement.findSoftwareModuleById(sm.getId()).get();
assertThat(sm.getName()).isEqualTo(knownSWName);
assertThat(sm.getVendor()).isEqualTo(updateVendor);
assertThat(sm.getLastModifiedBy()).isEqualTo("smUpdateTester");
@@ -144,7 +141,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
// check rest of response compared to DB
final MgmtArtifact artResult = ResourceUtility
.convertArtifactResponse(mvcResult.getResponse().getContentAsString());
- final Long artId = softwareManagement.findSoftwareModuleById(sm.getId()).getArtifacts().get(0).getId();
+ final Long artId = softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts().get(0).getId();
assertThat(artResult.getArtifactId()).as("Wrong artifact id").isEqualTo(artId);
assertThat(JsonPath.compile("$._links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
.as("Link contains no self url")
@@ -164,21 +161,21 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
// binary
try (InputStream fileInputStream = artifactManagement
.loadArtifactBinary(
- softwareManagement.findSoftwareModuleById(sm.getId()).getArtifacts().get(0).getSha1Hash())
+ softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts().get(0).getSha1Hash())
.getFileInputStream()) {
assertTrue("Wrong artifact content",
IOUtils.contentEquals(new ByteArrayInputStream(random), fileInputStream));
}
// hashes
- assertThat(artifactManagement.findArtifactByFilename("origFilename").get(0).getSha1Hash()).as("Wrong sha1 hash")
+ assertThat(artifactManagement.findArtifactByFilename("origFilename").get().getSha1Hash()).as("Wrong sha1 hash")
.isEqualTo(HashGeneratorUtils.generateSHA1(random));
- assertThat(artifactManagement.findArtifactByFilename("origFilename").get(0).getMd5Hash()).as("Wrong md5 hash")
+ assertThat(artifactManagement.findArtifactByFilename("origFilename").get().getMd5Hash()).as("Wrong md5 hash")
.isEqualTo(HashGeneratorUtils.generateMD5(random));
// metadata
- assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).getArtifacts().get(0).getFilename())
+ assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts().get(0).getFilename())
.as("wrong metadata of the filename").isEqualTo("origFilename");
}
@@ -240,8 +237,8 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1);
// hashes
- assertThat(artifactManagement.findArtifactByFilename("customFilename")).as("Local artifact is wrong")
- .hasSize(1);
+ assertThat(artifactManagement.findArtifactByFilename("customFilename").isPresent())
+ .as("Local artifact is wrong").isTrue();
}
@Test
@@ -661,7 +658,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Verfies that the create request actually results in the creation of the modules in the repository.")
- public void createSoftwareModules() throws JSONException, Exception {
+ public void createSoftwareModules() throws Exception {
final SoftwareModule os = entityFactory.softwareModule().create().name("name1").type(osType).version("version1")
.vendor("vendor1").description("description1").build();
final SoftwareModule ah = entityFactory.softwareModule().create().name("name3").type(appType)
@@ -689,10 +686,10 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andExpect(jsonPath("[1].createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("[1].createdAt", not(equalTo(0)))).andReturn();
- final SoftwareModule osCreated = softwareManagement.findSoftwareModuleByNameAndVersion("name1", "version1",
- osType.getId());
- final SoftwareModule appCreated = softwareManagement.findSoftwareModuleByNameAndVersion("name3", "version3",
- appType.getId());
+ final SoftwareModule osCreated = softwareManagement
+ .findSoftwareModuleByNameAndVersion("name1", "version1", osType.getId()).get();
+ final SoftwareModule appCreated = softwareManagement
+ .findSoftwareModuleByNameAndVersion("name3", "version3", appType.getId()).get();
assertThat(
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
@@ -749,17 +746,17 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
- artifactManagement.createArtifact(new ByteArrayInputStream(random), ds1.findFirstModuleByType(appType).getId(),
- "file1", false);
+ artifactManagement.createArtifact(new ByteArrayInputStream(random),
+ ds1.findFirstModuleByType(appType).get().getId(), "file1", false);
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(3);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1);
- mvc.perform(delete("/rest/v1/softwaremodules/{smId}", ds1.findFirstModuleByType(appType).getId()))
+ mvc.perform(delete("/rest/v1/softwaremodules/{smId}", ds1.findFirstModuleByType(appType).get().getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- mvc.perform(delete("/rest/v1/softwaremodules/{smId}", ds1.findFirstModuleByType(runtimeType).getId()))
+ mvc.perform(delete("/rest/v1/softwaremodules/{smId}", ds1.findFirstModuleByType(runtimeType).get().getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- mvc.perform(delete("/rest/v1/softwaremodules/{smId}", ds1.findFirstModuleByType(osType).getId()))
+ mvc.perform(delete("/rest/v1/softwaremodules/{smId}", ds1.findFirstModuleByType(osType).get().getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
// all 3 are now marked as deleted
@@ -784,7 +781,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
// check repo before delete
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(1);
- assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).getArtifacts()).hasSize(2);
+ assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts()).hasSize(2);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(2);
// delete
@@ -795,7 +792,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).as("After the sm should be marked as deleted")
.hasSize(1);
assertThat(artifactManagement.countArtifactsAll()).isEqualTo(1);
- assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).getArtifacts())
+ assertThat(softwareManagement.findSoftwareModuleById(sm.getId()).get().getArtifacts())
.as("After delete artifact should available for marked as deleted sm's").hasSize(1);
}
@@ -823,8 +820,10 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andExpect(jsonPath("[1]key", equalTo(knownKey2)))
.andExpect(jsonPath("[1]value", equalTo(knownValue2)));
- final SoftwareModuleMetadata metaKey1 = softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey1);
- final SoftwareModuleMetadata metaKey2 = softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey2);
+ final SoftwareModuleMetadata metaKey1 = softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey1)
+ .get();
+ final SoftwareModuleMetadata metaKey2 = softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey2)
+ .get();
assertThat(metaKey1.getValue()).as("Metadata key is wrong").isEqualTo(knownValue1);
assertThat(metaKey2.getValue()).as("Metadata key is wrong").isEqualTo(knownValue2);
@@ -850,7 +849,8 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("key", equalTo(knownKey))).andExpect(jsonPath("value", equalTo(updateValue)));
- final SoftwareModuleMetadata assertDS = softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey);
+ final SoftwareModuleMetadata assertDS = softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey)
+ .get();
assertThat(assertDS.getValue()).as("Metadata is wrong").isEqualTo(updateValue);
}
@@ -868,12 +868,34 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
mvc.perform(delete("/rest/v1/softwaremodules/{swId}/metadata/{key}", sm.getId(), knownKey))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- try {
- softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey);
- fail("expected EntityNotFoundException but didn't throw");
- } catch (final EntityNotFoundException e) {
- // ok as expected
- }
+ assertThat(softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey).isPresent()).isFalse();
+ }
+
+ @Test
+ @Description("Ensures that module metadta deletion request to API on an entity that does not exist results in NOT_FOUND.")
+ public void deleteModuleMetadataThatDoesNotExistLeadsToNotFound() throws Exception {
+ // prepare and create metadata for deletion
+ final String knownKey = "knownKey";
+ final String knownValue = "knownValue";
+
+ final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
+ softwareManagement.createSoftwareModuleMetadata(sm.getId(),
+ entityFactory.generateMetadata(knownKey, knownValue));
+
+ mvc.perform(delete("/rest/v1/softwaremodules/{swId}/metadata/XXX", sm.getId(), knownKey))
+ .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
+
+ mvc.perform(delete("/rest/v1/softwaremodules/1234/metadata/{key}", knownKey))
+ .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
+
+ assertThat(softwareManagement.findSoftwareModuleMetadata(sm.getId(), knownKey).isPresent()).isTrue();
+ }
+
+ @Test
+ @Description("Ensures that module deletion request to API on an entity that does not exist results in NOT_FOUND.")
+ public void deleteSoftwareModuleThatDoesNotExistLeadsToNotFound() throws Exception {
+ mvc.perform(delete("/rest/v1/softwaremodules/1234")).andDo(MockMvcResultPrinter.print())
+ .andExpect(status().isNotFound());
}
@Test
diff --git a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java
index dd693ba63..4ba5c61b1 100644
--- a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java
+++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java
@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
-import static org.fest.assertions.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.contains;
@@ -30,7 +30,6 @@ import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
-import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.springframework.http.MediaType;
@@ -140,7 +139,7 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes POST requests when max assignment is smaller than 1")
- public void createSoftwareModuleTypesInvalidAssignmentBadRequest() throws JSONException, Exception {
+ public void createSoftwareModuleTypesInvalidAssignmentBadRequest() throws Exception {
final List types = new ArrayList<>();
types.add(entityFactory.softwareModuleType().create().key("test-1").name("TestName-1").maxAssignments(-1)
@@ -161,7 +160,7 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes POST requests.")
- public void createSoftwareModuleTypes() throws JSONException, Exception {
+ public void createSoftwareModuleTypes() throws Exception {
final List types = Lists.newArrayList(
entityFactory.softwareModuleType().create().key("test1").name("TestName1").description("Desc1")
@@ -190,9 +189,9 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
.andExpect(jsonPath("[2].createdAt", not(equalTo(0))))
.andExpect(jsonPath("[2].maxAssignments", equalTo(3))).andReturn();
- final SoftwareModuleType created1 = softwareManagement.findSoftwareModuleTypeByKey("test1");
- final SoftwareModuleType created2 = softwareManagement.findSoftwareModuleTypeByKey("test2");
- final SoftwareModuleType created3 = softwareManagement.findSoftwareModuleTypeByKey("test3");
+ final SoftwareModuleType created1 = softwareManagement.findSoftwareModuleTypeByKey("test1").get();
+ final SoftwareModuleType created2 = softwareManagement.findSoftwareModuleTypeByKey("test2").get();
+ final SoftwareModuleType created3 = softwareManagement.findSoftwareModuleTypeByKey("test3").get();
assertThat(
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
@@ -239,6 +238,13 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(3);
}
+ @Test
+ @Description("Ensures that module type deletion request to API on an entity that does not exist results in NOT_FOUND.")
+ public void deleteSoftwareModuleTypeThatDoesNotExistLeadsToNotFound() throws Exception {
+ mvc.perform(delete("/rest/v1/softwaremoduletypes/1234")).andDo(MockMvcResultPrinter.print())
+ .andExpect(status().isNotFound());
+ }
+
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} DELETE requests (soft delete scenario).")
diff --git a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryResourceTest.java
index a92dce6be..69e29576a 100644
--- a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryResourceTest.java
+++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryResourceTest.java
@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
-import static org.fest.assertions.api.Assertions.assertThat;
+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;
@@ -74,8 +74,7 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte
mvc.perform(delete(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + filterQuery.getId()))
.andExpect(status().isOk());
- final TargetFilterQuery tfq = targetFilterQueryManagement.findTargetFilterQueryById(filterQuery.getId());
- assertThat(tfq).isNull();
+ assertThat(targetFilterQueryManagement.findTargetFilterQueryById(filterQuery.getId()).isPresent()).isFalse();
}
@Test
@@ -113,7 +112,7 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte
.andExpect(jsonPath("$.query", equalTo(filterQuery2)))
.andExpect(jsonPath("$.name", equalTo(filterName)));
- final TargetFilterQuery tfqCheck = targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId());
+ final TargetFilterQuery tfqCheck = targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).get();
assertThat(tfqCheck.getQuery()).isEqualTo(filterQuery2);
assertThat(tfqCheck.getName()).isEqualTo(filterName);
}
@@ -136,7 +135,7 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte
.andExpect(jsonPath("$.query", equalTo(filterQuery)))
.andExpect(jsonPath("$.name", equalTo(filterName2)));
- final TargetFilterQuery tfqCheck = targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId());
+ final TargetFilterQuery tfqCheck = targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).get();
assertThat(tfqCheck.getQuery()).isEqualTo(filterQuery);
assertThat(tfqCheck.getName()).isEqualTo(filterName2);
}
@@ -293,8 +292,9 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte
.content("{\"id\":" + set.getId() + "}").contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- assertThat(targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).getAutoAssignDistributionSet())
- .isEqualTo(set);
+ assertThat(
+ targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).get().getAutoAssignDistributionSet())
+ .isEqualTo(set);
final String hrefPrefix = "http://localhost" + MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/"
+ tfq.getId();
@@ -319,8 +319,9 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte
final TargetFilterQuery tfq = createSingleTargetFilterQuery(knownName, knownQuery);
targetFilterQueryManagement.updateTargetFilterQueryAutoAssignDS(tfq.getId(), set.getId());
- assertThat(targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).getAutoAssignDistributionSet())
- .isEqualTo(set);
+ assertThat(
+ targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).get().getAutoAssignDistributionSet())
+ .isEqualTo(set);
mvc.perform(get(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + tfq.getId() + "/autoAssignDS"))
.andExpect(status().isOk()).andExpect(jsonPath(JSON_PATH_NAME, equalTo(dsName)));
@@ -328,8 +329,9 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte
mvc.perform(delete(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + tfq.getId() + "/autoAssignDS"))
.andExpect(status().isNoContent());
- assertThat(targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).getAutoAssignDistributionSet())
- .isNull();
+ assertThat(
+ targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).get().getAutoAssignDistributionSet())
+ .isNull();
mvc.perform(get(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + tfq.getId() + "/autoAssignDS"))
.andExpect(status().isNoContent());
diff --git a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResourceTest.java
index cc84769e8..437e750a9 100644
--- a/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResourceTest.java
+++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResourceTest.java
@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
-import static org.fest.assertions.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.contains;
@@ -226,12 +226,12 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
tA.getControllerId(), tA.getActions().get(0).getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isNoContent());
- final Action action = deploymentManagement.findAction(tA.getActions().get(0).getId());
+ final Action action = deploymentManagement.findAction(tA.getActions().get(0).getId()).get();
// still active because in "canceling" state and waiting for controller
// feedback
assertThat(action.isActive()).isTrue();
- final Target queryTarget = targetManagement.findTargetByControllerID(tA.getControllerId());
+ final Target queryTarget = targetManagement.findTargetByControllerID(tA.getControllerId()).get();
// action has not been cancelled confirmed from controller, so DS
// remains assigned until
// confirmation
@@ -301,13 +301,12 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
mvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId))
.andExpect(status().isOk());
- final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownControllerId);
- assertThat(findTargetByControllerID).isNull();
+ assertThat(targetManagement.findTargetByControllerID(knownControllerId).isPresent()).isFalse();
}
@Test
@Description("Ensures that deletion is refused with not found if target does not exist.")
- public void deleteTargetWhichDoesNotExistsLeadsToEntityNotFound() throws Exception {
+ public void deleteTargetWhichDoesNotExistsLeadsToNotFound() throws Exception {
final String knownControllerId = "knownControllerIdDelete";
mvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId))
@@ -316,7 +315,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
@Test
@Description("Ensures that update is refused with not found if target does not exist.")
- public void updateTargetWhichDoesNotExistsLeadsToEntityNotFound() throws Exception {
+ public void updateTargetWhichDoesNotExistsLeadsToNotFound() throws Exception {
final String knownControllerId = "knownControllerIdUpdate";
mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content("{}")
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
@@ -341,7 +340,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
.andExpect(jsonPath("$.description", equalTo(knownNewDescription)))
.andExpect(jsonPath("$.name", equalTo(knownNameNotModiy)));
- final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownControllerId);
+ final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownControllerId).get();
assertThat(findTargetByControllerID.getDescription()).isEqualTo(knownNewDescription);
assertThat(findTargetByControllerID.getName()).isEqualTo(knownNameNotModiy);
}
@@ -364,7 +363,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
.andExpect(jsonPath("$.securityToken", equalTo(knownNewToken)))
.andExpect(jsonPath("$.name", equalTo(knownNameNotModiy)));
- final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownControllerId);
+ final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownControllerId).get();
assertThat(findTargetByControllerID.getSecurityToken()).isEqualTo(knownNewToken);
assertThat(findTargetByControllerID.getName()).isEqualTo(knownNameNotModiy);
}
@@ -387,7 +386,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
.andExpect(jsonPath("$.address", equalTo(knownNewAddress)))
.andExpect(jsonPath("$.name", equalTo(knownNameNotModiy)));
- final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownControllerId);
+ final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownControllerId).get();
assertThat(findTargetByControllerID.getTargetInfo().getAddress().toString()).isEqualTo(knownNewAddress);
assertThat(findTargetByControllerID.getName()).isEqualTo(knownNameNotModiy);
}
@@ -572,9 +571,9 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
// test
- final SoftwareModule os = ds.findFirstModuleByType(osType);
- final SoftwareModule jvm = ds.findFirstModuleByType(runtimeType);
- final SoftwareModule bApp = ds.findFirstModuleByType(appType);
+ final SoftwareModule os = ds.findFirstModuleByType(osType).get();
+ final SoftwareModule jvm = ds.findFirstModuleByType(runtimeType).get();
+ final SoftwareModule bApp = ds.findFirstModuleByType(appType).get();
mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId + "/assignedDS"))
.andExpect(status().isOk()).andDo(MockMvcResultPrinter.print())
.andExpect(jsonPath(JSON_PATH_ID, equalTo(ds.getId().intValue())))
@@ -747,17 +746,17 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
.isEqualTo("http://localhost/rest/v1/targets/id3");
assertThat(targetManagement.findTargetByControllerID("id1")).isNotNull();
- assertThat(targetManagement.findTargetByControllerID("id1").getName()).isEqualTo("testname1");
- assertThat(targetManagement.findTargetByControllerID("id1").getDescription()).isEqualTo("testid1");
- assertThat(targetManagement.findTargetByControllerID("id1").getSecurityToken()).isEqualTo("token");
- assertThat(targetManagement.findTargetByControllerID("id1").getTargetInfo().getAddress().toString())
+ assertThat(targetManagement.findTargetByControllerID("id1").get().getName()).isEqualTo("testname1");
+ assertThat(targetManagement.findTargetByControllerID("id1").get().getDescription()).isEqualTo("testid1");
+ assertThat(targetManagement.findTargetByControllerID("id1").get().getSecurityToken()).isEqualTo("token");
+ assertThat(targetManagement.findTargetByControllerID("id1").get().getTargetInfo().getAddress().toString())
.isEqualTo("amqp://test123/foobar");
assertThat(targetManagement.findTargetByControllerID("id2")).isNotNull();
- assertThat(targetManagement.findTargetByControllerID("id2").getName()).isEqualTo("testname2");
- assertThat(targetManagement.findTargetByControllerID("id2").getDescription()).isEqualTo("testid2");
+ assertThat(targetManagement.findTargetByControllerID("id2").get().getName()).isEqualTo("testname2");
+ assertThat(targetManagement.findTargetByControllerID("id2").get().getDescription()).isEqualTo("testid2");
assertThat(targetManagement.findTargetByControllerID("id3")).isNotNull();
- assertThat(targetManagement.findTargetByControllerID("id3").getName()).isEqualTo("testname3");
- assertThat(targetManagement.findTargetByControllerID("id3").getDescription()).isEqualTo("testid3");
+ assertThat(targetManagement.findTargetByControllerID("id3").get().getName()).isEqualTo("testname3");
+ assertThat(targetManagement.findTargetByControllerID("id3").get().getDescription()).isEqualTo("testid3");
}
@Test
@@ -1079,7 +1078,8 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
.content("{\"id\":" + set.getId() + "}").contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
- assertThat(targetManagement.findTargetByControllerID("fsdfsd").getAssignedDistributionSet()).isEqualTo(set);
+ assertThat(targetManagement.findTargetByControllerID("fsdfsd").get().getAssignedDistributionSet())
+ .isEqualTo(set);
}
@Test
@@ -1101,7 +1101,8 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
assertThat(findActiveActionsByTarget).hasSize(1);
assertThat(findActiveActionsByTarget.get(0).getActionType()).isEqualTo(ActionType.TIMEFORCED);
assertThat(findActiveActionsByTarget.get(0).getForcedTime()).isEqualTo(forceTime);
- assertThat(targetManagement.findTargetByControllerID("fsdfsd").getAssignedDistributionSet()).isEqualTo(set);
+ assertThat(targetManagement.findTargetByControllerID("fsdfsd").get().getAssignedDistributionSet())
+ .isEqualTo(set);
}
@Test
@@ -1279,6 +1280,6 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
// verify active action
final Slice actionsByTarget = deploymentManagement.findActionsByTarget(tA.getControllerId(), pageReq);
assertThat(actionsByTarget.getContent()).hasSize(1);
- return targetManagement.findTargetByControllerID(tA.getControllerId());
+ return targetManagement.findTargetByControllerID(tA.getControllerId()).get();
}
}
diff --git a/hawkbit-repository/hawkbit-repository-api/pom.xml b/hawkbit-repository/hawkbit-repository-api/pom.xml
index 68241de55..d76c8d5b6 100644
--- a/hawkbit-repository/hawkbit-repository-api/pom.xml
+++ b/hawkbit-repository/hawkbit-repository-api/pom.xml
@@ -62,13 +62,8 @@
test
- org.easytesting
- fest-assert-core
- test
-
-
- org.easytesting
- fest-assert
+ org.springframework.boot
+ spring-boot-starter-testtest
diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/ArtifactManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/ArtifactManagement.java
index 92d172fa1..c1e56df73 100644
--- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/ArtifactManagement.java
+++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/ArtifactManagement.java
@@ -9,17 +9,17 @@
package org.eclipse.hawkbit.repository;
import java.io.InputStream;
-import java.util.List;
+import java.util.Optional;
import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
+import org.eclipse.hawkbit.repository.exception.ArtifactBinaryNotFoundException;
import org.eclipse.hawkbit.repository.exception.ArtifactDeleteFailedException;
import org.eclipse.hawkbit.repository.exception.ArtifactUploadFailedException;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
-import org.eclipse.hawkbit.repository.exception.ArtifactBinaryNotFoundException;
import org.eclipse.hawkbit.repository.exception.InvalidMD5HashException;
import org.eclipse.hawkbit.repository.exception.InvalidSHA1HashException;
import org.eclipse.hawkbit.repository.model.Artifact;
@@ -119,7 +119,8 @@ public interface ArtifactManagement {
* of the {@link Artifact} that has to be deleted.
* @throws ArtifactDeleteFailedException
* if deletion failed (MongoDB is not available)
- *
+ * @throws EntityNotFoundException
+ * if artifact with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteArtifact(@NotNull Long id);
@@ -129,12 +130,11 @@ public interface ArtifactManagement {
*
* @param id
* to search for
- * @return found {@link Artifact} or null is it could not be
- * found.
+ * @return found {@link Artifact}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER)
- Artifact findArtifact(@NotNull Long id);
+ Optional findArtifact(@NotNull Long id);
/**
* Find by artifact by software module id and filename.
@@ -143,11 +143,11 @@ public interface ArtifactManagement {
* file name
* @param softwareModuleId
* software module id.
- * @return Artifact if artifact present
+ * @return found {@link Artifact}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER)
- List findByFilenameAndSoftwareModule(@NotNull String filename, @NotNull Long softwareModuleId);
+ Optional findByFilenameAndSoftwareModule(@NotNull String filename, @NotNull Long softwareModuleId);
/**
* Find all local artifact by sha1 and return the first artifact.
@@ -158,7 +158,7 @@ public interface ArtifactManagement {
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER)
- Artifact findFirstArtifactBySHA1(@NotNull String sha1);
+ Optional findFirstArtifactBySHA1(@NotNull String sha1);
/**
* Searches for {@link Artifact} with given file name.
@@ -169,7 +169,7 @@ public interface ArtifactManagement {
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER)
- List findArtifactByFilename(@NotNull String filename);
+ Optional findArtifactByFilename(@NotNull String filename);
/**
* Get local artifact for a base software module.
diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java
index 351e46282..c47abbeb4 100644
--- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java
+++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java
@@ -106,6 +106,9 @@ public interface ControllerManagement {
* @throws TooManyStatusEntriesException
* if more than the allowed number of status entries are
* inserted
+ *
+ * @throws EntityNotFoundException
+ * if action status not exist
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
Action addUpdateActionStatus(@NotNull ActionStatusCreate create);
@@ -117,9 +120,6 @@ public interface ControllerManagement {
* @param controllerId
* identifies the target to retrieve the actions from
* @return a list of actions assigned to given target which are active
- *
- * @throws EntityNotFoundException
- * if target with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
Optional findOldestActiveActionByTarget(@NotNull String controllerId);
@@ -133,7 +133,7 @@ public interface ControllerManagement {
* @return the corresponding {@link Action}
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
- Action findActionWithDetails(@NotNull Long actionId);
+ Optional findActionWithDetails(@NotNull Long actionId);
/**
* register new target in the repository (plug-and-play).
@@ -149,19 +149,19 @@ public interface ControllerManagement {
/**
* Retrieves last {@link Action} for a download of an artifact of given
- * module and target.
+ * module and target if exists and is not canceled.
*
* @param controllerId
* to look for
- * @param module
- * that should be assigned to the target
+ * @param moduleId
+ * of the the {@link SoftwareModule} that should be assigned to
+ * the target
* @return last {@link Action} for given combination
*
- * @throws EntityNotFoundException
- * if action for given combination could not be found
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER)
- Action getActionForDownloadByTargetAndSoftwareModule(@NotEmpty String controllerId, @NotNull SoftwareModule module);
+ Optional getActionForDownloadByTargetAndSoftwareModule(@NotEmpty String controllerId,
+ @NotNull Long moduleId);
/**
* @return current {@link TenantConfigurationKey#POLLING_TIME_INTERVAL}.
@@ -271,7 +271,7 @@ public interface ControllerManagement {
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_SYSTEM_CODE)
- Target findByControllerId(@NotEmpty String controllerId);
+ Optional findByControllerId(@NotEmpty String controllerId);
/**
* Finds {@link Target} based on given ID returns found Target without
@@ -285,6 +285,6 @@ public interface ControllerManagement {
*/
@PreAuthorize(SpringEvalExpressions.IS_CONTROLLER + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_SYSTEM_CODE)
- Target findByTargetId(@NotNull Long targetId);
+ Optional findByTargetId(@NotNull Long targetId);
}
diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/DeploymentManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/DeploymentManagement.java
index d3675ea49..bb5a99055 100644
--- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/DeploymentManagement.java
+++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/DeploymentManagement.java
@@ -10,6 +10,7 @@ package org.eclipse.hawkbit.repository;
import java.util.Collection;
import java.util.List;
+import java.util.Optional;
import javax.validation.constraints.NotNull;
@@ -123,12 +124,11 @@ public interface DeploymentManagement {
* @param actionId
* to be canceled
*
- * @return generated {@link Action} or null if not active on
- * given {@link Target}.
+ * @return canceled {@link Action}
+ *
* @throws CancelActionNotAllowedException
* in case the given action is not active or is already a cancel
* action
- *
* @throws EntityNotFoundException
* if action with given ID does not exist
*/
@@ -181,9 +181,10 @@ public interface DeploymentManagement {
* @param actionId
* to be id of the action
* @return the corresponding {@link Action}
+ *
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
- Action findAction(@NotNull Long actionId);
+ Optional findAction(@NotNull Long actionId);
/**
* Retrieves all {@link Action}s from repository.
@@ -242,6 +243,7 @@ public interface DeploymentManagement {
* @param pageable
* the pageable request to limit, sort the actions
* @return a slice of actions found for a specific target
+ *
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Slice findActionsByTarget(@NotEmpty String controllerId, @NotNull Pageable pageable);
@@ -255,6 +257,9 @@ public interface DeploymentManagement {
* @param actionId
* to be filtered on
* @return the corresponding {@link Page} of {@link ActionStatus}
+ *
+ * @throws EntityNotFoundException
+ * if action with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page findActionStatusByAction(@NotNull Pageable pageReq, @NotNull Long actionId);
@@ -268,6 +273,9 @@ public interface DeploymentManagement {
* @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 findActionStatusByActionWithMessages(@NotNull Pageable pageable, @NotNull Long actionId);
@@ -292,7 +300,7 @@ public interface DeploymentManagement {
* @return the corresponding {@link Action}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
- Action findActionWithDetails(@NotNull Long actionId);
+ Optional findActionWithDetails(@NotNull Long actionId);
/**
* Retrieves all active {@link Action}s of a specific target ordered by
@@ -325,8 +333,8 @@ public interface DeploymentManagement {
* @param actionId
* to be canceled
*
- * @return generated {@link Action} or null if not active on
- * {@link Target}.
+ * @return quite {@link Action}
+ *
* @throws CancelActionNotAllowedException
* in case the given action is not active
*
@@ -343,6 +351,9 @@ public interface DeploymentManagement {
* @param actionId
* the ID of the action
* @return the updated or the found {@link Action}
+ *
+ * @throws EntityNotFoundException
+ * if action with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET)
Action forceTargetAction(@NotNull Long actionId);
diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java
index 0a811338f..0366e4449 100644
--- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java
+++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java
@@ -10,6 +10,7 @@ package org.eclipse.hawkbit.repository;
import java.util.Collection;
import java.util.List;
+import java.util.Optional;
import javax.validation.constraints.NotNull;
@@ -60,7 +61,7 @@ public interface DistributionSetManagement {
* @return the updated {@link DistributionSet}.
*
* @throws EntityNotFoundException
- * if given module does not exist
+ * if (at least one) given module does not exist
*
* @throws EntityReadOnlyException
* if use tries to change the {@link DistributionSet} s while
@@ -86,7 +87,8 @@ public interface DistributionSetManagement {
* @return list of assigned ds
*
* @throws EntityNotFoundException
- * if tag with given ID does not exist
+ * if tag with given ID does not exist or (at least one) of the
+ * distribution sets.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
List assignTag(@NotEmpty Collection dsIds, @NotNull Long tagId);
@@ -108,6 +110,9 @@ public interface DistributionSetManagement {
* to look for
*
* @return number of {@link DistributionSet}s
+ *
+ * @throws EntityNotFoundException
+ * if type with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Long countDistributionSetsByType(@NotNull Long typeId);
@@ -214,9 +219,13 @@ public interface DistributionSetManagement {
* result means that they cannot be assigned anymore to any targets. (define
* e.g. findByDeletedFalse())
*
- *
+ *
* @param setId
* to delete
+ *
+ * @throws EntityNotFoundException
+ * if given {@link DistributionSet} does not exist
+ *
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteDistributionSet(@NotNull Long setId);
@@ -228,6 +237,9 @@ public interface DistributionSetManagement {
*
* @param dsIds
* to be deleted
+ *
+ * @throws EntityNotFoundException
+ * if (at least one) given distribution set does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteDistributionSet(@NotEmpty Collection dsIds);
@@ -264,9 +276,12 @@ public interface DistributionSetManagement {
* @param actionId
* the action associated with the distribution set
* @return the distribution set which is associated with the action
+ *
+ * @throws EntityNotFoundException
+ * if action with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
- DistributionSet findDistributionSetByAction(@NotNull Long actionId);
+ Optional findDistributionSetByAction(@NotNull Long actionId);
/**
* Find {@link DistributionSet} based on given ID without details, e.g.
@@ -274,10 +289,11 @@ public interface DistributionSetManagement {
*
* @param distid
* to look for.
- * @return {@link DistributionSet} or null if it does not exist
+ * @return {@link DistributionSet}
+ *
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
- DistributionSet findDistributionSetById(@NotNull Long distid);
+ Optional findDistributionSetById(@NotNull Long distid);
/**
* Find {@link DistributionSet} based on given ID including (lazy loaded)
@@ -288,10 +304,10 @@ public interface DistributionSetManagement {
*
* @param distid
* to look for.
- * @return {@link DistributionSet} or null if it does not exist
+ * @return {@link DistributionSet}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
- DistributionSet findDistributionSetByIdWithDetails(@NotNull Long distid);
+ Optional findDistributionSetByIdWithDetails(@NotNull Long distid);
/**
* Find distribution set by name and version.
@@ -303,7 +319,8 @@ public interface DistributionSetManagement {
* @return the page with the found {@link DistributionSet}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
- DistributionSet findDistributionSetByNameAndVersion(@NotEmpty String distributionName, @NotEmpty String version);
+ Optional findDistributionSetByNameAndVersion(@NotEmpty String distributionName,
+ @NotEmpty String version);
/**
* finds all meta data by the given distribution set id.
@@ -314,21 +331,14 @@ public interface DistributionSetManagement {
* the page request to page the result
* @return a paged result of all meta data entries for a given distribution
* set id
+ *
+ * @throws EntityNotFoundException
+ * if distribution set with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page findDistributionSetMetadataByDistributionSetId(@NotNull Long distributionSetId,
@NotNull Pageable pageable);
- /**
- * Finds all meta data by the given distribution set id.
- *
- * @param distributionSetId
- * the distribution set id to retrieve the meta data from
- * @return list of distributionSetMetadata for a given distribution set Id.
- */
- @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
- List findDistributionSetMetadataByDistributionSetId(@NotNull Long distributionSetId);
-
/**
* finds all meta data by the given distribution set id.
*
@@ -346,6 +356,9 @@ public interface DistributionSetManagement {
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
+ *
+ * @throws EntityNotFoundException
+ * of distribution set with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page findDistributionSetMetadataByDistributionSetId(@NotNull Long distributionSetId,
@@ -449,27 +462,27 @@ public interface DistributionSetManagement {
/**
* @param id
* as {@link DistributionSetType#getId()}
- * @return {@link DistributionSetType} if found or null if not
+ * @return {@link DistributionSetType}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
- DistributionSetType findDistributionSetTypeById(@NotNull Long id);
+ Optional findDistributionSetTypeById(@NotNull Long id);
/**
* @param key
* as {@link DistributionSetType#getKey()}
- * @return {@link DistributionSetType} if found or null if not
+ * @return {@link DistributionSetType}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
- DistributionSetType findDistributionSetTypeByKey(@NotEmpty String key);
+ Optional findDistributionSetTypeByKey(@NotEmpty String key);
/**
* @param name
* as {@link DistributionSetType#getName()}
- * @return {@link DistributionSetType} if found or null if not
+ * @return {@link DistributionSetType}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
- DistributionSetType findDistributionSetTypeByName(@NotEmpty String name);
+ Optional findDistributionSetTypeByName(@NotEmpty String name);
/**
* @param pageable
@@ -506,11 +519,9 @@ public interface DistributionSetManagement {
* @param key
* of the meta data element
* @return the found DistributionSetMetadata or {@code null} if not exits
- * @throws EntityNotFoundException
- * in case the meta data does not exists for the given key
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
- DistributionSetMetadata findDistributionSetMetadata(@NotNull Long setId, @NotEmpty String key);
+ Optional findDistributionSetMetadata(@NotNull Long setId, @NotEmpty String key);
/**
* Checks if a {@link DistributionSet} is currently in use by a target in
@@ -536,6 +547,9 @@ public interface DistributionSetManagement {
* to toggle
* @return {@link DistributionSetTagAssignmentResult} with all meta data of
* the assignment outcome.
+ *
+ * @throws EntityNotFoundException
+ * if given tag does not exist or (at least one) module
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
DistributionSetTagAssignmentResult toggleTagAssignment(@NotEmpty Collection dsIds, @NotNull String tagName);
@@ -715,6 +729,6 @@ public interface DistributionSetManagement {
* @return the found {@link DistributionSet}s
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
- List findDistributionSetAllById(@NotNull Collection ids);
+ List findDistributionSetAllById(@NotEmpty Collection ids);
}
diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RolloutGroupManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RolloutGroupManagement.java
index 8823c00f9..41596f194 100644
--- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RolloutGroupManagement.java
+++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RolloutGroupManagement.java
@@ -8,6 +8,8 @@
*/
package org.eclipse.hawkbit.repository;
+import java.util.Optional;
+
import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
@@ -67,9 +69,10 @@ public interface RolloutGroupManagement {
* the ID of the rollout group to find
* @return the found {@link RolloutGroup} by its ID or {@code null} if it
* does not exists
+ *
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
- RolloutGroup findRolloutGroupById(@NotNull Long rolloutGroupId);
+ Optional findRolloutGroupById(@NotNull Long rolloutGroupId);
/**
* Retrieves a page of {@link RolloutGroup}s filtered by a given
@@ -151,9 +154,10 @@ public interface RolloutGroupManagement {
* @param rolloutGroupId
* rollout group id
* @return rolloutGroup with details of targets count for different statuses
+ *
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
- RolloutGroup findRolloutGroupWithDetailedStatus(@NotNull Long rolloutGroupId);
+ Optional findRolloutGroupWithDetailedStatus(@NotNull Long rolloutGroupId);
/**
* Count targets of rollout group.
diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RolloutManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RolloutManagement.java
index 2d8a96d2b..24c55b863 100644
--- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RolloutManagement.java
+++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RolloutManagement.java
@@ -9,7 +9,7 @@
package org.eclipse.hawkbit.repository;
import java.util.List;
-import java.util.concurrent.Future;
+import java.util.Optional;
import javax.validation.constraints.NotNull;
@@ -45,8 +45,8 @@ public interface RolloutManagement {
/**
* Checking running rollouts. Rollouts which are checked updating the
- * lastCheck to indicate that the current instance
- * is handling the specific rollout. This code should run as system-code.
+ * lastCheck to indicate that the current instance is handling the specific
+ * rollout. This code should run as system-code.
*
*
*
- * This method is intended to be called by a scheduler.
- * And must be running in an transaction so it's
- * splitted from the scheduler.
+ * This method is intended to be called by a scheduler. And must be running
+ * in an transaction so it's splitted from the scheduler.
*
* Rollouts which are currently running are investigated, by means the
* error- and finish condition of running groups in this rollout are
@@ -292,7 +291,7 @@ public interface RolloutManagement {
* not exists
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
- Rollout findRolloutById(@NotNull Long rolloutId);
+ Optional findRolloutById(@NotNull Long rolloutId);
/**
* Retrieves a specific rollout by its name.
@@ -303,7 +302,7 @@ public interface RolloutManagement {
* does not exists
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
- Rollout findRolloutByName(@NotNull String rolloutName);
+ Optional findRolloutByName(@NotEmpty String rolloutName);
/**
* Get count of targets in different status in rollout.
@@ -311,10 +310,21 @@ public interface RolloutManagement {
* @param rolloutId
* rollout id
* @return rollout details of targets count for different statuses
+ *
*
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_READ)
- Rollout findRolloutWithDetailedStatus(@NotNull Long rolloutId);
+ Optional findRolloutWithDetailedStatus(@NotNull Long rolloutId);
+
+ /**
+ * Checks if rollout with given ID exists.
+ *
+ * @param rolloutId
+ * rollout id
+ *
+ * @return true if rollout exists
+ */
+ boolean exists(@NotNull Long rolloutId);
/***
* Get finished percentage details for a specified group which is in running
@@ -378,7 +388,7 @@ public interface RolloutManagement {
* all actions are created and the first group is started. The rollout
* itself will be then also in {@link RolloutStatus#RUNNING}.
*
- * @param rollout
+ * @param rolloutId
* the rollout to be started
*
* @return started rollout
@@ -390,7 +400,7 @@ public interface RolloutManagement {
* ready rollouts can be started.
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE)
- Rollout startRollout(@NotNull Long rollout);
+ Rollout startRollout(@NotNull Long rolloutId);
/**
* Update rollout details.
@@ -399,6 +409,10 @@ public interface RolloutManagement {
* rollout to be updated
*
* @return Rollout updated rollout
+ *
+ * @throws EntityNotFoundException
+ * if rollout or DS with given IDs do not exist
+ *
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE)
Rollout updateRollout(@NotNull RolloutUpdate update);
diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/SoftwareManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/SoftwareManagement.java
index 5307e6f55..064529474 100644
--- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/SoftwareManagement.java
+++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/SoftwareManagement.java
@@ -10,6 +10,7 @@ package org.eclipse.hawkbit.repository;
import java.util.Collection;
import java.util.List;
+import java.util.Optional;
import javax.validation.constraints.NotNull;
@@ -50,6 +51,9 @@ public interface SoftwareManagement {
* @param typeId
* to filter the result by type
* @return number of found {@link SoftwareModule}s
+ *
+ * @throws EntityNotFoundException
+ * if software module type with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Long countSoftwareModuleByFilters(String searchText, Long typeId);
@@ -77,6 +81,9 @@ public interface SoftwareManagement {
* @return SoftwareModule
* @throws EntityAlreadyExistsException
* if a given entity already exists
+ *
+ * @throws EntityNotFoundException
+ * of given software module type does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
List createSoftwareModule(@NotNull Collection creates);
@@ -88,6 +95,9 @@ public interface SoftwareManagement {
* @return SoftwareModule
* @throws EntityAlreadyExistsException
* if a given entity already exists
+ *
+ * @throws EntityNotFoundException
+ * of given software module type does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY)
SoftwareModule createSoftwareModule(@NotNull SoftwareModuleCreate create);
@@ -103,6 +113,8 @@ public interface SoftwareManagement {
* @throws EntityAlreadyExistsException
* in case one of the meta data entry already exists for the
* specific key
+ * @throws EntityNotFoundException
+ * if software module with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
List createSoftwareModuleMetadata(@NotNull Long moduleId,
@@ -119,6 +131,8 @@ public interface SoftwareManagement {
* @throws EntityAlreadyExistsException
* in case the meta data entry already exists for the specific
* key
+ * @throws EntityNotFoundException
+ * if software module with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
SoftwareModuleMetadata createSoftwareModuleMetadata(@NotNull Long moduleId, @NotNull MetaData metadata);
@@ -159,6 +173,9 @@ public interface SoftwareManagement {
* where meta data has to be deleted
* @param key
* of the metda data element
+ *
+ * @throws EntityNotFoundException
+ * of module or metadata entry does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
void deleteSoftwareModuleMetadata(@NotNull Long moduleId, @NotEmpty String key);
@@ -168,6 +185,9 @@ public interface SoftwareManagement {
*
* @param moduleIds
* of the Software Modules to be deleted
+ *
+ * @throws EntityNotFoundException
+ * if (at least one) module with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteSoftwareModules(@NotNull Collection moduleIds);
@@ -179,7 +199,7 @@ public interface SoftwareManagement {
* to delete
*
* @throws EntityNotFoundException
- * not found is type with giben ID does not exist
+ * not found is type with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteSoftwareModuleType(@NotNull Long typeId);
@@ -191,6 +211,9 @@ public interface SoftwareManagement {
* to search for
* @return all {@link SoftwareModule}s that are assigned to given
* {@link DistributionSet}.
+ *
+ * @throws EntityNotFoundException
+ * if distribution set with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page findSoftwareModuleByAssignedTo(@NotNull Pageable pageable, @NotNull Long setId);
@@ -207,6 +230,9 @@ public interface SoftwareManagement {
* @param typeId
* to be filtered as "like" on {@link SoftwareModule#getType()}
* @return the page of found {@link SoftwareModule}
+ *
+ * @throws EntityNotFoundException
+ * if given software module type does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Slice findSoftwareModuleByFilters(@NotNull Pageable pageable, String searchText, Long typeId);
@@ -227,12 +253,12 @@ public interface SoftwareManagement {
*
* @param id
* to search for
- * @return the found {@link SoftwareModule}s or null if not
- * found.
+ * @return the found {@link SoftwareModule}s
+ *
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.IS_CONTROLLER)
- SoftwareModule findSoftwareModuleById(@NotNull Long id);
+ Optional findSoftwareModuleById(@NotNull Long id);
/**
* retrieves {@link SoftwareModule} by their name AND version AND type..
@@ -243,10 +269,13 @@ public interface SoftwareManagement {
* of the {@link SoftwareModule}
* @param typeId
* of the {@link SoftwareModule}
- * @return the found {@link SoftwareModule} or null
+ * @return the found {@link SoftwareModule}
+ *
+ * @throws EntityNotFoundException
+ * if software module type with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
- SoftwareModule findSoftwareModuleByNameAndVersion(@NotEmpty String name, @NotEmpty String version,
+ Optional findSoftwareModuleByNameAndVersion(@NotEmpty String name, @NotEmpty String version,
@NotNull Long typeId);
/**
@@ -257,11 +286,9 @@ public interface SoftwareManagement {
* @param key
* of the meta data element
* @return the found SoftwareModuleMetadata or {@code null} if not exits
- * @throws EntityNotFoundException
- * in case the meta data does not exists for the given key
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
- SoftwareModuleMetadata findSoftwareModuleMetadata(@NotNull Long moduleId, @NotEmpty String key);
+ Optional findSoftwareModuleMetadata(@NotNull Long moduleId, @NotEmpty String key);
/**
* finds all meta data by the given software module id.
@@ -272,6 +299,9 @@ public interface SoftwareManagement {
* the page request to page the result
* @return a paged result of all meta data entries for a given software
* module id
+ *
+ * @throws EntityNotFoundException
+ * if software module with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page findSoftwareModuleMetadataBySoftwareModuleId(@NotNull Long swId,
@@ -294,6 +324,8 @@ public interface SoftwareManagement {
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
+ * @throws EntityNotFoundException
+ * if software module with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page findSoftwareModuleMetadataBySoftwareModuleId(@NotNull Long moduleId,
@@ -318,6 +350,9 @@ public interface SoftwareManagement {
* @param typeId
* filtered as "equal" on {@link SoftwareModule#getType()}
* @return the page of found {@link SoftwareModule}
+ *
+ * @throws EntityNotFoundException
+ * if given software module type does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Slice findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(
@@ -371,6 +406,9 @@ public interface SoftwareManagement {
* @param typeId
* to be filtered on
* @return the found {@link SoftwareModule}s
+ *
+ * @throws EntityNotFoundException
+ * if software module type with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Slice findSoftwareModulesByType(@NotNull Pageable pageable, @NotNull Long typeId);
@@ -383,7 +421,7 @@ public interface SoftwareManagement {
* {@link SoftwareModuleType#getId()}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
- SoftwareModuleType findSoftwareModuleTypeById(@NotNull Long id);
+ Optional findSoftwareModuleTypeById(@NotNull Long id);
/**
*
@@ -393,7 +431,7 @@ public interface SoftwareManagement {
* {@link SoftwareModuleType#getKey()}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
- SoftwareModuleType findSoftwareModuleTypeByKey(@NotEmpty String key);
+ Optional findSoftwareModuleTypeByKey(@NotEmpty String key);
/**
*
@@ -403,7 +441,7 @@ public interface SoftwareManagement {
* {@link SoftwareModuleType#getName()}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
- SoftwareModuleType findSoftwareModuleTypeByName(@NotNull String name);
+ Optional findSoftwareModuleTypeByName(@NotNull String name);
/**
* @param pageable
@@ -443,6 +481,9 @@ public interface SoftwareManagement {
* if given module does not exist
*
* @return the saved Entity.
+ *
+ * @throws EntityNotFoundException
+ * if fiven {@link SoftwareModule} does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY)
SoftwareModule updateSoftwareModule(@NotNull SoftwareModuleUpdate update);
@@ -455,8 +496,8 @@ public interface SoftwareManagement {
* @param metadata
* the meta data entry to be updated
*
- *
* @return the updated meta data entry
+ *
* @throws EntityNotFoundException
* in case the meta data entry does not exists and cannot be
* updated
@@ -492,6 +533,9 @@ public interface SoftwareManagement {
* @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 findSoftwareModuleMetadataBySoftwareModuleId(@NotNull Long moduleId);
diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TagManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TagManagement.java
index e6c69a4c7..0c2483cb0 100644
--- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TagManagement.java
+++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TagManagement.java
@@ -10,6 +10,7 @@ package org.eclipse.hawkbit.repository;
import java.util.Collection;
import java.util.List;
+import java.util.Optional;
import javax.validation.constraints.NotNull;
@@ -102,6 +103,9 @@ public interface TagManagement {
*
* @param tagName
* to be deleted
+ *
+ * @throws EntityNotFoundException
+ * if tag with given name does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY)
void deleteDistributionSetTag(@NotEmpty String tagName);
@@ -111,6 +115,9 @@ public interface TagManagement {
*
* @param targetTagName
* tag name of the {@link TargetTag} to be deleted
+ *
+ * @throws EntityNotFoundException
+ * if tag with given name does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_TARGET)
void deleteTargetTag(@NotEmpty String targetTagName);
@@ -150,12 +157,6 @@ public interface TagManagement {
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
Page findAllDistributionSetTags(@NotNull String rsqlParam, @NotNull Pageable pageable);
- /**
- * @return all {@link TargetTag}s
- */
- @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
- List findAllTargetTags();
-
/**
* returns all {@link TargetTag}s.
*
@@ -190,41 +191,40 @@ public interface TagManagement {
*
* @param name
* to look for.
- * @return {@link DistributionSet} or null if it does not exist
+ * @return {@link DistributionSet}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
- DistributionSetTag findDistributionSetTag(@NotEmpty String name);
+ Optional findDistributionSetTag(@NotEmpty String name);
/**
* Finds {@link DistributionSetTag} by given id.
*
* @param id
* to search for
- * @return the found {@link DistributionSetTag}s or null if not
- * found.
+ * @return the found {@link DistributionSetTag}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
- DistributionSetTag findDistributionSetTagById(@NotNull Long id);
+ Optional findDistributionSetTagById(@NotNull Long id);
/**
* Find {@link TargetTag} based on given Name.
*
* @param name
* to look for.
- * @return {@link TargetTag} or null if it does not exist
+ * @return {@link TargetTag}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
- TargetTag findTargetTag(@NotEmpty String name);
+ Optional findTargetTag(@NotEmpty String name);
/**
* Finds {@link TargetTag} by given id.
*
* @param id
* to search for
- * @return the found {@link TargetTag}s or null if not found.
+ * @return the found {@link TargetTag}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
- TargetTag findTargetTagById(@NotNull Long id);
+ Optional findTargetTagById(@NotNull Long id);
/**
* Updates an existing {@link DistributionSetTag}.
diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagement.java
index 5ab4266f8..d57e1a217 100644
--- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagement.java
+++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagement.java
@@ -8,6 +8,8 @@
*/
package org.eclipse.hawkbit.repository;
+import java.util.Optional;
+
import javax.validation.constraints.NotNull;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
@@ -42,6 +44,9 @@ public interface TargetFilterQueryManagement {
*
* @param targetFilterQueryId
* IDs of target filter query to be deleted
+ *
+ * @throws EntityNotFoundException
+ * if filter with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_TARGET)
void deleteTargetFilterQuery(@NotNull Long targetFilterQueryId);
@@ -118,7 +123,7 @@ public interface TargetFilterQueryManagement {
* @return the page with the found {@link TargetFilterQuery}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
- Page findTargetFilterQueryByQuery(@NotNull Pageable pageable, String query);
+ Page findTargetFilterQueryByQuery(@NotNull Pageable pageable, @NotNull String query);
/**
* Retrieves all target filter query which {@link TargetFilterQuery}.
@@ -159,7 +164,7 @@ public interface TargetFilterQueryManagement {
*
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
- TargetFilterQuery findTargetFilterQueryById(@NotNull Long targetFilterQueryId);
+ Optional findTargetFilterQueryById(@NotNull Long targetFilterQueryId);
/**
* Find target filter query by name.
@@ -170,7 +175,7 @@ public interface TargetFilterQueryManagement {
*
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
- TargetFilterQuery findTargetFilterQueryByName(@NotNull String targetFilterQueryName);
+ Optional findTargetFilterQueryByName(@NotNull String targetFilterQueryName);
/**
* updates the {@link TargetFilterQuery}.
diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TargetManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TargetManagement.java
index da7004cc8..4c6c771ba 100644
--- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TargetManagement.java
+++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/TargetManagement.java
@@ -10,6 +10,7 @@ package org.eclipse.hawkbit.repository;
import java.util.Collection;
import java.util.List;
+import java.util.Optional;
import javax.validation.constraints.NotNull;
@@ -64,6 +65,9 @@ public interface TargetManagement {
* to search for
*
* @return number of found {@link Target}s.
+ *
+ * @throws EntityNotFoundException
+ * if distribution set with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
@@ -94,6 +98,9 @@ public interface TargetManagement {
* flag to select targets with no tag assigned
*
* @return the found number {@link Target}s
+ *
+ * @throws EntityNotFoundException
+ * if distribution set with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Long countTargetByFilters(Collection status, Boolean overdueState, String searchText,
@@ -106,6 +113,9 @@ public interface TargetManagement {
* @param distId
* to search for
* @return number of found {@link Target}s.
+ *
+ * @throws EntityNotFoundException
+ * if distribution set with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET + SpringEvalExpressions.HAS_AUTH_OR
+ SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY)
@@ -175,10 +185,13 @@ public interface TargetManagement {
*
* @param targetIDs
* the IDs of the targets to be deleted
+ *
+ * @throws EntityNotFoundException
+ * if (at least one) of the given target IDs does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_TARGET)
void deleteTargets(@NotEmpty Collection targetIDs);
-
+
/**
* Deletes target with the given IDs.
*
@@ -203,10 +216,13 @@ public interface TargetManagement {
* @param rsqlParam
* filter definition in RSQL syntax
* @return a page of the found {@link Target}s
+ *
+ * @throws EntityNotFoundException
+ * if distribution set with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
- Page findAllTargetsByTargetFilterQueryAndNonDS(@NotNull Pageable pageRequest, Long distributionSetId,
- @NotNull String rsqlParam);
+ Page findAllTargetsByTargetFilterQueryAndNonDS(@NotNull Pageable pageRequest,
+ @NotNull Long distributionSetId, @NotNull String rsqlParam);
/**
* Counts all targets for all the given parameter {@link TargetFilterQuery}
@@ -218,6 +234,9 @@ public interface TargetManagement {
* @param rsqlParam
* filter definition in RSQL syntax
* @return the count of found {@link Target}s
+ *
+ * @throws EntityNotFoundException
+ * if distribution set with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Long countTargetsByTargetFilterQueryAndNonDS(@NotNull Long distributionSetId, @NotNull String rsqlParam);
@@ -261,6 +280,9 @@ public interface TargetManagement {
* @param group
* the {@link RolloutGroup}
* @return the found {@link Target}s
+ *
+ * @throws EntityNotFoundException
+ * if rollout group with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Page findAllTargetsInRolloutGroupWithoutAction(@NotNull Pageable pageRequest, @NotNull Long group);
@@ -276,6 +298,9 @@ public interface TargetManagement {
* @param pageReq
* page parameter
* @return the found {@link Target}s
+ *
+ * @throws EntityNotFoundException
+ * if distribution set with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_READ_TARGET)
Page findTargetByAssignedDistributionSet(@NotNull Long distributionSetID, @NotNull Pageable pageReq);
@@ -297,7 +322,8 @@ public interface TargetManagement {
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
- *
+ * @throws EntityNotFoundException
+ * if distribution set with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_READ_TARGET)
Page findTargetByAssignedDistributionSet(@NotNull Long distributionSetID, @NotNull String rsqlParam,
@@ -322,10 +348,10 @@ public interface TargetManagement {
*
* @param controllerId
* to look for.
- * @return {@link Target} or null if it does not exist
+ * @return {@link Target}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
- Target findTargetByControllerID(@NotEmpty String controllerId);
+ Optional findTargetByControllerID(@NotEmpty String controllerId);
/**
* Find {@link Target} based on given ID returns found Target with details,
@@ -337,10 +363,10 @@ public interface TargetManagement {
*
* @param controllerId
* to look for.
- * @return {@link Target} or null if it does not exist
+ * @return {@link Target}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
- Target findTargetByControllerIDWithDetails(@NotEmpty String controllerId);
+ Optional findTargetByControllerIDWithDetails(@NotEmpty String controllerId);
/**
* Filter {@link Target}s for all the given parameters. If all parameters
@@ -369,6 +395,9 @@ public interface TargetManagement {
* flag to select targets with no tag assigned
*
* @return the found {@link Target}s
+ *
+ * @throws EntityNotFoundException
+ * if distribution set with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Slice findTargetByFilters(@NotNull Pageable pageable, Collection status,
@@ -385,6 +414,9 @@ public interface TargetManagement {
* @param pageReq
* page parameter
* @return the found {@link Target}s
+ *
+ * @throws EntityNotFoundException
+ * if distribution set with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_READ_TARGET)
Page findTargetByInstalledDistributionSet(@NotNull Long distributionSetID, @NotNull Pageable pageReq);
@@ -407,6 +439,9 @@ public interface TargetManagement {
* given {@code fieldNameProvider}
* @throws RSQLParameterSyntaxException
* if the RSQL syntax is wrong
+ *
+ * @throws EntityNotFoundException
+ * if distribution set with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_READ_TARGET)
Page findTargetByInstalledDistributionSet(@NotNull Long distributionSetId, @NotNull String rsqlParam,
@@ -506,6 +541,9 @@ public interface TargetManagement {
* non-null value; filters are AND-gated
* @return a paged result {@link Page} of the {@link Target}s in a defined
* order.
+ *
+ * @throws EntityNotFoundException
+ * if distribution set with given ID does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
Slice findTargetsAllOrderByLinkedDistributionSet(@NotNull Pageable pageable,
@@ -546,6 +584,9 @@ public interface TargetManagement {
* @param tagName
* to toggle
* @return TagAssigmentResult with all meta data of the assignment outcome.
+ *
+ * @throws EntityNotFoundException
+ * if tag with given name does not exist
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET)
TargetTagAssignmentResult toggleTagAssignment(@NotEmpty Collection targetIds, @NotEmpty String tagName);
@@ -600,10 +641,10 @@ public interface TargetManagement {
*
* @param id
* to look for
- * @return {@link Target} or null if it does not exist
+ * @return {@link Target}
*/
@PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET)
- Target findTargetById(Long id);
+ Optional findTargetById(Long id);
/**
* Retrieves all targets without details, i.e. NO {@link Target#getTags()}
diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/EntityNotFoundException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/EntityNotFoundException.java
index 47cb1e274..146807db5 100644
--- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/EntityNotFoundException.java
+++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/EntityNotFoundException.java
@@ -8,15 +8,17 @@
*/
package org.eclipse.hawkbit.repository.exception;
+import java.util.Collection;
+import java.util.stream.Collectors;
+
import org.eclipse.hawkbit.exception.AbstractServerRtException;
import org.eclipse.hawkbit.exception.SpServerError;
+import org.eclipse.hawkbit.repository.model.BaseEntity;
+import org.eclipse.hawkbit.repository.model.MetaData;
/**
- * the {@link EntityNotFoundException} is thrown when a entity is tried find but
- * not found.
- *
- *
- *
+ * the {@link EntityNotFoundException} is thrown when a entity queried but not
+ * found.
*/
public class EntityNotFoundException extends AbstractServerRtException {
@@ -58,7 +60,51 @@ public class EntityNotFoundException extends AbstractServerRtException {
* @param message
* of the exception
*/
- public EntityNotFoundException(final String message) {
+ protected EntityNotFoundException(final String message) {
super(message, THIS_ERROR);
}
+
+ /**
+ * Parameterized constructor for {@link BaseEntity} not found.
+ *
+ * @param type
+ * of the entity that was not found
+ *
+ * @param enityId
+ * of the {@link BaseEntity}
+ */
+ public EntityNotFoundException(final Class extends BaseEntity> type, final Object enityId) {
+ this(type.getSimpleName() + " with given identifier {" + enityId + "} does not exist.");
+ }
+
+ /**
+ * Parameterized constructor for {@link MetaData} not found.
+ *
+ * @param type
+ * of the entity that was not found
+ * @param enityId
+ * of the {@link BaseEntity} the {@link MetaData} was for
+ * @param key
+ * for the {@link MetaData} entry
+ */
+ public EntityNotFoundException(final Class extends MetaData> type, final Long enityId, final String key) {
+ this(type.getSimpleName() + " for given entity {" + enityId + "} and with key {" + key + "} does not exist.");
+ }
+
+ /**
+ * Parameterized constructor for a list of {@link BaseEntity}s not found.
+ *
+ * @param type
+ * of the entity that was not found
+ *
+ * @param expected
+ * collection of the {@link BaseEntity#getId()}s
+ * @param found
+ * collection of the {@link BaseEntity#getId()}s
+ */
+ public EntityNotFoundException(final Class extends BaseEntity> type, final Collection expected,
+ final Collection found) {
+ this(type.getSimpleName() + "s with given identifiers {" + expected.stream().filter(id -> !found.contains(id))
+ .map(String::valueOf).collect(Collectors.joining(",")) + "} do not exist.");
+ }
}
diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/SoftwareModuleNotAssignedToTargetException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/SoftwareModuleNotAssignedToTargetException.java
new file mode 100644
index 000000000..af4e1ec21
--- /dev/null
+++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/SoftwareModuleNotAssignedToTargetException.java
@@ -0,0 +1,39 @@
+/**
+ * Copyright (c) 2015 Bosch Software Innovations GmbH and others.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.eclipse.hawkbit.repository.exception;
+
+import java.lang.annotation.Target;
+
+import org.eclipse.hawkbit.repository.model.Action;
+import org.eclipse.hawkbit.repository.model.SoftwareModule;
+
+/**
+ * the {@link SoftwareModuleNotAssignedToTargetException} is thrown when a
+ * {@link SoftwareModule} is requested as part of an {@link Action} that has
+ * however never been assigned to the {@link Target}.
+ */
+public class SoftwareModuleNotAssignedToTargetException extends EntityNotFoundException {
+
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Constructor
+ *
+ * @param moduleId
+ * thats is not assigned to given {@link Target}
+ * @param controllerId
+ * of the {@link Target} where given {@link SoftwareModule} is
+ * not part of
+ */
+ public SoftwareModuleNotAssignedToTargetException(final Long moduleId, final String controllerId) {
+ super("No assignment found for " + SoftwareModule.class.getSimpleName() + " with id {" + moduleId + "} to "
+ + Target.class.getSimpleName() + " with id {" + controllerId + "}.");
+ }
+
+}
diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/SoftwareModuleTypeNotInDistributionSetTypeException.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/SoftwareModuleTypeNotInDistributionSetTypeException.java
new file mode 100644
index 000000000..edfb8f436
--- /dev/null
+++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/SoftwareModuleTypeNotInDistributionSetTypeException.java
@@ -0,0 +1,40 @@
+/**
+ * Copyright (c) 2015 Bosch Software Innovations GmbH and others.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.eclipse.hawkbit.repository.exception;
+
+import org.eclipse.hawkbit.repository.model.DistributionSetType;
+import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
+
+/**
+ * the {@link SoftwareModuleTypeNotInDistributionSetTypeException} is thrown
+ * when a {@link SoftwareModuleType} is requested as part of a
+ * {@link DistributionSetType} but actually neither
+ * {@link DistributionSetType#getMandatoryModuleTypes()} or
+ * {@link DistributionSetType#getOptionalModuleTypes()}.
+ */
+public class SoftwareModuleTypeNotInDistributionSetTypeException extends EntityNotFoundException {
+
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Constructor
+ *
+ * @param moduleTypeId
+ * thats is not part of given {@link DistributionSetType}
+ * @param distributionSetTypeId
+ * of the {@link DistributionSetType} where given
+ * {@link SoftwareModuleType} is not part of
+ */
+ public SoftwareModuleTypeNotInDistributionSetTypeException(final Long moduleTypeId,
+ final Long distributionSetTypeId) {
+ super(SoftwareModuleType.class.getSimpleName() + " with id {" + moduleTypeId + "} is not part of "
+ + DistributionSetType.class.getSimpleName() + " with id {" + distributionSetTypeId + "}.");
+ }
+
+}
diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Action.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Action.java
index 5200510e4..464095b71 100644
--- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Action.java
+++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/Action.java
@@ -12,10 +12,7 @@ import java.util.List;
import java.util.concurrent.TimeUnit;
/**
- * Operations to be executed by the target. Usually a software update. Other
- * supported actions are the cancellation of a running update action or a
- * refresh request for target attributes.
- *
+ * Update operations to be executed by the target.
*/
public interface Action extends TenantAwareBaseEntity {
diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSet.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSet.java
index f8fc4a7ff..2e7e2c7ac 100644
--- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSet.java
+++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSet.java
@@ -9,6 +9,7 @@
package org.eclipse.hawkbit.repository.model;
import java.util.List;
+import java.util.Optional;
import java.util.Set;
/**
@@ -57,10 +58,10 @@ public interface DistributionSet extends NamedVersionedEntity {
*
* @param type
* to search for
- * @return SoftwareModule of given type or null if not found.
+ * @return SoftwareModule of given type
*/
- default SoftwareModule findFirstModuleByType(final SoftwareModuleType type) {
- return getModules().stream().filter(module -> module.getType().equals(type)).findFirst().orElse(null);
+ default Optional findFirstModuleByType(final SoftwareModuleType type) {
+ return getModules().stream().filter(module -> module.getType().equals(type)).findAny();
}
/**
diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetType.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetType.java
index c9aac9a2c..94bb1bfda 100644
--- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetType.java
+++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetType.java
@@ -73,7 +73,7 @@ public interface DistributionSetType extends NamedEntity {
*/
default boolean containsMandatoryModuleType(final Long softwareModuleTypeId) {
return getMandatoryModuleTypes().stream().filter(element -> element.getId().equals(softwareModuleTypeId))
- .findFirst().isPresent();
+ .findAny().isPresent();
}
/**
@@ -98,7 +98,7 @@ public interface DistributionSetType extends NamedEntity {
*/
default boolean containsOptionalModuleType(final Long softwareModuleTypeId) {
return getOptionalModuleTypes().stream().filter(element -> element.getId().equals(softwareModuleTypeId))
- .findFirst().isPresent();
+ .findAny().isPresent();
}
/**
diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModule.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModule.java
index ef4c31b46..b4c67e702 100644
--- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModule.java
+++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModule.java
@@ -23,11 +23,7 @@ public interface SoftwareModule extends NamedVersionedEntity {
* @return found {@link Artifact}
*/
default Optional getArtifact(final Long artifactId) {
- if (getArtifacts().isEmpty()) {
- return Optional.empty();
- }
-
- return getArtifacts().stream().filter(artifact -> artifact.getId().equals(artifactId)).findFirst();
+ return getArtifacts().stream().filter(artifact -> artifact.getId().equals(artifactId)).findAny();
}
/**
@@ -36,12 +32,8 @@ public interface SoftwareModule extends NamedVersionedEntity {
* @return found {@link Artifact}
*/
default Optional getArtifactByFilename(final String fileName) {
- if (getArtifacts().isEmpty()) {
- return Optional.empty();
- }
-
return getArtifacts().stream().filter(artifact -> artifact.getFilename().equalsIgnoreCase(fileName.trim()))
- .findFirst();
+ .findAny();
}
/**
diff --git a/hawkbit-repository/hawkbit-repository-api/src/test/java/org/eclipse/hawkbit/repository/RepositoryManagementMethodPreAuthorizeAnnotatedTest.java b/hawkbit-repository/hawkbit-repository-api/src/test/java/org/eclipse/hawkbit/repository/RepositoryManagementMethodPreAuthorizeAnnotatedTest.java
index 1a0d85d30..135e01570 100644
--- a/hawkbit-repository/hawkbit-repository-api/src/test/java/org/eclipse/hawkbit/repository/RepositoryManagementMethodPreAuthorizeAnnotatedTest.java
+++ b/hawkbit-repository/hawkbit-repository-api/src/test/java/org/eclipse/hawkbit/repository/RepositoryManagementMethodPreAuthorizeAnnotatedTest.java
@@ -8,7 +8,7 @@
*/
package org.eclipse.hawkbit.repository;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.lang.reflect.Method;
diff --git a/hawkbit-repository/hawkbit-repository-core/pom.xml b/hawkbit-repository/hawkbit-repository-core/pom.xml
index 2f18c74fa..5a17c97aa 100644
--- a/hawkbit-repository/hawkbit-repository-core/pom.xml
+++ b/hawkbit-repository/hawkbit-repository-core/pom.xml
@@ -37,23 +37,8 @@
- junit
- junit
- test
-
-
- org.mockito
- mockito-core
- test
-
-
- org.easytesting
- fest-assert-core
- test
-
-
- org.easytesting
- fest-assert
+ org.springframework.boot
+ spring-boot-starter-testtest
diff --git a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/event/EventType.java b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/event/EventType.java
index 13342020b..23aa8081e 100644
--- a/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/event/EventType.java
+++ b/hawkbit-repository/hawkbit-repository-core/src/main/java/org/eclipse/hawkbit/event/EventType.java
@@ -137,7 +137,7 @@ public class EventType {
*/
public static EventType from(final Class> clazz) {
final Optional foundEventType = TYPES.entrySet().stream()
- .filter(entry -> entry.getValue().equals(clazz)).map(entry -> entry.getKey()).findFirst();
+ .filter(entry -> entry.getValue().equals(clazz)).map(entry -> entry.getKey()).findAny();
if (!foundEventType.isPresent()) {
return null;
}
diff --git a/hawkbit-repository/hawkbit-repository-core/src/test/java/org/eclipse/hawkbit/event/BusProtoStuffMessageConverterTest.java b/hawkbit-repository/hawkbit-repository-core/src/test/java/org/eclipse/hawkbit/event/BusProtoStuffMessageConverterTest.java
index d8c9aeab4..6a7585dd1 100644
--- a/hawkbit-repository/hawkbit-repository-core/src/test/java/org/eclipse/hawkbit/event/BusProtoStuffMessageConverterTest.java
+++ b/hawkbit-repository/hawkbit-repository-core/src/test/java/org/eclipse/hawkbit/event/BusProtoStuffMessageConverterTest.java
@@ -8,15 +8,15 @@
*/
package org.eclipse.hawkbit.event;
-import static org.fest.assertions.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import java.util.HashMap;
+import org.assertj.core.api.Assertions;
import org.eclipse.hawkbit.repository.event.remote.entity.RemoteEntityEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetCreatedEvent;
import org.eclipse.hawkbit.repository.model.Target;
-import org.fest.assertions.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
diff --git a/hawkbit-repository/hawkbit-repository-jpa/pom.xml b/hawkbit-repository/hawkbit-repository-jpa/pom.xml
index 7398d24db..485d6783a 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/pom.xml
+++ b/hawkbit-repository/hawkbit-repository-jpa/pom.xml
@@ -109,16 +109,6 @@
allure-junit-adaptortest
-
- org.easytesting
- fest-assert-core
- test
-
-
- org.easytesting
- fest-assert
- test
- org.powermockpowermock-module-junit4
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionRepository.java
index 532b55b94..b386b34f3 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionRepository.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/ActionRepository.java
@@ -16,7 +16,6 @@ import org.eclipse.hawkbit.repository.jpa.model.JpaAction;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.jpa.model.JpaRollout;
import org.eclipse.hawkbit.repository.jpa.model.JpaRolloutGroup;
-import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status;
@@ -53,7 +52,7 @@ public interface ActionRepository extends BaseEntityRepository,
* @return the found {@link Action}
*/
@EntityGraph(value = "Action.all", type = EntityGraphType.LOAD)
- JpaAction findById(Long actionId);
+ Optional getById(Long actionId);
/**
* Retrieves all {@link Action}s which are referring the given
@@ -113,14 +112,14 @@ public interface ActionRepository extends BaseEntityRepository,
*
* @param targetId
* to search for
- * @param module
+ * @param moduleId
* to search for
* @return action if there is one with assigned target and module is part of
* assigned {@link DistributionSet}.
*/
- @Query("Select a from JpaAction a join a.distributionSet ds join ds.modules modul where a.target.controllerId = :target and modul = :module order by a.id desc")
+ @Query("Select a from JpaAction a join a.distributionSet ds join ds.modules modul where a.target.controllerId = :target and modul.id = :module order by a.id desc")
List findActionByTargetAndSoftwareModule(@Param("target") final String targetId,
- @Param("module") JpaSoftwareModule module);
+ @Param("module") Long moduleId);
/**
* Retrieves all {@link Action}s which are referring the given
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/BaseEntityRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/BaseEntityRepository.java
index 0d9f72b37..1b1c1fb1d 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/BaseEntityRepository.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/BaseEntityRepository.java
@@ -9,8 +9,10 @@
package org.eclipse.hawkbit.repository.jpa;
import java.io.Serializable;
+import java.util.Optional;
import org.eclipse.hawkbit.repository.jpa.model.AbstractJpaTenantAwareBaseEntity;
+import org.eclipse.hawkbit.repository.model.BaseEntity;
import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.repository.NoRepositoryBean;
@@ -41,4 +43,13 @@ public interface BaseEntityRepository findById(I id);
+
}
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetRepository.java
index 81ee7df7d..7aa56a512 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetRepository.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetRepository.java
@@ -12,10 +12,10 @@ import java.util.Collection;
import java.util.List;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
-import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule;
import org.eclipse.hawkbit.repository.model.Action;
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.SoftwareModule;
import org.eclipse.hawkbit.repository.model.Tag;
@@ -42,7 +42,7 @@ public interface DistributionSetRepository
* @return list of found {@link DistributionSet}s
*/
@Query(value = "Select Distinct ds from JpaDistributionSet ds join ds.tags dst where dst = :tag")
- List findByTag(@Param("tag") final JpaDistributionSetTag tag);
+ List findByTag(@Param("tag") final DistributionSetTag tag);
/**
* deletes the {@link DistributionSet}s with the given IDs.
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetTagRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetTagRepository.java
index 597c8b192..1fc5b4c44 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetTagRepository.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/DistributionSetTagRepository.java
@@ -9,6 +9,7 @@
package org.eclipse.hawkbit.repository.jpa;
import java.util.List;
+import java.util.Optional;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag;
import org.eclipse.hawkbit.repository.model.DistributionSet;
@@ -44,7 +45,7 @@ public interface DistributionSetTagRepository
* to filter on
* @return the {@link DistributionSetTag} if found, otherwise null
*/
- JpaDistributionSetTag findByNameEquals(final String tagName);
+ Optional findByNameEquals(final String tagName);
/**
* Returns all instances of the type.
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaArtifactManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaArtifactManagement.java
index 6e5af9b68..4e9ae1b4d 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaArtifactManagement.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaArtifactManagement.java
@@ -9,7 +9,6 @@
package org.eclipse.hawkbit.repository.jpa;
import java.io.InputStream;
-import java.util.List;
import java.util.Optional;
import org.eclipse.hawkbit.artifact.repository.ArtifactRepository;
@@ -105,9 +104,9 @@ public class JpaArtifactManagement implements ArtifactManagement {
@Override
@Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
- public boolean clearArtifactBinary(final Long existing) {
- return clearArtifactBinary(Optional.ofNullable(localArtifactRepository.findOne(existing))
- .orElseThrow(() -> new EntityNotFoundException("Artifact with given ID" + existing + " not found.")));
+ public boolean clearArtifactBinary(final Long artifactId) {
+ return clearArtifactBinary(localArtifactRepository.findById(artifactId)
+ .orElseThrow(() -> new EntityNotFoundException(Artifact.class, artifactId)));
}
private boolean clearArtifactBinary(final JpaArtifact existing) {
@@ -132,11 +131,8 @@ public class JpaArtifactManagement implements ArtifactManagement {
@Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteArtifact(final Long id) {
- final JpaArtifact existing = localArtifactRepository.findOne(id);
-
- if (null == existing) {
- return;
- }
+ final JpaArtifact existing = (JpaArtifact) findArtifact(id)
+ .orElseThrow(() -> new EntityNotFoundException(Artifact.class, id));
clearArtifactBinary(existing);
@@ -146,23 +142,23 @@ public class JpaArtifactManagement implements ArtifactManagement {
}
@Override
- public Artifact findArtifact(final Long id) {
- return localArtifactRepository.findOne(id);
+ public Optional findArtifact(final Long id) {
+ return Optional.ofNullable(localArtifactRepository.findOne(id));
}
@Override
- public List findByFilenameAndSoftwareModule(final String filename, final Long softwareModuleId) {
- return localArtifactRepository.findByFilenameAndSoftwareModuleId(filename, softwareModuleId);
+ public Optional findByFilenameAndSoftwareModule(final String filename, final Long softwareModuleId) {
+ return localArtifactRepository.findFirstByFilenameAndSoftwareModuleId(filename, softwareModuleId);
}
@Override
- public Artifact findFirstArtifactBySHA1(final String sha1Hash) {
+ public Optional findFirstArtifactBySHA1(final String sha1Hash) {
return localArtifactRepository.findFirstBySha1Hash(sha1Hash);
}
@Override
- public List findArtifactByFilename(final String filename) {
- return localArtifactRepository.findByFilename(filename);
+ public Optional findArtifactByFilename(final String filename) {
+ return localArtifactRepository.findFirstByFilename(filename);
}
@Override
@@ -208,7 +204,7 @@ public class JpaArtifactManagement implements ArtifactManagement {
if (softwareModule == null) {
LOG.debug("no software module with ID {} exists", moduleId);
- throw new EntityNotFoundException("Software Module: " + moduleId);
+ throw new EntityNotFoundException(SoftwareModule.class, moduleId);
}
return softwareModule;
}
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaControllerManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaControllerManagement.java
index 2a3dc126b..8a476ed2a 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaControllerManagement.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaControllerManagement.java
@@ -39,7 +39,6 @@ import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus;
import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus_;
import org.eclipse.hawkbit.repository.jpa.model.JpaAction_;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
-import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget;
import org.eclipse.hawkbit.repository.jpa.model.JpaTargetInfo;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget_;
@@ -47,7 +46,6 @@ import org.eclipse.hawkbit.repository.jpa.specifications.ActionSpecifications;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.ActionStatus;
-import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetInfo;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
@@ -133,33 +131,31 @@ public class JpaControllerManagement implements ControllerManagement {
@Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public Target updateLastTargetQuery(final String controllerId, final URI address) {
- final Target target = Optional.ofNullable(targetRepository.findByControllerId(controllerId))
- .orElseThrow(() -> new EntityNotFoundException("Target with given ID " + controllerId + " not found"));
+ final Target target = targetRepository.findByControllerId(controllerId)
+ .orElseThrow(() -> new EntityNotFoundException(Target.class, controllerId));
return updateTargetStatus(target.getTargetInfo(), null, System.currentTimeMillis(), address).getTarget();
}
@Override
- public Action getActionForDownloadByTargetAndSoftwareModule(final String controllerId,
- final SoftwareModule module) {
- final List action = actionRepository.findActionByTargetAndSoftwareModule(controllerId,
- (JpaSoftwareModule) module);
+ public Optional getActionForDownloadByTargetAndSoftwareModule(final String controllerId,
+ final Long moduleId) {
+ final List action = actionRepository.findActionByTargetAndSoftwareModule(controllerId, moduleId);
if (action.isEmpty() || action.get(0).isCancelingOrCanceled()) {
- throw new EntityNotFoundException(
- "No assigment found for module " + module.getId() + " to target " + controllerId);
+ return Optional.empty();
}
- return action.get(0);
+ return Optional.ofNullable(action.get(0));
}
@Override
public boolean hasTargetArtifactAssigned(final String controllerId, final String sha1Hash) {
- final Target target = targetRepository.findByControllerId(controllerId);
- if (target == null) {
+ final Optional target = targetRepository.findByControllerId(controllerId);
+ if (!target.isPresent()) {
return false;
}
- return actionRepository.count(ActionSpecifications.hasTargetAssignedArtifact(target, sha1Hash)) > 0;
+ return actionRepository.count(ActionSpecifications.hasTargetAssignedArtifact(target.get(), sha1Hash)) > 0;
}
@Override
@@ -180,8 +176,8 @@ public class JpaControllerManagement implements ControllerManagement {
}
@Override
- public Action findActionWithDetails(final Long actionId) {
- return getActionAndThrowExceptionIfNotFound(actionId);
+ public Optional findActionWithDetails(final Long actionId) {
+ return actionRepository.getById(actionId);
}
@Override
@@ -388,11 +384,8 @@ public class JpaControllerManagement implements ControllerManagement {
@Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public Target updateControllerAttributes(final String controllerId, final Map data) {
- final JpaTarget target = targetRepository.findByControllerId(controllerId);
-
- if (target == null) {
- throw new EntityNotFoundException(controllerId);
- }
+ final JpaTarget target = (JpaTarget) targetRepository.findByControllerId(controllerId)
+ .orElseThrow(() -> new EntityNotFoundException(Target.class, controllerId));
final JpaTargetInfo targetInfo = (JpaTargetInfo) target.getTargetInfo();
targetInfo.getControllerAttributes().putAll(data);
@@ -435,8 +428,7 @@ public class JpaControllerManagement implements ControllerManagement {
* {@link Status#RETRIEVED}
*/
private Action handleRegisterRetrieved(final Long actionId, final String message) {
- final JpaAction action = Optional.ofNullable(actionRepository.findById(actionId)).orElseThrow(
- () -> new EntityNotFoundException("Actionw ith given ID " + actionId + " doesn not exist."));
+ final JpaAction action = getActionAndThrowExceptionIfNotFound(actionId);
// do a manual query with CriteriaBuilder to avoid unnecessary field
// queries and an extra
// count query made by spring-data when using pageable requests, we
@@ -492,8 +484,8 @@ public class JpaControllerManagement implements ControllerManagement {
}
private JpaAction getActionAndThrowExceptionIfNotFound(final Long actionId) {
- return Optional.ofNullable(actionRepository.findById(actionId))
- .orElseThrow(() -> new EntityNotFoundException("Action with ID " + actionId + " not found!"));
+ return actionRepository.findById(actionId)
+ .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
}
@Override
@@ -504,13 +496,13 @@ public class JpaControllerManagement implements ControllerManagement {
}
@Override
- public Target findByControllerId(final String controllerId) {
+ public Optional findByControllerId(final String controllerId) {
return targetRepository.findByControllerId(controllerId);
}
@Override
- public Target findByTargetId(final Long targetId) {
- return targetRepository.findOne(targetId);
+ public Optional findByTargetId(final Long targetId) {
+ return Optional.ofNullable(targetRepository.findOne(targetId));
}
}
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDeploymentManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDeploymentManagement.java
index 8700a4677..8ce179987 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDeploymentManagement.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDeploymentManagement.java
@@ -174,8 +174,7 @@ public class JpaDeploymentManagement implements DeploymentManagement {
final Collection targets, final String actionMessage) {
final JpaDistributionSet set = distributoinSetRepository.findOne(dsID);
if (set == null) {
- throw new EntityNotFoundException(
- String.format("no %s with id %d found", DistributionSet.class.getSimpleName(), dsID));
+ throw new EntityNotFoundException(DistributionSet.class, dsID);
}
return assignDistributionSetToTargets(set, targets, null, null, actionMessage);
@@ -365,8 +364,8 @@ public class JpaDeploymentManagement implements DeploymentManagement {
public Action cancelAction(final Long actionId) {
LOG.debug("cancelAction({})", actionId);
- final JpaAction action = Optional.ofNullable(actionRepository.findOne(actionId))
- .orElseThrow(() -> new EntityNotFoundException("Action with given ID " + actionId + " not found"));
+ final JpaAction action = actionRepository.findById(actionId)
+ .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
if (action.isCancelingOrCanceled()) {
throw new CancelActionNotAllowedException("Actions in canceling or canceled state cannot be canceled");
@@ -412,8 +411,8 @@ public class JpaDeploymentManagement implements DeploymentManagement {
@Modifying
@Transactional(isolation = Isolation.READ_COMMITTED)
public Action forceQuitAction(final Long actionId) {
- final JpaAction action = Optional.ofNullable(actionRepository.findOne(actionId))
- .orElseThrow(() -> new EntityNotFoundException("Action with given ID " + actionId + " not found"));
+ final JpaAction action = actionRepository.findById(actionId)
+ .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
if (!action.isCancelingOrCanceled()) {
throw new ForceQuitActionNotAllowedException(
@@ -542,13 +541,13 @@ public class JpaDeploymentManagement implements DeploymentManagement {
}
@Override
- public Action findAction(final Long actionId) {
- return actionRepository.findOne(actionId);
+ public Optional findAction(final Long actionId) {
+ return Optional.ofNullable(actionRepository.findOne(actionId));
}
@Override
- public Action findActionWithDetails(final Long actionId) {
- return actionRepository.findById(actionId);
+ public Optional findActionWithDetails(final Long actionId) {
+ return actionRepository.getById(actionId);
}
@Override
@@ -622,8 +621,10 @@ public class JpaDeploymentManagement implements DeploymentManagement {
@Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public Action forceTargetAction(final Long actionId) {
- final JpaAction action = actionRepository.findOne(actionId);
- if (action != null && !action.isForced()) {
+ final JpaAction action = actionRepository.findById(actionId)
+ .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
+
+ if (!action.isForced()) {
action.setActionType(ActionType.FORCED);
return actionRepository.save(action);
}
@@ -632,11 +633,19 @@ public class JpaDeploymentManagement implements DeploymentManagement {
@Override
public Page findActionStatusByAction(final Pageable pageReq, final Long actionId) {
+ if (!actionRepository.exists(actionId)) {
+ throw new EntityNotFoundException(Action.class, actionId);
+ }
+
return actionStatusRepository.findByActionId(pageReq, actionId);
}
@Override
public Page findActionStatusByActionWithMessages(final Pageable pageReq, final Long actionId) {
+ if (!actionRepository.exists(actionId)) {
+ throw new EntityNotFoundException(Action.class, actionId);
+ }
+
return actionStatusRepository.getByActionId(pageReq, actionId);
}
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDistributionSetManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDistributionSetManagement.java
index 5798a29db..ee3134744 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDistributionSetManagement.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaDistributionSetManagement.java
@@ -48,6 +48,7 @@ import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility;
import org.eclipse.hawkbit.repository.jpa.specifications.DistributionSetSpecification;
import org.eclipse.hawkbit.repository.jpa.specifications.DistributionSetTypeSpecification;
import org.eclipse.hawkbit.repository.jpa.specifications.SpecificationsBuilder;
+import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetFilter;
import org.eclipse.hawkbit.repository.model.DistributionSetFilter.DistributionSetFilterBuilder;
@@ -56,6 +57,8 @@ import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.MetaData;
+import org.eclipse.hawkbit.repository.model.SoftwareModule;
+import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.rsql.VirtualPropertyReplacer;
import org.eclipse.hawkbit.tenancy.TenantAware;
import org.springframework.beans.factory.annotation.Autowired;
@@ -125,22 +128,28 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
private SoftwareModuleTypeRepository softwareModuleTypeRepository;
@Override
- public DistributionSet findDistributionSetByIdWithDetails(final Long distid) {
- return distributionSetRepository.findOne(DistributionSetSpecification.byId(distid));
+ public Optional findDistributionSetByIdWithDetails(final Long distid) {
+ return Optional.ofNullable(distributionSetRepository.findOne(DistributionSetSpecification.byId(distid)));
}
@Override
- public DistributionSet findDistributionSetById(final Long distid) {
- return distributionSetRepository.findOne(distid);
+ public Optional findDistributionSetById(final Long distid) {
+ return Optional.ofNullable(distributionSetRepository.findOne(distid));
}
@Override
@Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public DistributionSetTagAssignmentResult toggleTagAssignment(final Collection dsIds, final String tagName) {
-
final List sets = findDistributionSetListWithDetails(dsIds);
- final DistributionSetTag myTag = tagManagement.findDistributionSetTag(tagName);
+
+ if (sets.size() < dsIds.size()) {
+ throw new EntityNotFoundException(DistributionSet.class, dsIds,
+ sets.stream().map(DistributionSet::getId).collect(Collectors.toList()));
+ }
+
+ final DistributionSetTag myTag = tagManagement.findDistributionSetTag(tagName)
+ .orElseThrow(() -> new EntityNotFoundException(DistributionSetTag.class, tagName));
DistributionSetTagAssignmentResult result;
@@ -207,46 +216,37 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
}
private DistributionSetType findDistributionSetTypeWithExceptionIfNotFound(final String distributionSetTypekey) {
-
- final DistributionSetType module = findDistributionSetTypeByKey(distributionSetTypekey);
- if (module == null) {
- throw new EntityNotFoundException(
- "DistributionSetType with key {" + distributionSetTypekey + "} does not exist");
- }
- return module;
+ return findDistributionSetTypeByKey(distributionSetTypekey)
+ .orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, distributionSetTypekey));
}
private JpaDistributionSetType findDistributionSetTypeAndThrowExceptionIfNotFound(final Long setId) {
- final JpaDistributionSetType set = (JpaDistributionSetType) findDistributionSetTypeById(setId);
+ return (JpaDistributionSetType) findDistributionSetTypeById(setId)
+ .orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, setId));
- if (set == null) {
- throw new EntityNotFoundException("Distribution set type cannot be updated as it does not exixt" + setId);
- }
- return set;
}
private JpaDistributionSet findDistributionSetAndThrowExceptionIfNotFound(final Long setId) {
- final JpaDistributionSet set = (JpaDistributionSet) findDistributionSetById(setId);
-
- if (set == null) {
- throw new EntityNotFoundException("Distribution set cannot be updated as it does not exixt" + setId);
- }
- return set;
+ return (JpaDistributionSet) findDistributionSetById(setId)
+ .orElseThrow(() -> new EntityNotFoundException(DistributionSet.class, setId));
}
private JpaSoftwareModule findSoftwareModuleAndThrowExceptionIfNotFound(final Long moduleId) {
- final JpaSoftwareModule module = softwareModuleRepository.findOne(moduleId);
-
- if (module == null) {
- throw new EntityNotFoundException("Distribution set cannot be updated as it does not exixt" + moduleId);
- }
- return module;
+ return Optional.ofNullable(softwareModuleRepository.findOne(moduleId))
+ .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, moduleId));
}
@Override
@Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteDistributionSet(final Collection distributionSetIDs) {
+ final List setsFound = findDistributionSetAllById(distributionSetIDs);
+
+ if (setsFound.size() < distributionSetIDs.size()) {
+ throw new EntityNotFoundException(DistributionSet.class, distributionSetIDs,
+ setsFound.stream().map(DistributionSet::getId).collect(Collectors.toList()));
+ }
+
final List assigned = distributionSetRepository
.findAssignedToTargetDistributionSetsById(distributionSetIDs);
assigned.addAll(distributionSetRepository.findAssignedToRolloutDistributionSetsById(distributionSetIDs));
@@ -303,15 +303,17 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
@Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public DistributionSet assignSoftwareModules(final Long setId, final Collection moduleIds) {
- final JpaDistributionSet set = findDistributionSetAndThrowExceptionIfNotFound(setId);
+
final Collection modules = softwareModuleRepository.findByIdIn(moduleIds);
if (modules.size() < moduleIds.size()) {
- throw new EntityNotFoundException("Not all given software modules where found.");
+ throw new EntityNotFoundException(SoftwareModule.class, moduleIds,
+ modules.stream().map(SoftwareModule::getId).collect(Collectors.toList()));
}
checkDistributionSetIsAssignedToTargets(setId);
+ final JpaDistributionSet set = findDistributionSetAndThrowExceptionIfNotFound(setId);
modules.forEach(set::addModule);
return distributionSetRepository.save(set);
@@ -363,15 +365,15 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public DistributionSetType assignMandatorySoftwareModuleTypes(final Long dsTypeId,
final Collection softwareModulesTypeIds) {
- final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(dsTypeId);
-
final Collection modules = softwareModuleTypeRepository
.findByIdIn(softwareModulesTypeIds);
if (modules.size() < softwareModulesTypeIds.size()) {
- throw new EntityNotFoundException("Not all given software module types where found.");
+ throw new EntityNotFoundException(SoftwareModuleType.class, softwareModulesTypeIds,
+ modules.stream().map(SoftwareModuleType::getId).collect(Collectors.toList()));
}
+ final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(dsTypeId);
checkDistributionSetTypeSoftwareModuleTypesIsAllowedToModify(dsTypeId);
modules.forEach(type::addMandatoryModuleType);
@@ -384,17 +386,17 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public DistributionSetType assignOptionalSoftwareModuleTypes(final Long dsTypeId,
final Collection softwareModulesTypeIds) {
- final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(dsTypeId);
final Collection modules = softwareModuleTypeRepository
.findByIdIn(softwareModulesTypeIds);
if (modules.size() < softwareModulesTypeIds.size()) {
- throw new EntityNotFoundException("Not all given software module types where found.");
+ throw new EntityNotFoundException(SoftwareModuleType.class, softwareModulesTypeIds,
+ modules.stream().map(SoftwareModuleType::getId).collect(Collectors.toList()));
}
+ final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(dsTypeId);
checkDistributionSetTypeSoftwareModuleTypesIsAllowedToModify(dsTypeId);
-
modules.forEach(type::addOptionalModuleType);
return distributionSetTypeRepository.save(type);
@@ -545,10 +547,11 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
}
@Override
- public DistributionSet findDistributionSetByNameAndVersion(final String distributionName, final String version) {
+ public Optional findDistributionSetByNameAndVersion(final String distributionName,
+ final String version) {
final Specification spec = DistributionSetSpecification
.equalsNameAndVersionIgnoreCase(distributionName, version);
- return distributionSetRepository.findOne(spec);
+ return Optional.ofNullable(distributionSetRepository.findOne(spec));
}
@@ -571,18 +574,20 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
}
@Override
- public DistributionSetType findDistributionSetTypeByName(final String name) {
- return distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byName(name));
+ public Optional findDistributionSetTypeByName(final String name) {
+ return Optional
+ .ofNullable(distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byName(name)));
}
@Override
- public DistributionSetType findDistributionSetTypeById(final Long id) {
- return distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byId(id));
+ public Optional findDistributionSetTypeById(final Long typeId) {
+ return Optional
+ .ofNullable(distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byId(typeId)));
}
@Override
- public DistributionSetType findDistributionSetTypeByKey(final String key) {
- return distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byKey(key));
+ public Optional findDistributionSetTypeByKey(final String key) {
+ return Optional.ofNullable(distributionSetTypeRepository.findOne(DistributionSetTypeSpecification.byKey(key)));
}
@Override
@@ -599,9 +604,8 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteDistributionSetType(final Long typeId) {
- final JpaDistributionSetType toDelete = Optional.ofNullable(distributionSetTypeRepository.findOne(typeId))
- .orElseThrow(() -> new EntityNotFoundException(
- "DistributionSet Type with given ID " + typeId + " does not exist"));
+ final JpaDistributionSetType toDelete = distributionSetTypeRepository.findById(typeId)
+ .orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, typeId));
if (distributionSetRepository.countByTypeId(typeId) > 0) {
toDelete.setDeleted(true);
@@ -634,7 +638,8 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
// check if exists otherwise throw entity not found exception
final JpaDistributionSetMetadata toUpdate = (JpaDistributionSetMetadata) findDistributionSetMetadata(dsId,
- md.getKey());
+ md.getKey()).orElseThrow(
+ () -> new EntityNotFoundException(DistributionSetMetadata.class, dsId, md.getKey()));
toUpdate.setValue(md.getValue());
// touch it to update the lock revision because we are modifying the
// DS indirectly
@@ -645,9 +650,32 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
@Override
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
@Modifying
- public void deleteDistributionSetMetadata(final Long distributionSet, final String key) {
- touch(distributionSet);
- distributionSetMetadataRepository.delete(new DsMetadataCompositeKey(distributionSet, key));
+ public void deleteDistributionSetMetadata(final Long distributionSetId, final String key) {
+ final JpaDistributionSetMetadata metadata = (JpaDistributionSetMetadata) findDistributionSetMetadata(
+ distributionSetId, key).orElseThrow(
+ () -> new EntityNotFoundException(DistributionSetMetadata.class, distributionSetId, key));
+
+ touch(metadata.getDistributionSet());
+ distributionSetMetadataRepository.delete(metadata.getId());
+ }
+
+ /**
+ * Method to get the latest distribution set based on DS ID after the
+ * metadata changes for that distribution set.
+ *
+ * @param ds
+ * is the DS to touch
+ */
+ private JpaDistributionSet touch(final DistributionSet ds) {
+
+ // merge base distribution set so optLockRevision gets updated and audit
+ // log written because
+ // modifying metadata is modifying the base distribution set itself for
+ // auditing purposes.
+ final JpaDistributionSet result = entityManager.merge((JpaDistributionSet) ds);
+ result.setLastModifiedAt(0L);
+
+ return result;
}
/**
@@ -655,24 +683,20 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
* metadata changes for that distribution set.
*
* @param distId
- * Distribution set
+ * of the DS to touch
*/
private JpaDistributionSet touch(final Long distId) {
- final DistributionSet latestDistributionSet = findDistributionSetAndThrowExceptionIfNotFound(distId);
-
- // merge base distribution set so optLockRevision gets updated and audit
- // log written because
- // modifying metadata is modifying the base distribution set itself for
- // auditing purposes.
- final JpaDistributionSet result = entityManager.merge((JpaDistributionSet) latestDistributionSet);
- result.setLastModifiedAt(0L);
-
- return result;
+ return touch(findDistributionSetById(distId)
+ .orElseThrow(() -> new EntityNotFoundException(DistributionSet.class, distId)));
}
@Override
public Page findDistributionSetMetadataByDistributionSetId(final Long distributionSetId,
final Pageable pageable) {
+ if (!distributionSetRepository.exists(distributionSetId)) {
+ throw new EntityNotFoundException(DistributionSet.class, distributionSetId);
+ }
+
return convertMdPage(distributionSetMetadataRepository
.findAll((Specification) (root, query, cb) -> cb.equal(
root.get(JpaDistributionSetMetadata_.distributionSet).get(JpaDistributionSet_.id),
@@ -680,18 +704,14 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
pageable);
}
- @Override
- public List findDistributionSetMetadataByDistributionSetId(final Long distributionSetId) {
- return Collections.unmodifiableList(distributionSetMetadataRepository
- .findAll((Specification) (root, query, cb) -> cb.equal(
- root.get(JpaDistributionSetMetadata_.distributionSet).get(JpaDistributionSet_.id),
- distributionSetId)));
- }
-
@Override
public Page findDistributionSetMetadataByDistributionSetId(final Long distributionSetId,
final String rsqlParam, final Pageable pageable) {
+ if (!distributionSetRepository.exists(distributionSetId)) {
+ throw new EntityNotFoundException(DistributionSet.class, distributionSetId);
+ }
+
final Specification spec = RSQLUtility.parse(rsqlParam,
DistributionSetMetadataFields.class, virtualPropertyReplacer);
@@ -710,18 +730,18 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
}
@Override
- public DistributionSetMetadata findDistributionSetMetadata(final Long distributionSet, final String key) {
- final DistributionSetMetadata findOne = distributionSetMetadataRepository
- .findOne(new DsMetadataCompositeKey(distributionSet, key));
- if (findOne == null) {
- throw new EntityNotFoundException("Metadata with key '" + key + "' does not exist");
- }
- return findOne;
+ public Optional findDistributionSetMetadata(final Long distributionSet, final String key) {
+ return Optional.ofNullable(
+ distributionSetMetadataRepository.findOne(new DsMetadataCompositeKey(distributionSet, key)));
}
@Override
- public DistributionSet findDistributionSetByAction(final Long actionId) {
- return distributionSetRepository.findByActionId(actionId);
+ public Optional findDistributionSetByAction(final Long actionId) {
+ if (!actionRepository.exists(actionId)) {
+ throw new EntityNotFoundException(Action.class, actionId);
+ }
+
+ return Optional.ofNullable(distributionSetRepository.findByActionId(actionId));
}
@Override
@@ -819,10 +839,13 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
public List assignTag(final Collection dsIds, final Long dsTagId) {
final List allDs = findDistributionSetListWithDetails(dsIds);
- final DistributionSetTag distributionSetTag = Optional
- .ofNullable(tagManagement.findDistributionSetTagById(dsTagId))
- .orElseThrow(() -> new EntityNotFoundException(
- "DistributionSet Tag with given ID " + dsTagId + " not found."));
+ if (allDs.size() < dsIds.size()) {
+ throw new EntityNotFoundException(DistributionSet.class, dsIds,
+ allDs.stream().map(DistributionSet::getId).collect(Collectors.toList()));
+ }
+
+ final DistributionSetTag distributionSetTag = tagManagement.findDistributionSetTagById(dsTagId)
+ .orElseThrow(() -> new EntityNotFoundException(DistributionSetTag.class, dsTagId));
allDs.forEach(ds -> ds.addTag(distributionSetTag));
@@ -835,10 +858,8 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public List unAssignAllDistributionSetsByTag(final Long dsTagId) {
- final DistributionSetTag distributionSetTag = Optional
- .ofNullable(tagManagement.findDistributionSetTagById(dsTagId))
- .orElseThrow(() -> new EntityNotFoundException(
- "DistributionSet Tag with given ID " + dsTagId + " not found."));
+ final DistributionSetTag distributionSetTag = tagManagement.findDistributionSetTagById(dsTagId)
+ .orElseThrow(() -> new EntityNotFoundException(DistributionSetTag.class, dsTagId));
@SuppressWarnings({ "unchecked", "rawtypes" })
final Collection distributionSets = (Collection) distributionSetTag
@@ -854,13 +875,11 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
final List allDs = findDistributionSetListWithDetails(Arrays.asList(dsId));
if (allDs.isEmpty()) {
- throw new EntityNotFoundException("DistributionSet with given ID " + dsId + " not found.");
+ throw new EntityNotFoundException(DistributionSet.class, dsId);
}
- final DistributionSetTag distributionSetTag = Optional
- .ofNullable(tagManagement.findDistributionSetTagById(dsTagId))
- .orElseThrow(() -> new EntityNotFoundException(
- "DistributionSet Tag with given ID " + dsTagId + " not found."));
+ final DistributionSetTag distributionSetTag = tagManagement.findDistributionSetTagById(dsTagId)
+ .orElseThrow(() -> new EntityNotFoundException(DistributionSetTag.class, dsTagId));
final List unAssignTag = unAssignTag(allDs, distributionSetTag);
return unAssignTag.isEmpty() ? null : unAssignTag.get(0);
}
@@ -885,7 +904,7 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteDistributionSet(final Long setId) {
if (!distributionSetRepository.exists(setId)) {
- throw new EntityNotFoundException("DistributionSet with given ID " + setId + " does not exist.");
+ throw new EntityNotFoundException(DistributionSet.class, setId);
}
deleteDistributionSet(Lists.newArrayList(setId));
@@ -893,6 +912,10 @@ public class JpaDistributionSetManagement implements DistributionSetManagement {
@Override
public Long countDistributionSetsByType(final Long typeId) {
+ if (!distributionSetTypeRepository.exists(typeId)) {
+ throw new EntityNotFoundException(DistributionSetType.class, typeId);
+ }
+
return distributionSetRepository.countByTypeId(typeId);
}
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutGroupManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutGroupManagement.java
index 23ca21efd..5c5c9762a 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutGroupManagement.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutGroupManagement.java
@@ -78,8 +78,8 @@ public class JpaRolloutGroupManagement implements RolloutGroupManagement {
private VirtualPropertyReplacer virtualPropertyReplacer;
@Override
- public RolloutGroup findRolloutGroupById(final Long rolloutGroupId) {
- return rolloutGroupRepository.findOne(rolloutGroupId);
+ public Optional findRolloutGroupById(final Long rolloutGroupId) {
+ return Optional.ofNullable(rolloutGroupRepository.findOne(rolloutGroupId));
}
@Override
@@ -131,14 +131,21 @@ public class JpaRolloutGroupManagement implements RolloutGroupManagement {
}
@Override
- public RolloutGroup findRolloutGroupWithDetailedStatus(final Long rolloutGroupId) {
- final JpaRolloutGroup rolloutGroup = (JpaRolloutGroup) findRolloutGroupById(rolloutGroupId);
+ public Optional findRolloutGroupWithDetailedStatus(final Long rolloutGroupId) {
+ final Optional rolloutGroup = findRolloutGroupById(rolloutGroupId);
+
+ if (!rolloutGroup.isPresent()) {
+ return rolloutGroup;
+ }
+
+ final JpaRolloutGroup jpaRolloutGroup = (JpaRolloutGroup) rolloutGroup.get();
+
final List rolloutStatusCountItems = actionRepository
.getStatusCountByRolloutGroupId(rolloutGroupId);
final TotalTargetCountStatus totalTargetCountStatus = new TotalTargetCountStatus(rolloutStatusCountItems,
- Long.valueOf(rolloutGroup.getTotalTargets()));
- rolloutGroup.setTotalTargetCountStatus(totalTargetCountStatus);
+ Long.valueOf(jpaRolloutGroup.getTotalTargets()));
+ jpaRolloutGroup.setTotalTargetCountStatus(totalTargetCountStatus);
return rolloutGroup;
}
@@ -168,9 +175,8 @@ public class JpaRolloutGroupManagement implements RolloutGroupManagement {
@Override
public Page findRolloutGroupTargets(final Long rolloutGroupId, final Pageable page) {
- final JpaRolloutGroup rolloutGroup = Optional.ofNullable(rolloutGroupRepository.findOne(rolloutGroupId))
- .orElseThrow(() -> new EntityNotFoundException(
- "Rollout Group with given ID " + rolloutGroupId + " not found."));
+ final JpaRolloutGroup rolloutGroup = rolloutGroupRepository.findById(rolloutGroupId)
+ .orElseThrow(() -> new EntityNotFoundException(RolloutGroup.class, rolloutGroupId));
if (isRolloutStatusReady(rolloutGroup)) {
// in case of status ready the action has not been created yet and
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutManagement.java
index 4478de556..120853eeb 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutManagement.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutManagement.java
@@ -17,7 +17,6 @@ import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
-import javax.persistence.EntityNotFoundException;
import javax.validation.ConstraintDeclarationException;
import org.apache.commons.lang3.StringUtils;
@@ -34,6 +33,7 @@ import org.eclipse.hawkbit.repository.builder.RolloutUpdate;
import org.eclipse.hawkbit.repository.event.remote.entity.RolloutGroupCreatedEvent;
import org.eclipse.hawkbit.repository.exception.ConstraintViolationException;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
+import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.RolloutIllegalStateException;
import org.eclipse.hawkbit.repository.jpa.executor.AfterTransactionCommitExecutor;
import org.eclipse.hawkbit.repository.jpa.model.JpaAction;
@@ -147,7 +147,6 @@ public class JpaRolloutManagement implements RolloutManagement {
@Override
public Page findAllByPredicate(final String rsqlParam, final Pageable pageable) {
-
final Specification specification = RSQLUtility.parse(rsqlParam, RolloutFields.class,
virtualPropertyReplacer);
@@ -156,8 +155,8 @@ public class JpaRolloutManagement implements RolloutManagement {
}
@Override
- public Rollout findRolloutById(final Long rolloutId) {
- return rolloutRepository.findOne(rolloutId);
+ public Optional findRolloutById(final Long rolloutId) {
+ return Optional.ofNullable(rolloutRepository.findOne(rolloutId));
}
@Override
@@ -181,9 +180,9 @@ public class JpaRolloutManagement implements RolloutManagement {
}
private JpaRollout createRollout(final JpaRollout rollout) {
- final JpaRollout existingRollout = rolloutRepository.findByName(rollout.getName());
- if (existingRollout != null) {
- throw new EntityAlreadyExistsException(existingRollout.getName());
+ final Optional existingRollout = rolloutRepository.findByName(rollout.getName());
+ if (existingRollout.isPresent()) {
+ throw new EntityAlreadyExistsException(existingRollout.get().getName());
}
final Long totalTargets = targetManagement.countTargetByTargetFilterQuery(rollout.getTargetFilterQuery());
@@ -294,8 +293,7 @@ public class JpaRolloutManagement implements RolloutManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
@Modifying
public void fillRolloutGroupsWithTargets(final Long rolloutId) {
- final JpaRollout rollout = Optional.ofNullable(rolloutRepository.findOne(rolloutId))
- .orElseThrow(() -> new EntityNotFoundException("Rollout with id " + rolloutId + " not found."));
+ final JpaRollout rollout = getRolloutAndThrowExceptionIfNotFound(rolloutId);
RolloutHelper.verifyRolloutInStatus(rollout, RolloutStatus.CREATING);
@@ -409,7 +407,7 @@ public class JpaRolloutManagement implements RolloutManagement {
throw new ConstraintDeclarationException("Rollout target filter does not match any targets");
}
- RolloutGroupsValidation validation = validateTargetsInGroups(groups, baseFilter, totalTargets);
+ final RolloutGroupsValidation validation = validateTargetsInGroups(groups, baseFilter, totalTargets);
return totalTargets - validation.getTargetsInGroups();
}
@@ -433,14 +431,14 @@ public class JpaRolloutManagement implements RolloutManagement {
final long totalTargets) {
final List groupTargetCounts = new ArrayList<>(groups.size());
final Map targetFilterCounts = groups.stream()
- .map(group -> RolloutHelper.getGroupTargetFilter(baseFilter, group)).distinct().collect(Collectors
- .toMap(Function.identity(), filter -> targetManagement.countTargetByTargetFilterQuery(filter)));
+ .map(group -> RolloutHelper.getGroupTargetFilter(baseFilter, group)).distinct()
+ .collect(Collectors.toMap(Function.identity(), targetManagement::countTargetByTargetFilterQuery));
long unusedTargetsCount = 0;
for (int i = 0; i < groups.size(); i++) {
final RolloutGroup group = groups.get(i);
- String groupTargetFilter = RolloutHelper.getGroupTargetFilter(baseFilter, group);
+ final String groupTargetFilter = RolloutHelper.getGroupTargetFilter(baseFilter, group);
RolloutHelper.verifyRolloutGroupTargetPercentage(group.getTargetPercentage());
final long targetsInGroupFilter = targetFilterCounts.get(groupTargetFilter);
@@ -474,8 +472,8 @@ public class JpaRolloutManagement implements RolloutManagement {
return 0;
}
final List previousGroups = groups.subList(0, groupIndex);
- String overlappingTargetsFilter = RolloutHelper.getOverlappingWithGroupsTargetFilter(baseFilter, previousGroups,
- group);
+ final String overlappingTargetsFilter = RolloutHelper.getOverlappingWithGroupsTargetFilter(baseFilter,
+ previousGroups, group);
if (targetFilterCounts.containsKey(overlappingTargetsFilter)) {
return targetFilterCounts.get(overlappingTargetsFilter);
@@ -490,8 +488,7 @@ public class JpaRolloutManagement implements RolloutManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
@Modifying
public Rollout startRollout(final Long rolloutId) {
- final JpaRollout rollout = Optional.ofNullable(rolloutRepository.findOne(rolloutId))
- .orElseThrow(() -> new EntityNotFoundException("Rollout with id " + rolloutId + " not found."));
+ final JpaRollout rollout = getRolloutAndThrowExceptionIfNotFound(rolloutId);
RolloutHelper.checkIfRolloutCanStarted(rollout, rollout);
rollout.setStatus(RolloutStatus.STARTING);
rollout.setLastCheck(0);
@@ -516,7 +513,6 @@ public class JpaRolloutManagement implements RolloutManagement {
jpaRollout.setStatus(RolloutStatus.RUNNING);
jpaRollout.setLastCheck(0);
rolloutRepository.save(jpaRollout);
-
}
private boolean ensureAllGroupsAreScheduled(final Rollout rollout) {
@@ -534,12 +530,6 @@ public class JpaRolloutManagement implements RolloutManagement {
/**
* Schedules a group of the rollout. Scheduled Actions are created to
* achieve this. The creation of those Actions is allowed to fail.
- *
- * @param rollout
- * the Rollout
- * @param group
- * the RolloutGroup
- * @return whether the complete group was scheduled
*/
private boolean scheduleRolloutGroup(final JpaRollout rollout, final JpaRolloutGroup group) {
final long targetsInGroup = rolloutTargetGroupRepository.countByRolloutGroup(group);
@@ -599,19 +589,6 @@ public class JpaRolloutManagement implements RolloutManagement {
* Creates an action entry into the action repository. In case of existing
* scheduled actions the scheduled actions gets canceled. A scheduled action
* is created in-active.
- *
- * @param targets
- * the targets to create scheduled actions for
- * @param distributionSet
- * the distribution set for the actions
- * @param actionType
- * the action type for the action
- * @param forcedTime
- * the forcedTime of the action
- * @param rollout
- * the roll out for this action
- * @param rolloutGroup
- * the roll out group for this action
*/
private void createScheduledAction(final Collection targets, final DistributionSet distributionSet,
final ActionType actionType, final Long forcedTime, final Rollout rollout,
@@ -620,7 +597,7 @@ public class JpaRolloutManagement implements RolloutManagement {
// is already scheduled and a next action is created then cancel the
// current scheduled action to cancel. E.g. a new scheduled action is
// created.
- final List targetIds = targets.stream().map(t -> t.getId()).collect(Collectors.toList());
+ final List targetIds = targets.stream().map(Target::getId).collect(Collectors.toList());
actionRepository.switchStatus(Action.Status.CANCELED, targetIds, false, Action.Status.SCHEDULED);
targets.forEach(target -> {
final JpaAction action = new JpaAction();
@@ -640,8 +617,7 @@ public class JpaRolloutManagement implements RolloutManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
@Modifying
public void pauseRollout(final Long rolloutId) {
- final JpaRollout rollout = Optional.ofNullable(rolloutRepository.findOne(rolloutId))
- .orElseThrow(() -> new EntityNotFoundException("Rollout with id " + rolloutId + " not found."));
+ final JpaRollout rollout = getRolloutAndThrowExceptionIfNotFound(rolloutId);
if (rollout.getStatus() != RolloutStatus.RUNNING) {
throw new RolloutIllegalStateException("Rollout can only be paused in state running but current state is "
+ rollout.getStatus().name().toLowerCase());
@@ -659,8 +635,7 @@ public class JpaRolloutManagement implements RolloutManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
@Modifying
public void resumeRollout(final Long rolloutId) {
- final JpaRollout rollout = Optional.ofNullable(rolloutRepository.findOne(rolloutId))
- .orElseThrow(() -> new EntityNotFoundException("Rollout with id " + rolloutId + " not found."));
+ final JpaRollout rollout = getRolloutAndThrowExceptionIfNotFound(rolloutId);
if (!(RolloutStatus.PAUSED.equals(rollout.getStatus()))) {
throw new RolloutIllegalStateException("Rollout can only be resumed in state paused but current state is "
+ rollout.getStatus().name().toLowerCase());
@@ -855,7 +830,6 @@ public class JpaRolloutManagement implements RolloutManagement {
startFirstRolloutGroup(rollout);
}
});
-
}
@Override
@@ -876,7 +850,6 @@ public class JpaRolloutManagement implements RolloutManagement {
startRollout(rollout.getId());
}
});
-
}
private List getRolloutsToCheckForStatus(final long delayBetweenChecks, final RolloutStatus status) {
@@ -891,7 +864,6 @@ public class JpaRolloutManagement implements RolloutManagement {
}
return rolloutRepository.findByLastCheckAndStatus(lastCheck, status);
-
}
@Override
@@ -913,7 +885,7 @@ public class JpaRolloutManagement implements RolloutManagement {
}
@Override
- public Rollout findRolloutByName(final String rolloutName) {
+ public Optional findRolloutByName(final String rolloutName) {
return rolloutRepository.findByName(rolloutName);
}
@@ -922,8 +894,7 @@ public class JpaRolloutManagement implements RolloutManagement {
@Modifying
public Rollout updateRollout(final RolloutUpdate u) {
final GenericRolloutUpdate update = (GenericRolloutUpdate) u;
- final JpaRollout rollout = Optional.ofNullable(rolloutRepository.findOne(update.getId()))
- .orElseThrow(() -> new EntityNotFoundException("Rollout with id " + update.getId() + " not found."));
+ final JpaRollout rollout = getRolloutAndThrowExceptionIfNotFound(update.getId());
update.getName().ifPresent(rollout::setName);
update.getDescription().ifPresent(rollout::setDescription);
@@ -931,32 +902,40 @@ public class JpaRolloutManagement implements RolloutManagement {
update.getForcedTime().ifPresent(rollout::setForcedTime);
update.getStartAt().ifPresent(rollout::setStartAt);
update.getSet().ifPresent(setId -> {
- final DistributionSet set = distributionSetManagement.findDistributionSetById(setId);
- if (set == null) {
- throw new EntityNotFoundException("Distribution set cannot be set as it does not exists" + setId);
- }
+ final DistributionSet set = distributionSetManagement.findDistributionSetById(setId)
+ .orElseThrow(() -> new EntityNotFoundException(DistributionSet.class, setId));
+
rollout.setDistributionSet(set);
});
return rolloutRepository.save(rollout);
}
+ private JpaRollout getRolloutAndThrowExceptionIfNotFound(final Long rolloutId) {
+ return rolloutRepository.findById(rolloutId)
+ .orElseThrow(() -> new EntityNotFoundException(Rollout.class, rolloutId));
+ }
+
@Override
public Page findAllRolloutsWithDetailedStatus(final Pageable pageable) {
final Page rollouts = rolloutRepository.findAll(pageable);
setRolloutStatusDetails(rollouts);
return RolloutHelper.convertPage(rollouts, pageable);
-
}
@Override
- public Rollout findRolloutWithDetailedStatus(final Long rolloutId) {
- final Rollout rollout = findRolloutById(rolloutId);
+ public Optional findRolloutWithDetailedStatus(final Long rolloutId) {
+ final Optional rollout = findRolloutById(rolloutId);
+
+ if (!rollout.isPresent()) {
+ return rollout;
+ }
+
final List rolloutStatusCountItems = actionRepository
.getStatusCountByRolloutId(rolloutId);
final TotalTargetCountStatus totalTargetCountStatus = new TotalTargetCountStatus(rolloutStatusCountItems,
- rollout.getTotalTargets());
- ((JpaRollout) rollout).setTotalTargetCountStatus(totalTargetCountStatus);
+ rollout.get().getTotalTargets());
+ ((JpaRollout) rollout.get()).setTotalTargetCountStatus(totalTargetCountStatus);
return rollout;
}
@@ -966,8 +945,7 @@ public class JpaRolloutManagement implements RolloutManagement {
}
private void setRolloutStatusDetails(final Slice rollouts) {
- final List rolloutIds = rollouts.getContent().stream().map(rollout -> rollout.getId())
- .collect(Collectors.toList());
+ final List rolloutIds = rollouts.getContent().stream().map(Rollout::getId).collect(Collectors.toList());
final Map> allStatesForRollout = getStatusCountItemForRollout(
rolloutIds);
@@ -980,20 +958,24 @@ public class JpaRolloutManagement implements RolloutManagement {
@Override
public float getFinishedPercentForRunningGroup(final Long rolloutId, final Long rolloutGroupId) {
- final RolloutGroup rolloutGroup = Optional.ofNullable(rolloutGroupRepository.findOne(rolloutGroupId))
- .orElseThrow(() -> new EntityNotFoundException(
- "Rollout group with given ID " + rolloutGroupId + " not found."));
+ final RolloutGroup rolloutGroup = rolloutGroupRepository.findById(rolloutGroupId)
+ .orElseThrow(() -> new EntityNotFoundException(RolloutGroup.class, rolloutGroupId));
final long totalGroup = rolloutGroup.getTotalTargets();
- final Long finished = actionRepository.countByRolloutIdAndRolloutGroupIdAndStatus(rolloutId,
- rolloutGroup.getId(), Action.Status.FINISHED);
if (totalGroup == 0) {
// in case e.g. targets has been deleted we don't have any actions
// left for this group, so the group is finished
return 100;
}
+
+ final Long finished = actionRepository.countByRolloutIdAndRolloutGroupIdAndStatus(rolloutId,
+ rolloutGroup.getId(), Action.Status.FINISHED);
// calculate threshold
return ((float) finished / (float) totalGroup) * 100;
}
+ @Override
+ public boolean exists(final Long rolloutId) {
+ return rolloutRepository.exists(rolloutId);
+ }
}
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSoftwareManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSoftwareManagement.java
index 7480d8c79..8735324e1 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSoftwareManagement.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaSoftwareManagement.java
@@ -55,6 +55,7 @@ import org.eclipse.hawkbit.repository.jpa.specifications.SoftwareModuleSpecifica
import org.eclipse.hawkbit.repository.jpa.specifications.SpecificationsBuilder;
import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.repository.model.AssignedSoftwareModule;
+import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.MetaData;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata;
@@ -122,9 +123,8 @@ public class JpaSoftwareManagement implements SoftwareManagement {
public SoftwareModule updateSoftwareModule(final SoftwareModuleUpdate u) {
final GenericSoftwareModuleUpdate update = (GenericSoftwareModuleUpdate) u;
- final JpaSoftwareModule module = Optional.ofNullable(softwareModuleRepository.findOne(update.getId()))
- .orElseThrow(() -> new EntityNotFoundException(
- "Software module cannot be updated as it does not exixt" + update.getId()));
+ final JpaSoftwareModule module = softwareModuleRepository.findById(update.getId())
+ .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, update.getId()));
update.getDescription().ifPresent(module::setDescription);
update.getVendor().ifPresent(module::setVendor);
@@ -138,7 +138,8 @@ public class JpaSoftwareManagement implements SoftwareManagement {
public SoftwareModuleType updateSoftwareModuleType(final SoftwareModuleTypeUpdate u) {
final GenericSoftwareModuleTypeUpdate update = (GenericSoftwareModuleTypeUpdate) u;
- final JpaSoftwareModuleType type = findSoftwareModuleTypeAndThrowExceptionIfNotFound(update.getId());
+ final JpaSoftwareModuleType type = (JpaSoftwareModuleType) findSoftwareModuleTypeById(update.getId())
+ .orElseThrow(() -> new EntityNotFoundException(SoftwareModuleType.class, update.getId()));
update.getDescription().ifPresent(type::setDescription);
update.getColour().ifPresent(type::setColour);
@@ -146,15 +147,6 @@ public class JpaSoftwareManagement implements SoftwareManagement {
return softwareModuleTypeRepository.save(type);
}
- private JpaSoftwareModuleType findSoftwareModuleTypeAndThrowExceptionIfNotFound(final Long smTypeid) {
- final JpaSoftwareModuleType set = softwareModuleTypeRepository.findOne(smTypeid);
-
- if (set == null) {
- throw new EntityNotFoundException("Software module type cannot be updated as it does not exixt" + smTypeid);
- }
- return set;
- }
-
@Override
@Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
@@ -173,6 +165,7 @@ public class JpaSoftwareManagement implements SoftwareManagement {
@Override
public Slice findSoftwareModulesByType(final Pageable pageable, final Long typeId) {
+ throwExceptionIfSoftwareModuleTypeDoesNotExist(typeId);
final List> specList = Lists.newArrayListWithExpectedSize(2);
@@ -182,6 +175,12 @@ public class JpaSoftwareManagement implements SoftwareManagement {
return convertSmPage(findSwModuleByCriteriaAPI(pageable, specList), pageable);
}
+ private void throwExceptionIfSoftwareModuleTypeDoesNotExist(final Long typeId) {
+ if (!softwareModuleTypeRepository.exists(typeId)) {
+ throw new EntityNotFoundException(SoftwareModuleType.class, typeId);
+ }
+ }
+
private static Slice convertSmPage(final Slice findAll,
final Pageable pageable) {
return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, 0);
@@ -197,14 +196,16 @@ public class JpaSoftwareManagement implements SoftwareManagement {
}
@Override
- public SoftwareModule findSoftwareModuleById(final Long id) {
- return softwareModuleRepository.findOne(id);
+ public Optional findSoftwareModuleById(final Long id) {
+ return Optional.ofNullable(softwareModuleRepository.findOne(id));
}
@Override
- public SoftwareModule findSoftwareModuleByNameAndVersion(final String name, final String version,
+ public Optional findSoftwareModuleByNameAndVersion(final String name, final String version,
final Long typeId) {
+ throwExceptionIfSoftwareModuleTypeDoesNotExist(typeId);
+
return softwareModuleRepository.findOneByNameAndVersionAndTypeId(name, version, typeId);
}
@@ -233,6 +234,12 @@ public class JpaSoftwareManagement implements SoftwareManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteSoftwareModules(final Collection ids) {
final List swModulesToDelete = softwareModuleRepository.findByIdIn(ids);
+
+ if (swModulesToDelete.size() < ids.size()) {
+ throw new EntityNotFoundException(SoftwareModule.class, ids,
+ swModulesToDelete.stream().map(SoftwareModule::getId).collect(Collectors.toList()));
+ }
+
final Set assignedModuleIds = new HashSet<>();
swModulesToDelete.forEach(swModule -> {
@@ -329,6 +336,8 @@ public class JpaSoftwareManagement implements SoftwareManagement {
}
if (null != typeId) {
+ throwExceptionIfSoftwareModuleTypeDoesNotExist(typeId);
+
spec = SoftwareModuleSpecification.equalType(typeId);
specList.add(spec);
}
@@ -393,8 +402,8 @@ public class JpaSoftwareManagement implements SoftwareManagement {
Predicate[] unassignedSpec;
if (!assignedSoftwareModules.isEmpty()) {
unassignedSpec = specificationsToPredicate(buildSpecificationList(searchText, typeId), unassignedRoot,
- unassignedQuery, cb, cb.not(unassignedRoot.get(JpaSoftwareModule_.id)
- .in(assignedSoftwareModules.stream().map(sw -> sw.getId()).collect(Collectors.toList()))));
+ unassignedQuery, cb, cb.not(unassignedRoot.get(JpaSoftwareModule_.id).in(
+ assignedSoftwareModules.stream().map(SoftwareModule::getId).collect(Collectors.toList()))));
} else {
unassignedSpec = specificationsToPredicate(buildSpecificationList(searchText, typeId), unassignedRoot,
unassignedQuery, cb);
@@ -412,13 +421,14 @@ public class JpaSoftwareManagement implements SoftwareManagement {
return new SliceImpl<>(resultList);
}
- private static List> buildSpecificationList(final String searchText,
- final Long typeId) {
+ private List> buildSpecificationList(final String searchText, final Long typeId) {
final List> specList = Lists.newArrayListWithExpectedSize(3);
if (!Strings.isNullOrEmpty(searchText)) {
specList.add(SoftwareModuleSpecification.likeNameOrVersion(searchText));
}
if (typeId != null) {
+ throwExceptionIfSoftwareModuleTypeDoesNotExist(typeId);
+
specList.add(SoftwareModuleSpecification.equalType(typeId));
}
specList.add(SoftwareModuleSpecification.isDeletedFalse());
@@ -447,6 +457,8 @@ public class JpaSoftwareManagement implements SoftwareManagement {
}
if (null != typeId) {
+ throwExceptionIfSoftwareModuleTypeDoesNotExist(typeId);
+
spec = SoftwareModuleSpecification.equalType(typeId);
specList.add(spec);
}
@@ -465,17 +477,17 @@ public class JpaSoftwareManagement implements SoftwareManagement {
}
@Override
- public SoftwareModuleType findSoftwareModuleTypeByKey(final String key) {
+ public Optional findSoftwareModuleTypeByKey(final String key) {
return softwareModuleTypeRepository.findByKey(key);
}
@Override
- public SoftwareModuleType findSoftwareModuleTypeById(final Long id) {
- return softwareModuleTypeRepository.findOne(id);
+ public Optional findSoftwareModuleTypeById(final Long smTypeId) {
+ return Optional.ofNullable(softwareModuleTypeRepository.findOne(smTypeId));
}
@Override
- public SoftwareModuleType findSoftwareModuleTypeByName(final String name) {
+ public Optional findSoftwareModuleTypeByName(final String name) {
return softwareModuleTypeRepository.findByName(name);
}
@@ -492,9 +504,8 @@ public class JpaSoftwareManagement implements SoftwareManagement {
@Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteSoftwareModuleType(final Long typeId) {
- final JpaSoftwareModuleType toDelete = Optional.ofNullable(softwareModuleTypeRepository.findOne(typeId))
- .orElseThrow(() -> new EntityNotFoundException(
- "Software Module Type with giben ID " + typeId + " does not exist."));
+ final JpaSoftwareModuleType toDelete = softwareModuleTypeRepository.findById(typeId)
+ .orElseThrow(() -> new EntityNotFoundException(SoftwareModuleType.class, typeId));
if (softwareModuleRepository.countByType(toDelete) > 0
|| distributionSetTypeRepository.countByElementsSmType(toDelete) > 0) {
@@ -507,6 +518,10 @@ public class JpaSoftwareManagement implements SoftwareManagement {
@Override
public Page findSoftwareModuleByAssignedTo(final Pageable pageable, final Long setId) {
+ if (!distributionSetRepository.exists(setId)) {
+ throw new EntityNotFoundException(DistributionSet.class, setId);
+ }
+
return softwareModuleRepository.findByAssignedToId(pageable, setId);
}
@@ -548,11 +563,12 @@ public class JpaSoftwareManagement implements SoftwareManagement {
public SoftwareModuleMetadata updateSoftwareModuleMetadata(final Long moduleId, final MetaData md) {
// check if exists otherwise throw entity not found exception
- final JpaSoftwareModuleMetadata metadata = findSoftwareModuleMetadata(
- new SwMetadataCompositeKey(moduleId, md.getKey()));
+ final JpaSoftwareModuleMetadata metadata = (JpaSoftwareModuleMetadata) findSoftwareModuleMetadata(moduleId,
+ md.getKey()).orElseThrow(
+ () -> new EntityNotFoundException(SoftwareModuleMetadata.class, moduleId, md.getKey()));
metadata.setValue(md.getValue());
- touch(moduleId);
+ touch(metadata.getSoftwareModule());
return softwareModuleMetadataRepository.save(metadata);
}
@@ -560,40 +576,63 @@ public class JpaSoftwareManagement implements SoftwareManagement {
* Method to get the latest module based on ID after the metadata changes
* for that module.
*
- * @param distributionSet
- * Distribution set
+ * @param latestModule
+ * module to touch
*/
- private JpaSoftwareModule touch(final Long moduleId) {
- final JpaSoftwareModule latestModule = softwareModuleRepository.findOne(moduleId);
-
+ private JpaSoftwareModule touch(final SoftwareModule latestModule) {
// merge base distribution set so optLockRevision gets updated and audit
// log written because
// modifying metadata is modifying the base distribution set itself for
// auditing purposes.
- final JpaSoftwareModule result = entityManager.merge(latestModule);
+ final JpaSoftwareModule result = entityManager.merge((JpaSoftwareModule) latestModule);
result.setLastModifiedAt(0L);
return result;
}
+ /**
+ * Method to get the latest module based on ID after the metadata changes
+ * for that module.
+ *
+ * @param moduleId
+ * of the module to touch
+ */
+ private JpaSoftwareModule touch(final Long moduleId) {
+ return touch(findSoftwareModuleById(moduleId)
+ .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, moduleId)));
+ }
+
@Override
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
@Modifying
public void deleteSoftwareModuleMetadata(final Long moduleId, final String key) {
- touch(moduleId);
- softwareModuleMetadataRepository.delete(new SwMetadataCompositeKey(moduleId, key));
+ final JpaSoftwareModuleMetadata metadata = (JpaSoftwareModuleMetadata) findSoftwareModuleMetadata(moduleId, key)
+ .orElseThrow(() -> new EntityNotFoundException(SoftwareModuleMetadata.class, moduleId, key));
+
+ touch(metadata.getSoftwareModule());
+ softwareModuleMetadataRepository.delete(metadata.getId());
}
@Override
public Page findSoftwareModuleMetadataBySoftwareModuleId(final Long swId,
final Pageable pageable) {
+ throwExceptionIfSoftwareModuleDoesNotExist(swId);
+
return softwareModuleMetadataRepository.findBySoftwareModuleId(swId, pageable);
}
+ private void throwExceptionIfSoftwareModuleDoesNotExist(final Long swId) {
+ if (!softwareModuleRepository.exists(swId)) {
+ throw new EntityNotFoundException(SoftwareModule.class, swId);
+ }
+ }
+
@Override
public Page findSoftwareModuleMetadataBySoftwareModuleId(final Long softwareModuleId,
final String rsqlParam, final Pageable pageable) {
+ throwExceptionIfSoftwareModuleDoesNotExist(softwareModuleId);
+
final Specification spec = RSQLUtility.parse(rsqlParam,
SoftwareModuleMetadataFields.class, virtualPropertyReplacer);
return convertSmMdPage(
@@ -609,6 +648,8 @@ public class JpaSoftwareManagement implements SoftwareManagement {
@Override
public List findSoftwareModuleMetadataBySoftwareModuleId(final Long softwareModuleId) {
+ throwExceptionIfSoftwareModuleDoesNotExist(softwareModuleId);
+
return Collections.unmodifiableList(softwareModuleMetadataRepository
.findAll((Specification) (root, query, cb) -> cb
.and(cb.equal(root.get(JpaSoftwareModuleMetadata_.softwareModule).get(JpaSoftwareModule_.id),
@@ -616,16 +657,8 @@ public class JpaSoftwareManagement implements SoftwareManagement {
}
@Override
- public SoftwareModuleMetadata findSoftwareModuleMetadata(final Long moduleId, final String key) {
- return findSoftwareModuleMetadata(new SwMetadataCompositeKey(moduleId, key));
- }
-
- private JpaSoftwareModuleMetadata findSoftwareModuleMetadata(final SwMetadataCompositeKey id) {
- final JpaSoftwareModuleMetadata findOne = softwareModuleMetadataRepository.findOne(id);
- if (findOne == null) {
- throw new EntityNotFoundException("Metadata with key '" + id.getKey() + "' does not exist");
- }
- return findOne;
+ public Optional findSoftwareModuleMetadata(final Long moduleId, final String key) {
+ return Optional.ofNullable(softwareModuleMetadataRepository.findOne(new SwMetadataCompositeKey(moduleId, key)));
}
private void checkAndThrowAlreadyExistsIfSoftwareModuleMetadataExists(final SwMetadataCompositeKey metadataId) {
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTagManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTagManagement.java
index 8f7651804..f2b5c3b43 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTagManagement.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTagManagement.java
@@ -62,7 +62,7 @@ public class JpaTagManagement implements TagManagement {
private VirtualPropertyReplacer virtualPropertyReplacer;
@Override
- public TargetTag findTargetTag(final String name) {
+ public Optional findTargetTag(final String name) {
return targetTagRepository.findByNameEquals(name);
}
@@ -73,7 +73,7 @@ public class JpaTagManagement implements TagManagement {
final JpaTargetTag targetTag = create.buildTargetTag();
- if (findTargetTag(targetTag.getName()) != null) {
+ if (findTargetTag(targetTag.getName()).isPresent()) {
throw new EntityAlreadyExistsException();
}
@@ -95,7 +95,8 @@ public class JpaTagManagement implements TagManagement {
@Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteTargetTag(final String targetTagName) {
- final JpaTargetTag tag = targetTagRepository.findByNameEquals(targetTagName);
+ final TargetTag tag = targetTagRepository.findByNameEquals(targetTagName)
+ .orElseThrow(() -> new EntityNotFoundException(TargetTag.class, targetTagName));
targetRepository.findByTag(tag.getId()).forEach(set -> {
set.removeTag(tag);
@@ -107,11 +108,6 @@ public class JpaTagManagement implements TagManagement {
}
- @Override
- public List findAllTargetTags() {
- return Collections.unmodifiableList(targetTagRepository.findAll());
- }
-
@Override
public Page findAllTargetTags(final String rsqlParam, final Pageable pageable) {
@@ -139,8 +135,8 @@ public class JpaTagManagement implements TagManagement {
public TargetTag updateTargetTag(final TagUpdate u) {
final GenericTagUpdate update = (GenericTagUpdate) u;
- final JpaTargetTag tag = Optional.ofNullable(targetTagRepository.findOne(update.getId()))
- .orElseThrow(() -> new EntityNotFoundException("Target tag with ID " + update.getId() + " not found"));
+ final JpaTargetTag tag = targetTagRepository.findById(update.getId())
+ .orElseThrow(() -> new EntityNotFoundException(TargetTag.class, update.getId()));
update.getName().ifPresent(tag::setName);
update.getDescription().ifPresent(tag::setDescription);
@@ -155,9 +151,8 @@ public class JpaTagManagement implements TagManagement {
public DistributionSetTag updateDistributionSetTag(final TagUpdate u) {
final GenericTagUpdate update = (GenericTagUpdate) u;
- final JpaDistributionSetTag tag = Optional.ofNullable(distributionSetTagRepository.findOne(update.getId()))
- .orElseThrow(() -> new EntityNotFoundException(
- "Distribution set tag with ID " + update.getId() + " not found"));
+ final JpaDistributionSetTag tag = distributionSetTagRepository.findById(update.getId())
+ .orElseThrow(() -> new EntityNotFoundException(DistributionSetTag.class, update.getId()));
update.getName().ifPresent(tag::setName);
update.getDescription().ifPresent(tag::setDescription);
@@ -167,7 +162,7 @@ public class JpaTagManagement implements TagManagement {
}
@Override
- public DistributionSetTag findDistributionSetTag(final String name) {
+ public Optional findDistributionSetTag(final String name) {
return distributionSetTagRepository.findByNameEquals(name);
}
@@ -179,7 +174,7 @@ public class JpaTagManagement implements TagManagement {
final JpaDistributionSetTag distributionSetTag = create.buildDistributionSetTag();
- if (distributionSetTagRepository.findByNameEquals(distributionSetTag.getName()) != null) {
+ if (distributionSetTagRepository.findByNameEquals(distributionSetTag.getName()).isPresent()) {
throw new EntityAlreadyExistsException();
}
@@ -203,7 +198,8 @@ public class JpaTagManagement implements TagManagement {
@Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteDistributionSetTag(final String tagName) {
- final JpaDistributionSetTag tag = distributionSetTagRepository.findByNameEquals(tagName);
+ final DistributionSetTag tag = distributionSetTagRepository.findByNameEquals(tagName)
+ .orElseThrow(() -> new EntityNotFoundException(DistributionSetTag.class, tagName));
distributionSetRepository.findByTag(tag).forEach(set -> {
set.removeTag(tag);
@@ -219,13 +215,13 @@ public class JpaTagManagement implements TagManagement {
}
@Override
- public TargetTag findTargetTagById(final Long id) {
- return targetTagRepository.findOne(id);
+ public Optional findTargetTagById(final Long id) {
+ return Optional.ofNullable(targetTagRepository.findOne(id));
}
@Override
- public DistributionSetTag findDistributionSetTagById(final Long id) {
- return distributionSetTagRepository.findOne(id);
+ public Optional findDistributionSetTagById(final Long id) {
+ return Optional.ofNullable(distributionSetTagRepository.findOne(id));
}
@Override
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTargetFilterQueryManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTargetFilterQueryManagement.java
index a79685372..c81847855 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTargetFilterQueryManagement.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTargetFilterQueryManagement.java
@@ -76,7 +76,7 @@ public class JpaTargetFilterQueryManagement implements TargetFilterQueryManageme
final JpaTargetFilterQuery query = create.build();
- if (targetFilterQueryRepository.findByName(query.getName()) != null) {
+ if (targetFilterQueryRepository.findByName(query.getName()).isPresent()) {
throw new EntityAlreadyExistsException(query.getName());
}
return targetFilterQueryRepository.save(query);
@@ -86,6 +86,9 @@ public class JpaTargetFilterQueryManagement implements TargetFilterQueryManageme
@Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteTargetFilterQuery(final Long targetFilterQueryId) {
+ findTargetFilterQueryById(targetFilterQueryId)
+ .orElseThrow(() -> new EntityNotFoundException(TargetFilterQuery.class, targetFilterQueryId));
+
targetFilterQueryRepository.delete(targetFilterQueryId);
}
@@ -165,13 +168,13 @@ public class JpaTargetFilterQueryManagement implements TargetFilterQueryManageme
}
@Override
- public TargetFilterQuery findTargetFilterQueryByName(final String targetFilterQueryName) {
+ public Optional findTargetFilterQueryByName(final String targetFilterQueryName) {
return targetFilterQueryRepository.findByName(targetFilterQueryName);
}
@Override
- public TargetFilterQuery findTargetFilterQueryById(final Long targetFilterQueryId) {
- return targetFilterQueryRepository.findOne(targetFilterQueryId);
+ public Optional findTargetFilterQueryById(final Long targetFilterQueryId) {
+ return Optional.ofNullable(targetFilterQueryRepository.findOne(targetFilterQueryId));
}
@Override
@@ -201,18 +204,13 @@ public class JpaTargetFilterQueryManagement implements TargetFilterQueryManageme
}
private JpaDistributionSet findDistributionSetAndThrowExceptionIfNotFound(final Long setId) {
- final JpaDistributionSet set = (JpaDistributionSet) distributionSetManagement
- .findDistributionSetByIdWithDetails(setId);
-
- if (set == null) {
- throw new EntityNotFoundException("Distribution set cannot be updated as it does not exixt" + setId);
- }
- return set;
+ return (JpaDistributionSet) distributionSetManagement.findDistributionSetByIdWithDetails(setId)
+ .orElseThrow(() -> new EntityNotFoundException(DistributionSet.class, setId));
}
private JpaTargetFilterQuery findTargetFilterQueryOrThrowExceptionIfNotFound(final Long queryId) {
- return Optional.ofNullable(targetFilterQueryRepository.findOne(queryId)).orElseThrow(
- () -> new EntityNotFoundException("TargetFilterQuery with given ID " + queryId + " not found!"));
+ return targetFilterQueryRepository.findById(queryId)
+ .orElseThrow(() -> new EntityNotFoundException(TargetFilterQuery.class, queryId));
}
@Override
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTargetManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTargetManagement.java
index c9111ad8e..fa3db9da3 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTargetManagement.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaTargetManagement.java
@@ -48,6 +48,8 @@ import org.eclipse.hawkbit.repository.jpa.model.JpaTarget_;
import org.eclipse.hawkbit.repository.jpa.rsql.RSQLUtility;
import org.eclipse.hawkbit.repository.jpa.specifications.SpecificationsBuilder;
import org.eclipse.hawkbit.repository.jpa.specifications.TargetSpecifications;
+import org.eclipse.hawkbit.repository.model.DistributionSet;
+import org.eclipse.hawkbit.repository.model.RolloutGroup;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetFilterQuery;
import org.eclipse.hawkbit.repository.model.TargetTag;
@@ -85,6 +87,12 @@ public class JpaTargetManagement implements TargetManagement {
@Autowired
private TargetRepository targetRepository;
+ @Autowired
+ private RolloutGroupRepository rolloutGroupRepository;
+
+ @Autowired
+ private DistributionSetRepository distributionSetRepository;
+
@Autowired
private TargetFilterQueryRepository targetFilterQueryRepository;
@@ -110,25 +118,29 @@ public class JpaTargetManagement implements TargetManagement {
private VirtualPropertyReplacer virtualPropertyReplacer;
@Override
- public Target findTargetByControllerID(final String controllerId) {
+ public Optional findTargetByControllerID(final String controllerId) {
return targetRepository.findByControllerId(controllerId);
}
@Override
- public Target findTargetByControllerIDWithDetails(final String controllerId) {
- final Target result = targetRepository.findByControllerId(controllerId);
+ public Optional findTargetByControllerIDWithDetails(final String controllerId) {
+ final Optional result = targetRepository.findByControllerId(controllerId);
// load lazy relations
- if (result != null) {
- result.getTargetInfo().getControllerAttributes().size();
- if (result.getTargetInfo() != null && result.getTargetInfo().getInstalledDistributionSet() != null) {
- result.getTargetInfo().getInstalledDistributionSet().getName();
- result.getTargetInfo().getInstalledDistributionSet().getModules().size();
- }
- if (result.getAssignedDistributionSet() != null) {
- result.getAssignedDistributionSet().getName();
- result.getAssignedDistributionSet().getModules().size();
- }
+ if (!result.isPresent()) {
+ return result;
}
+
+ result.get().getTargetInfo().getControllerAttributes().size();
+ if (result.get().getTargetInfo() != null
+ && result.get().getTargetInfo().getInstalledDistributionSet() != null) {
+ result.get().getTargetInfo().getInstalledDistributionSet().getName();
+ result.get().getTargetInfo().getInstalledDistributionSet().getModules().size();
+ }
+ if (result.get().getAssignedDistributionSet() != null) {
+ result.get().getAssignedDistributionSet().getName();
+ result.get().getAssignedDistributionSet().getModules().size();
+ }
+
return result;
}
@@ -159,10 +171,8 @@ public class JpaTargetManagement implements TargetManagement {
@Override
public Slice findTargetsByTargetFilterQuery(final Long targetFilterQueryId, final Pageable pageable) {
- final TargetFilterQuery targetFilterQuery = Optional
- .ofNullable(targetFilterQueryRepository.findOne(targetFilterQueryId))
- .orElseThrow(() -> new EntityNotFoundException(
- "TargetFilterQuery with given ID" + targetFilterQueryId + " not found"));
+ final TargetFilterQuery targetFilterQuery = targetFilterQueryRepository.findById(targetFilterQueryId)
+ .orElseThrow(() -> new EntityNotFoundException(TargetFilterQuery.class, targetFilterQueryId));
return findTargetsBySpec(
RSQLUtility.parse(targetFilterQuery.getQuery(), TargetFields.class, virtualPropertyReplacer), pageable);
@@ -192,9 +202,8 @@ public class JpaTargetManagement implements TargetManagement {
public Target updateTarget(final TargetUpdate u) {
final JpaTargetUpdate update = (JpaTargetUpdate) u;
- final JpaTarget target = Optional.ofNullable(targetRepository.findByControllerId(update.getControllerId()))
- .orElseThrow(() -> new EntityNotFoundException(
- "Target with ID " + update.getControllerId() + " not found."));
+ final JpaTarget target = (JpaTarget) targetRepository.findByControllerId(update.getControllerId())
+ .orElseThrow(() -> new EntityNotFoundException(Target.class, update.getControllerId()));
target.setNew(false);
@@ -210,6 +219,13 @@ public class JpaTargetManagement implements TargetManagement {
@Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteTargets(final Collection targetIDs) {
+ final List targets = targetRepository.findAll(targetIDs);
+
+ if (targets.size() < targetIDs.size()) {
+ throw new EntityNotFoundException(Target.class, targetIDs,
+ targets.stream().map(Target::getId).collect(Collectors.toList()));
+ }
+
targetRepository.deleteByIdIn(targetIDs);
targetIDs.forEach(targetId -> eventPublisher.publishEvent(new TargetDeletedEvent(tenantAware.getCurrentTenant(),
@@ -220,22 +236,23 @@ public class JpaTargetManagement implements TargetManagement {
@Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void deleteTarget(final String controllerID) {
- final Long targetId = Optional.ofNullable(targetRepository.findByControllerId(controllerID))
- .orElseThrow(
- () -> new EntityNotFoundException("Target with given ID " + controllerID + " does not exist."))
- .getId();
+ final Target target = targetRepository.findByControllerId(controllerID)
+ .orElseThrow(() -> new EntityNotFoundException(Target.class, controllerID));
- targetRepository.delete(targetId);
+ targetRepository.delete(target.getId());
}
@Override
public Page findTargetByAssignedDistributionSet(final Long distributionSetID, final Pageable pageReq) {
+ throwEntityNotFoundIfDsDoesNotExist(distributionSetID);
+
return targetRepository.findByAssignedDistributionSetId(pageReq, distributionSetID);
}
@Override
public Page findTargetByAssignedDistributionSet(final Long distributionSetID, final String rsqlParam,
final Pageable pageReq) {
+ throwEntityNotFoundIfDsDoesNotExist(distributionSetID);
final Specification spec = RSQLUtility.parse(rsqlParam, TargetFields.class, virtualPropertyReplacer);
@@ -248,6 +265,12 @@ public class JpaTargetManagement implements TargetManagement {
pageReq);
}
+ private void throwEntityNotFoundIfDsDoesNotExist(final Long distributionSetID) {
+ if (!distributionSetRepository.exists(distributionSetID)) {
+ throw new EntityNotFoundException(DistributionSet.class, distributionSetID);
+ }
+ }
+
private static Page convertPage(final Page findAll, final Pageable pageable) {
return new PageImpl<>(Collections.unmodifiableList(findAll.getContent()), pageable, findAll.getTotalElements());
}
@@ -258,12 +281,14 @@ public class JpaTargetManagement implements TargetManagement {
@Override
public Page findTargetByInstalledDistributionSet(final Long distributionSetID, final Pageable pageReq) {
+ throwEntityNotFoundIfDsDoesNotExist(distributionSetID);
return targetRepository.findByTargetInfoInstalledDistributionSetId(pageReq, distributionSetID);
}
@Override
public Page findTargetByInstalledDistributionSet(final Long distributionSetId, final String rsqlParam,
final Pageable pageable) {
+ throwEntityNotFoundIfDsDoesNotExist(distributionSetId);
final Specification spec = RSQLUtility.parse(rsqlParam, TargetFields.class, virtualPropertyReplacer);
@@ -303,7 +328,7 @@ public class JpaTargetManagement implements TargetManagement {
return countByCriteriaAPI(specList);
}
- private static List> buildSpecificationList(final FilterParams filterParams,
+ private List> buildSpecificationList(final FilterParams filterParams,
final boolean fetch) {
final List> specList = new ArrayList<>();
if (filterParams.getFilterByStatus() != null && !filterParams.getFilterByStatus().isEmpty()) {
@@ -313,6 +338,8 @@ public class JpaTargetManagement implements TargetManagement {
specList.add(TargetSpecifications.isOverdue(TimestampCalculator.calculateOverdueTimestamp()));
}
if (filterParams.getFilterByDistributionId() != null) {
+ throwEntityNotFoundIfDsDoesNotExist(filterParams.getFilterByDistributionId());
+
specList.add(TargetSpecifications
.hasInstalledOrAssignedDistributionSet(filterParams.getFilterByDistributionId()));
}
@@ -352,7 +379,8 @@ public class JpaTargetManagement implements TargetManagement {
@Modifying
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public TargetTagAssignmentResult toggleTagAssignment(final Collection targetIds, final String tagName) {
- final TargetTag tag = targetTagRepository.findByNameEquals(tagName);
+ final TargetTag tag = targetTagRepository.findByNameEquals(tagName)
+ .orElseThrow(() -> new EntityNotFoundException(TargetTag.class, tagName));
final List alreadyAssignedTargets = targetRepository.findByTagNameAndControllerIdIn(tagName,
targetIds);
final List allTargets = targetRepository
@@ -388,8 +416,8 @@ public class JpaTargetManagement implements TargetManagement {
final List allTargets = targetRepository
.findAll(TargetSpecifications.byControllerIdWithStatusAndTagsInJoin(controllerIds));
- final JpaTargetTag tag = Optional.ofNullable(targetTagRepository.findOne(tagId))
- .orElseThrow(() -> new EntityNotFoundException("Tag with given ID " + tagId + "does not exist"));
+ final JpaTargetTag tag = targetTagRepository.findById(tagId)
+ .orElseThrow(() -> new EntityNotFoundException(TargetTag.class, tagId));
allTargets.forEach(target -> target.addTag(tag));
return Collections
@@ -411,8 +439,8 @@ public class JpaTargetManagement implements TargetManagement {
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public List unAssignAllTargetsByTag(final Long targetTagId) {
- final TargetTag tag = Optional.ofNullable(targetTagRepository.findOne(targetTagId)).orElseThrow(
- () -> new EntityNotFoundException("TargetTag with given ID " + targetTagId + " does not exist."));
+ final TargetTag tag = targetTagRepository.findById(targetTagId)
+ .orElseThrow(() -> new EntityNotFoundException(TargetTag.class, targetTagId));
if (tag.getAssignedToTargets().isEmpty()) {
return Collections.emptyList();
@@ -428,8 +456,8 @@ public class JpaTargetManagement implements TargetManagement {
final List allTargets = Collections.unmodifiableList(targetRepository
.findAll(TargetSpecifications.byControllerIdWithStatusAndTagsInJoin(Arrays.asList(controllerID))));
- final TargetTag tag = Optional.ofNullable(targetTagRepository.findOne(targetTagId)).orElseThrow(
- () -> new EntityNotFoundException("TargetTag with given ID " + targetTagId + " does not exist."));
+ final TargetTag tag = targetTagRepository.findById(targetTagId)
+ .orElseThrow(() -> new EntityNotFoundException(TargetTag.class, targetTagId));
final List unAssignTag = unAssignTag(allTargets, tag);
return unAssignTag.isEmpty() ? null : unAssignTag.get(0);
@@ -438,7 +466,6 @@ public class JpaTargetManagement implements TargetManagement {
@Override
public Slice findTargetsAllOrderByLinkedDistributionSet(final Pageable pageable,
final Long orderByDistributionId, final FilterParams filterParams) {
-
final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
final CriteriaQuery query = cb.createQuery(JpaTarget.class);
final Root targetRoot = query.from(JpaTarget.class);
@@ -496,17 +523,22 @@ public class JpaTargetManagement implements TargetManagement {
@Override
public Long countTargetByAssignedDistributionSet(final Long distId) {
+ throwEntityNotFoundIfDsDoesNotExist(distId);
+
return targetRepository.countByAssignedDistributionSetId(distId);
}
@Override
public Long countTargetByInstalledDistributionSet(final Long distId) {
+ throwEntityNotFoundIfDsDoesNotExist(distId);
+
return targetRepository.countByTargetInfoInstalledDistributionSetId(distId);
}
@Override
- public Page findAllTargetsByTargetFilterQueryAndNonDS(@NotNull final Pageable pageRequest,
- final Long distributionSetId, @NotNull final String targetFilterQuery) {
+ public Page findAllTargetsByTargetFilterQueryAndNonDS(final Pageable pageRequest,
+ final Long distributionSetId, final String targetFilterQuery) {
+ throwEntityNotFoundIfDsDoesNotExist(distributionSetId);
final Specification spec = RSQLUtility.parse(targetFilterQuery, TargetFields.class,
virtualPropertyReplacer);
@@ -534,6 +566,10 @@ public class JpaTargetManagement implements TargetManagement {
@Override
public Page findAllTargetsInRolloutGroupWithoutAction(@NotNull final Pageable pageRequest,
@NotNull final Long group) {
+ if (!rolloutGroupRepository.exists(group)) {
+ throw new EntityNotFoundException(RolloutGroup.class, group);
+ }
+
return findTargetsBySpec(
(root, cq, cb) -> TargetSpecifications.hasNoActionInRolloutGroup(group).toPredicate(root, cq, cb),
pageRequest);
@@ -552,6 +588,8 @@ public class JpaTargetManagement implements TargetManagement {
@Override
public Long countTargetsByTargetFilterQueryAndNonDS(final Long distributionSetId, final String targetFilterQuery) {
+ throwEntityNotFoundIfDsDoesNotExist(distributionSetId);
+
final Specification spec = RSQLUtility.parse(targetFilterQuery, TargetFields.class,
virtualPropertyReplacer);
final List> specList = new ArrayList<>(2);
@@ -569,7 +607,7 @@ public class JpaTargetManagement implements TargetManagement {
final JpaTarget target = create.build();
- if (targetRepository.findByControllerId(target.getControllerId()) != null) {
+ if (targetRepository.findByControllerId(target.getControllerId()).isPresent()) {
throw new EntityAlreadyExistsException();
}
@@ -592,16 +630,18 @@ public class JpaTargetManagement implements TargetManagement {
@Override
public List findTargetsByTag(final String tagName) {
- final JpaTargetTag tag = targetTagRepository.findByNameEquals(tagName);
- return Collections.unmodifiableList(targetRepository.findByTag(tag.getId()));
+ final Optional tag = targetTagRepository.findByNameEquals(tagName);
+ if (!tag.isPresent()) {
+ return Collections.emptyList();
+ }
+
+ return Collections.unmodifiableList(targetRepository.findByTag(tag.get().getId()));
}
@Override
public Long countTargetByTargetFilterQuery(final Long targetFilterQueryId) {
- final TargetFilterQuery targetFilterQuery = Optional
- .ofNullable(targetFilterQueryRepository.findOne(targetFilterQueryId))
- .orElseThrow(() -> new EntityNotFoundException(
- "TargetFilterQuery with given ID" + targetFilterQueryId + " not found"));
+ final TargetFilterQuery targetFilterQuery = targetFilterQueryRepository.findById(targetFilterQueryId)
+ .orElseThrow(() -> new EntityNotFoundException(TargetFilterQuery.class, targetFilterQueryId));
final Specification specs = RSQLUtility.parse(targetFilterQuery.getQuery(), TargetFields.class,
virtualPropertyReplacer);
@@ -619,8 +659,8 @@ public class JpaTargetManagement implements TargetManagement {
}
@Override
- public Target findTargetById(final Long id) {
- return targetRepository.findOne(id);
+ public Optional findTargetById(final Long id) {
+ return Optional.ofNullable(targetRepository.findOne(id));
}
@Override
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/LocalArtifactRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/LocalArtifactRepository.java
index 78dd31142..3d84492ce 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/LocalArtifactRepository.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/LocalArtifactRepository.java
@@ -61,7 +61,7 @@ public interface LocalArtifactRepository extends BaseEntityRepository findFirstBySha1Hash(String sha1Hash);
/**
* Searches for a {@link Artifact} based user provided filename at upload.
@@ -70,7 +70,7 @@ public interface LocalArtifactRepository extends BaseEntityRepository findByFilename(String filename);
+ Optional findFirstByFilename(String filename);
/**
* Searches for local artifact for a base software module.
@@ -94,6 +94,6 @@ public interface LocalArtifactRepository extends BaseEntityRepository findByFilenameAndSoftwareModuleId(final String filename, final Long softwareModuleId);
+ Optional findFirstByFilenameAndSoftwareModuleId(final String filename, final Long softwareModuleId);
}
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutRepository.java
index de7a62897..753745b4f 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutRepository.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/RolloutRepository.java
@@ -9,6 +9,7 @@
package org.eclipse.hawkbit.repository.jpa;
import java.util.List;
+import java.util.Optional;
import org.eclipse.hawkbit.repository.jpa.model.JpaRollout;
import org.eclipse.hawkbit.repository.model.Rollout;
@@ -67,5 +68,5 @@ public interface RolloutRepository
* the rollout name
* @return {@link Rollout} for specific name
*/
- JpaRollout findByName(String name);
+ Optional findByName(String name);
}
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleRepository.java
index ebc2acfc2..70e45b2a1 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleRepository.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleRepository.java
@@ -9,6 +9,7 @@
package org.eclipse.hawkbit.repository.jpa;
import java.util.List;
+import java.util.Optional;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule;
@@ -55,7 +56,7 @@ public interface SoftwareModuleRepository
* @return the found {@link SoftwareModule} with the given name AND version
* AND type
*/
- JpaSoftwareModule findOneByNameAndVersionAndTypeId(String name, String version, Long typeId);
+ Optional findOneByNameAndVersionAndTypeId(String name, String version, Long typeId);
/**
* deletes the {@link SoftwareModule}s with the given IDs.
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleTypeRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleTypeRepository.java
index 1019f2d8b..9d2a3ad94 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleTypeRepository.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/SoftwareModuleTypeRepository.java
@@ -9,6 +9,7 @@
package org.eclipse.hawkbit.repository.jpa;
import java.util.List;
+import java.util.Optional;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
@@ -52,7 +53,7 @@ public interface SoftwareModuleTypeRepository
* @return all {@link SoftwareModuleType}s in the repository with given
* {@link SoftwareModuleType#getKey()}
*/
- JpaSoftwareModuleType findByKey(String key);
+ Optional findByKey(String key);
/**
*
@@ -61,7 +62,7 @@ public interface SoftwareModuleTypeRepository
* @return all {@link SoftwareModuleType}s in the repository with given
* {@link SoftwareModuleType#getName()}
*/
- JpaSoftwareModuleType findByName(String name);
+ Optional findByName(String name);
/**
* retrieves all software module types with a given
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryRepository.java
index 7afa16156..ec13a75c0 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryRepository.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryRepository.java
@@ -8,6 +8,8 @@
*/
package org.eclipse.hawkbit.repository.jpa;
+import java.util.Optional;
+
import org.eclipse.hawkbit.repository.jpa.model.JpaTargetFilterQuery;
import org.eclipse.hawkbit.repository.model.TargetFilterQuery;
import org.springframework.data.domain.Page;
@@ -32,7 +34,7 @@ public interface TargetFilterQueryRepository
* @param name
* @return custom target filter
*/
- TargetFilterQuery findByName(final String name);
+ Optional findByName(final String name);
/**
* Find list of all custom target filters.
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetRepository.java
index 7c8f85124..15bef6fe4 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetRepository.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetRepository.java
@@ -10,6 +10,7 @@ package org.eclipse.hawkbit.repository.jpa;
import java.util.Collection;
import java.util.List;
+import java.util.Optional;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget;
@@ -44,7 +45,7 @@ public interface TargetRepository extends BaseEntityRepository,
* @return found {@link Target} or null if not found.
*/
@EntityGraph(value = "Target.detail", type = EntityGraphType.LOAD)
- JpaTarget findByControllerId(String controllerID);
+ Optional findByControllerId(String controllerID);
/**
* Deletes the {@link Target}s with the given target IDs.
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetTagRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetTagRepository.java
index 471dd67db..9c232c756 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetTagRepository.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/TargetTagRepository.java
@@ -9,6 +9,7 @@
package org.eclipse.hawkbit.repository.jpa;
import java.util.List;
+import java.util.Optional;
import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag;
import org.eclipse.hawkbit.repository.model.TargetTag;
@@ -43,7 +44,7 @@ public interface TargetTagRepository
* to filter on
* @return the {@link TargetTag} if found, otherwise null
*/
- JpaTargetTag findByNameEquals(String tagName);
+ Optional findByNameEquals(String tagName);
/**
* Returns all instances of the type.
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaDistributionSetCreate.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaDistributionSetCreate.java
index e5fb559c8..93bd9f0b9 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaDistributionSetCreate.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaDistributionSetCreate.java
@@ -47,14 +47,8 @@ public class JpaDistributionSetCreate extends AbstractDistributionSetUpdateCreat
}
private DistributionSetType findDistributionSetTypeWithExceptionIfNotFound(final String distributionSetTypekey) {
-
- final DistributionSetType module = distributionSetManagement
- .findDistributionSetTypeByKey(distributionSetTypekey);
- if (module == null) {
- throw new EntityNotFoundException(
- "DistributionSetType with key {" + distributionSetTypekey + "} does not exist");
- }
- return module;
+ return distributionSetManagement.findDistributionSetTypeByKey(distributionSetTypekey)
+ .orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, distributionSetTypekey));
}
private Collection findSoftwareModuleWithExceptionIfNotFound(
@@ -65,8 +59,7 @@ public class JpaDistributionSetCreate extends AbstractDistributionSetUpdateCreat
final Collection module = softwareManagement.findSoftwareModulesById(softwareModuleId);
if (module.size() < softwareModuleId.size()) {
- throw new EntityNotFoundException(
- "Some SoftwareModules out of the range {" + softwareModuleId + "} due not exist");
+ throw new EntityNotFoundException(SoftwareModule.class, softwareModuleId);
}
return module;
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaDistributionSetTypeCreate.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaDistributionSetTypeCreate.java
index f7b4ff6b3..1003b3cc8 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaDistributionSetTypeCreate.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaDistributionSetTypeCreate.java
@@ -51,8 +51,7 @@ public class JpaDistributionSetTypeCreate extends AbstractDistributionSetTypeUpd
final Collection module = softwareManagement
.findSoftwareModuleTypesById(softwareModuleTypeId);
if (module.size() < softwareModuleTypeId.size()) {
- throw new EntityNotFoundException(
- "SoftwareModules types out of the range {" + softwareModuleTypeId + "} due not exist");
+ throw new EntityNotFoundException(SoftwareModuleType.class, softwareModuleTypeId);
}
return module;
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaRolloutCreate.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaRolloutCreate.java
index 9bdf65711..9974ae7e2 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaRolloutCreate.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaRolloutCreate.java
@@ -44,11 +44,7 @@ public class JpaRolloutCreate extends AbstractRolloutUpdateCreate
}
private DistributionSet findDistributionSetAndThrowExceptionIfNotFound(final Long setId) {
- final DistributionSet set = distributionSetManagement.findDistributionSetById(setId);
-
- if (set == null) {
- throw new EntityNotFoundException("Distribution set cannot be set as it does not exixt" + setId);
- }
- return set;
+ return distributionSetManagement.findDistributionSetById(setId)
+ .orElseThrow(() -> new EntityNotFoundException(DistributionSet.class, setId));
}
}
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaSoftwareModuleCreate.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaSoftwareModuleCreate.java
index eb03cf9fa..274e2a48d 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaSoftwareModuleCreate.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaSoftwareModuleCreate.java
@@ -39,12 +39,7 @@ public class JpaSoftwareModuleCreate extends AbstractSoftwareModuleUpdateCreate<
throw new ConstraintViolationException("type cannot be null");
}
- final SoftwareModuleType smType = softwareManagement.findSoftwareModuleTypeByKey(type.trim());
-
- if (smType == null) {
- throw new EntityNotFoundException(type.trim());
- }
-
- return smType;
+ return softwareManagement.findSoftwareModuleTypeByKey(type.trim())
+ .orElseThrow(() -> new EntityNotFoundException(SoftwareModuleType.class, type.trim()));
}
}
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTargetFilterQueryCreate.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTargetFilterQueryCreate.java
index 21d57a70d..c6d77e59c 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTargetFilterQueryCreate.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/builder/JpaTargetFilterQueryCreate.java
@@ -36,12 +36,8 @@ public class JpaTargetFilterQueryCreate extends AbstractTargetFilterQueryUpdateC
}
private DistributionSet findDistributionSetAndThrowExceptionIfNotFound(final Long setId) {
- final DistributionSet set = distributionSetManagement.findDistributionSetById(setId);
-
- if (set == null) {
- throw new EntityNotFoundException("Distribution set cannot be set as it does not exixt" + setId);
- }
- return set;
+ return distributionSetManagement.findDistributionSetById(setId)
+ .orElseThrow(() -> new EntityNotFoundException(DistributionSet.class, setId));
}
}
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaAction.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaAction.java
index 8bb30b511..3d63ae719 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaAction.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaAction.java
@@ -60,6 +60,7 @@ public class JpaAction extends AbstractJpaTenantAwareBaseEntity implements Actio
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "distribution_set", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_action_ds"))
+ @NotNull
private JpaDistributionSet distributionSet;
@ManyToOne(fetch = FetchType.LAZY)
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSet.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSet.java
index 54ff85c83..ab161a9b2 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSet.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSet.java
@@ -268,7 +268,7 @@ public class JpaDistributionSet extends AbstractJpaNamedVersionedEntity implemen
checkTypeCompatability(softwareModule);
final Optional found = modules.stream()
- .filter(module -> module.getId().equals(softwareModule.getId())).findFirst();
+ .filter(module -> module.getId().equals(softwareModule.getId())).findAny();
if (found.isPresent()) {
return false;
@@ -279,7 +279,7 @@ public class JpaDistributionSet extends AbstractJpaNamedVersionedEntity implemen
if (allready >= softwareModule.getType().getMaxAssignments()) {
modules.stream().filter(module -> module.getType().getKey().equals(softwareModule.getType().getKey()))
- .findFirst().map(modules::remove);
+ .findAny().map(modules::remove);
}
if (modules.add(softwareModule)) {
@@ -308,7 +308,7 @@ public class JpaDistributionSet extends AbstractJpaNamedVersionedEntity implemen
}
final Optional found = modules.stream()
- .filter(module -> module.getId().equals(softwareModule.getId())).findFirst();
+ .filter(module -> module.getId().equals(softwareModule.getId())).findAny();
if (found.isPresent()) {
modules.remove(found.get());
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetType.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetType.java
index 5d55e5aa6..05d39b056 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetType.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/model/JpaDistributionSetType.java
@@ -170,7 +170,7 @@ public class JpaDistributionSetType extends AbstractJpaNamedEntity implements Di
// check if this was in the list before before
final Optional existing = elements.stream()
- .filter(element -> element.getSmType().getKey().equals(smType.getKey())).findFirst();
+ .filter(element -> element.getSmType().getKey().equals(smType.getKey())).findAny();
if (existing.isPresent()) {
existing.get().setMandatory(mandatory);
@@ -187,7 +187,7 @@ public class JpaDistributionSetType extends AbstractJpaNamedEntity implements Di
}
// we search by id (standard equals compares also revison)
- elements.stream().filter(element -> element.getSmType().getId().equals(smTypeId)).findFirst()
+ elements.stream().filter(element -> element.getSmType().getId().equals(smTypeId)).findAny()
.ifPresent(elements::remove);
return this;
diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLUtility.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLUtility.java
index 66412b7fd..a999b9c2c 100644
--- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLUtility.java
+++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLUtility.java
@@ -235,7 +235,7 @@ public final class RSQLUtility {
private Optional> findCurrentJoinOfType(final Class> type) {
return getCurrentJoins().stream()
- .filter(j -> type.equals(j.getJavaType())).findFirst();
+ .filter(j -> type.equals(j.getJavaType())).findAny();
}
private void addCurrentJoin(Join