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-parent hawkbit-extension-artifact-repository-mongo - hawkBit :: Artifact Repository Mongo + hawkBit :: Extensions :: Artifact Repository Mongo @@ -49,16 +49,6 @@ spring-boot-starter-test test - - org.springframework - spring-test - test - - - org.easytesting - fest-assert-core - test - ru.yandex.qatools.allure allure-junit-adaptor @@ -70,12 +60,6 @@ de.flapdoodle.embed.mongo test - - - 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-SNAPSHOT hawkbit-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-test test 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-test test 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.boot spring-boot-starter-test @@ -53,16 +43,6 @@ allure-junit-adaptor test - - org.easytesting - fest-assert-core - test - - - org.easytesting - fest-assert - test - org.springframework.boot spring-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-aspects test - - org.easytesting - fest-assert-core - test - - - org.easytesting - fest-assert - test - ru.yandex.qatools.allure allure-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-test test - - org.springframework - spring-test - test - - - org.easytesting - fest-assert-core - test - - - org.easytesting - fest-assert - test - org.springframework.security spring-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-test test - - org.easytesting - fest-assert-core - test - - - org.easytesting - fest-assert - test - ru.yandex.qatools.allure allure-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-test test 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-aspects test - - org.easytesting - fest-assert-core - test - - - org.easytesting - fest-assert - test - ru.yandex.qatools.allure allure-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-test test 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. * *
      * {@code
@@ -58,9 +58,8 @@ public interface RolloutManagement {
      *  }
      * 
* - * 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 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 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 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-test test 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-adaptor test - - org.easytesting - fest-assert-core - test - - - org.easytesting - fest-assert - test - org.powermock powermock-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 join) { diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/event/remote/RemoteIdEventTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/event/remote/RemoteIdEventTest.java index 9f15e2b40..f678421da 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/event/remote/RemoteIdEventTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/event/remote/RemoteIdEventTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.event.remote; -import static org.fest.assertions.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import java.lang.reflect.Constructor; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/event/remote/RemoteTenantAwareEventTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/event/remote/RemoteTenantAwareEventTest.java index e5ba5daec..72f02fd9b 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/event/remote/RemoteTenantAwareEventTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/event/remote/RemoteTenantAwareEventTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.event.remote; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import org.eclipse.hawkbit.repository.jpa.model.JpaAction; import org.eclipse.hawkbit.repository.model.Action; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/event/remote/entity/AbstractRemoteEntityEventTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/event/remote/entity/AbstractRemoteEntityEventTest.java index 9c7c4ecb9..c75195c2b 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/event/remote/entity/AbstractRemoteEntityEventTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/event/remote/entity/AbstractRemoteEntityEventTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.event.remote.entity; -import static org.fest.assertions.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import java.lang.reflect.Constructor; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/event/remote/entity/ActionEventTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/event/remote/entity/ActionEventTest.java index e6b2bd61c..d86035f11 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/event/remote/entity/ActionEventTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/event/remote/entity/ActionEventTest.java @@ -44,6 +44,7 @@ public class ActionEventTest extends AbstractRemoteEntityEventTest { generateAction.setActionType(ActionType.FORCED); final Target target = testdataFactory.createTarget("Test"); generateAction.setTarget(target); + generateAction.setDistributionSet(testdataFactory.createDistributionSet()); return actionRepository.save(generateAction); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/event/remote/entity/RolloutGroupEventTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/event/remote/entity/RolloutGroupEventTest.java index fb150d464..974b73b8a 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/event/remote/entity/RolloutGroupEventTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/event/remote/entity/RolloutGroupEventTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.event.remote.entity; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.UUID; @@ -56,7 +56,7 @@ public class RolloutGroupEventTest extends AbstractRemoteEntityEventTest actionStatusList = deploymentManagement.findActionStatusByAction(pageReq, actionId) @@ -326,9 +326,9 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest { // create two artifacts with identical SHA1 hash final Artifact artifact = artifactManagement.createArtifact(new ByteArrayInputStream(random), - ds.findFirstModuleByType(osType).getId(), "file1", false); + ds.findFirstModuleByType(osType).get().getId(), "file1", false); final Artifact artifact2 = artifactManagement.createArtifact(new ByteArrayInputStream(random), - ds2.findFirstModuleByType(osType).getId(), "file1", false); + ds2.findFirstModuleByType(osType).get().getId(), "file1", false); assertThat(artifact.getSha1Hash()).isEqualTo(artifact2.getSha1Hash()); assertThat( @@ -462,8 +462,8 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest { entityFactory.actionStatus().create(action.getId()).status(Action.Status.RUNNING)); // nothing changed as "feedback after close" is disabled - assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() - .getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get() + .getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC); assertThat(actionStatusRepository.count()).isEqualTo(3); assertThat(deploymentManagement.findActionStatusByAction(pageReq, action.getId()).getNumberOfElements()) @@ -487,8 +487,8 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest { entityFactory.actionStatus().create(action.getId()).status(Action.Status.RUNNING)); // nothing changed as "feedback after close" is disabled - assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).getTargetInfo() - .getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC); + assertThat(targetManagement.findTargetByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get() + .getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC); // however, additional action status has been stored assertThat(actionStatusRepository.findAll(pageReq).getNumberOfElements()).isEqualTo(4); @@ -514,7 +514,7 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest { testData.put("test1", "testdata1"); controllerManagament.updateControllerAttributes(controllerId, testData); - final Target target = targetManagement.findTargetByControllerIDWithDetails(controllerId); + final Target target = targetManagement.findTargetByControllerIDWithDetails(controllerId).get(); assertThat(target.getTargetInfo().getControllerAttributes()).as("Controller Attributes are wrong") .isEqualTo(testData); } @@ -525,7 +525,7 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest { testData.put("test2", "testdata20"); controllerManagament.updateControllerAttributes(controllerId, testData); - final Target target = targetManagement.findTargetByControllerIDWithDetails(controllerId); + final Target target = targetManagement.findTargetByControllerIDWithDetails(controllerId).get(); testData.put("test1", "testdata1"); assertThat(target.getTargetInfo().getControllerAttributes()).as("Controller Attributes are wrong") .isEqualTo(testData); @@ -538,7 +538,7 @@ public class ControllerManagementTest extends AbstractJpaIntegrationTest { controllerManagament.updateControllerAttributes(controllerId, testData); - final Target target = targetManagement.findTargetByControllerIDWithDetails(controllerId); + final Target target = targetManagement.findTargetByControllerIDWithDetails(controllerId).get(); testData.put("test2", "testdata20"); assertThat(target.getTargetInfo().getControllerAttributes()).as("Controller Attributes are wrong") .isEqualTo(testData); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DeploymentManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DeploymentManagementTest.java index 15d33d2b7..06c877495 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DeploymentManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DeploymentManagementTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa; -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.fail; @@ -22,9 +22,9 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.eclipse.hawkbit.repository.ActionStatusFields; -import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.event.remote.TargetAssignDistributionSetEvent; import org.eclipse.hawkbit.repository.event.remote.entity.CancelTargetAssignmentEvent; +import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.exception.ForceQuitActionNotAllowedException; import org.eclipse.hawkbit.repository.exception.IncompleteDistributionSetException; import org.eclipse.hawkbit.repository.jpa.configuration.Constants; @@ -92,7 +92,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { final List testTarget = testdataFactory.createTargets(1); // one action with one action status is generated final Long actionId = assignDistributionSet(testDs, testTarget).getActions().get(0); - final Action action = deploymentManagement.findActionWithDetails(actionId); + final Action action = deploymentManagement.findActionWithDetails(actionId).get(); assertThat(action.getDistributionSet()).as("DistributionSet in action").isNotNull(); assertThat(action.getTarget()).as("Target in action").isNotNull(); @@ -109,7 +109,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { final List testTarget = testdataFactory.createTargets(1); // one action with one action status is generated final Action action = deploymentManagement - .findActionWithDetails(assignDistributionSet(testDs, testTarget).getActions().get(0)); + .findActionWithDetails(assignDistributionSet(testDs, testTarget).getActions().get(0)).get(); // save 2 action status actionStatusRepository.save(new JpaActionStatus(action, Status.RETRIEVED, System.currentTimeMillis())); actionStatusRepository.save(new JpaActionStatus(action, Status.RUNNING, System.currentTimeMillis())); @@ -123,15 +123,34 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { } @Test - @Description("Ensures that distribution sets can assigned and unassigned to a distribution set tag. Not exists distribution set will be ignored for the assignment.") - public void assignAndUnassignDistributionSetToTag() { - final List assignDS = new ArrayList<>(); + @Description("Ensures that tag to distribution set assignment that does not exist will cause EntityNotFoundException.") + public void assignDistributionSetToTagThatDoesNotExistThrowsException() { + final List assignDS = Lists.newArrayListWithExpectedSize(5); for (int i = 0; i < 4; i++) { - assignDS.add(testdataFactory.createDistributionSet("DS" + i, "1.0", new ArrayList()) - .getId()); + assignDS.add(testdataFactory.createDistributionSet("DS" + i, "1.0", Collections.emptyList()).getId()); } // not exists assignDS.add(Long.valueOf(100)); + + final DistributionSetTag tag = tagManagement + .createDistributionSetTag(entityFactory.tag().create().name("Tag1")); + + try { + distributionSetManagement.assignTag(assignDS, tag.getId()); + fail("It should not be possible to assign a DS that does not exist"); + } catch (final EntityNotFoundException e) { + // Ok + } + } + + @Test + @Description("Ensures that distribution sets can assigned and unassigned to a distribution set tag.") + public void assignAndUnassignDistributionSetToTag() { + final List assignDS = Lists.newArrayListWithExpectedSize(4); + for (int i = 0; i < 4; i++) { + assignDS.add(testdataFactory.createDistributionSet("DS" + i, "1.0", Collections.emptyList()).getId()); + } + final DistributionSetTag tag = tagManagement .createDistributionSetTag(entityFactory.tag().create().name("Tag1")); @@ -139,7 +158,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { assertThat(assignedDS.size()).as("assigned ds has wrong size").isEqualTo(4); assignedDS.forEach(ds -> assertThat(ds.getTags().size()).as("ds has wrong tag size").isEqualTo(1)); - DistributionSetTag findDistributionSetTag = tagManagement.findDistributionSetTag("Tag1"); + DistributionSetTag findDistributionSetTag = tagManagement.findDistributionSetTag("Tag1").get(); assertThat(assignedDS.size()).as("assigned ds has wrong size") .isEqualTo(findDistributionSetTag.getAssignedToDistributionSet().size()); @@ -147,13 +166,13 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { findDistributionSetTag.getId()); assertThat(unAssignDS.getId()).as("unassigned ds is wrong").isEqualTo(assignDS.get(0)); assertThat(unAssignDS.getTags().size()).as("unassigned ds has wrong tag size").isEqualTo(0); - findDistributionSetTag = tagManagement.findDistributionSetTag("Tag1"); + findDistributionSetTag = tagManagement.findDistributionSetTag("Tag1").get(); assertThat(findDistributionSetTag.getAssignedToDistributionSet().size()).as("ds tag ds has wrong ds size") .isEqualTo(3); final List unAssignTargets = distributionSetManagement .unAssignAllDistributionSetsByTag(findDistributionSetTag.getId()); - findDistributionSetTag = tagManagement.findDistributionSetTag("Tag1"); + findDistributionSetTag = tagManagement.findDistributionSetTag("Tag1").get(); assertThat(findDistributionSetTag.getAssignedToDistributionSet().size()).as("ds tag has wrong ds size") .isEqualTo(0); assertThat(unAssignTargets.size()).as("unassigned target has wrong size").isEqualTo(3); @@ -194,7 +213,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { final DistributionSet dsInstalled = action.getDistributionSet(); // check initial status - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) + assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getUpdateStatus()) .as("target has update status").isEqualTo(TargetUpdateStatus.IN_SYNC); // assign the two sets in a row @@ -206,26 +225,26 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { // we cancel second -> back to first deploymentManagement.cancelAction(secondAction.getId()); - secondAction = (JpaAction) deploymentManagement.findActionWithDetails(secondAction.getId()); + secondAction = (JpaAction) deploymentManagement.findActionWithDetails(secondAction.getId()).get(); // confirm cancellation controllerManagement.addCancelActionStatus( entityFactory.actionStatus().create(secondAction.getId()).status(Status.CANCELED)); assertThat(actionStatusRepository.findAll()).as("wrong size of actions status").hasSize(7); - assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet()).as("wrong ds") + assertThat(targetManagement.findTargetByControllerID("4712").get().getAssignedDistributionSet()).as("wrong ds") .isEqualTo(dsFirst); - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) + assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getUpdateStatus()) .as("wrong update status").isEqualTo(TargetUpdateStatus.PENDING); // we cancel first -> back to installed deploymentManagement.cancelAction(firstAction.getId()); - firstAction = (JpaAction) deploymentManagement.findActionWithDetails(firstAction.getId()); + firstAction = (JpaAction) deploymentManagement.findActionWithDetails(firstAction.getId()).get(); // confirm cancellation controllerManagement.addCancelActionStatus( entityFactory.actionStatus().create(firstAction.getId()).status(Status.CANCELED)); assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(9); - assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet()) + assertThat(targetManagement.findTargetByControllerID("4712").get().getAssignedDistributionSet()) .as("wrong assigned ds").isEqualTo(dsInstalled); - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) + assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getUpdateStatus()) .as("wrong update status").isEqualTo(TargetUpdateStatus.IN_SYNC); } @@ -241,7 +260,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { final DistributionSet dsInstalled = action.getDistributionSet(); // check initial status - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) + assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getUpdateStatus()) .as("wrong update status").isEqualTo(TargetUpdateStatus.IN_SYNC); // assign the two sets in a row @@ -254,28 +273,28 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { // we cancel first -> second is left deploymentManagement.cancelAction(firstAction.getId()); // confirm cancellation - firstAction = (JpaAction) deploymentManagement.findActionWithDetails(firstAction.getId()); + firstAction = (JpaAction) deploymentManagement.findActionWithDetails(firstAction.getId()).get(); controllerManagement.addCancelActionStatus( entityFactory.actionStatus().create(firstAction.getId()).status(Status.CANCELED)); assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(7); - assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet()) + assertThat(targetManagement.findTargetByControllerID("4712").get().getAssignedDistributionSet()) .as("wrong assigned ds").isEqualTo(dsSecond); - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) + assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getUpdateStatus()) .as("wrong target update status").isEqualTo(TargetUpdateStatus.PENDING); // we cancel second -> remain assigned until finished cancellation deploymentManagement.cancelAction(secondAction.getId()); - secondAction = (JpaAction) deploymentManagement.findActionWithDetails(secondAction.getId()); + secondAction = (JpaAction) deploymentManagement.findActionWithDetails(secondAction.getId()).get(); assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(8); - assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet()) + assertThat(targetManagement.findTargetByControllerID("4712").get().getAssignedDistributionSet()) .as("wrong assigned ds").isEqualTo(dsSecond); // confirm cancellation controllerManagement.addCancelActionStatus( entityFactory.actionStatus().create(secondAction.getId()).status(Status.CANCELED)); // cancelled success -> back to dsInstalled - assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet()) + assertThat(targetManagement.findTargetByControllerID("4712").get().getAssignedDistributionSet()) .as("wrong installed ds").isEqualTo(dsInstalled); - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) + assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getUpdateStatus()) .as("wrong target info update status").isEqualTo(TargetUpdateStatus.IN_SYNC); } @@ -289,7 +308,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { final DistributionSet ds = testdataFactory.createDistributionSet("newDS", true); // verify initial status - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) + assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getUpdateStatus()) .as("wrong target info update status").isEqualTo(TargetUpdateStatus.IN_SYNC); Action assigningAction = assignSet(target, ds); @@ -298,21 +317,21 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { assertThat(actionRepository.findAll()).as("wrong size of action").hasSize(2); assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(4); - target = targetManagement.findTargetByControllerID(target.getControllerId()); + target = targetManagement.findTargetByControllerID(target.getControllerId()).get(); // force quit assignment deploymentManagement.cancelAction(assigningAction.getId()); - assigningAction = deploymentManagement.findActionWithDetails(assigningAction.getId()); + assigningAction = deploymentManagement.findActionWithDetails(assigningAction.getId()).get(); deploymentManagement.forceQuitAction(assigningAction.getId()); - assigningAction = deploymentManagement.findActionWithDetails(assigningAction.getId()); + assigningAction = deploymentManagement.findActionWithDetails(assigningAction.getId()).get(); // verify assertThat(assigningAction.getStatus()).as("wrong size of status").isEqualTo(Status.CANCELED); - assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet()) + assertThat(targetManagement.findTargetByControllerID("4712").get().getAssignedDistributionSet()) .as("wrong assigned ds").isEqualTo(dsInstalled); - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) + assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getUpdateStatus()) .as("wrong target update status").isEqualTo(TargetUpdateStatus.IN_SYNC); } @@ -325,7 +344,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { final DistributionSet ds = testdataFactory.createDistributionSet("newDS", true); // verify initial status - assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) + assertThat(targetManagement.findTargetByControllerID("4712").get().getTargetInfo().getUpdateStatus()) .as("wrong update status").isEqualTo(TargetUpdateStatus.IN_SYNC); final Action assigningAction = assignSet(target, ds); @@ -344,11 +363,11 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { private JpaAction assignSet(final Target target, final DistributionSet ds) { assignDistributionSet(ds.getId(), target.getControllerId()); + assertThat(targetManagement.findTargetByControllerID(target.getControllerId()).get().getTargetInfo() + .getUpdateStatus()).as("wrong update status").isEqualTo(TargetUpdateStatus.PENDING); assertThat( - targetManagement.findTargetByControllerID(target.getControllerId()).getTargetInfo().getUpdateStatus()) - .as("wrong update status").isEqualTo(TargetUpdateStatus.PENDING); - assertThat(targetManagement.findTargetByControllerID(target.getControllerId()).getAssignedDistributionSet()) - .as("wrong assigned ds").isEqualTo(ds); + targetManagement.findTargetByControllerID(target.getControllerId()).get().getAssignedDistributionSet()) + .as("wrong assigned ds").isEqualTo(ds); final JpaAction action = actionRepository .findByTargetAndDistributionSet(pageReq, (JpaTarget) target, (JpaDistributionSet) ds).getContent() .get(0); @@ -396,13 +415,13 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { .doesNotContain(Iterables.toArray(savedDeployedTargets, Target.class)); for (final Target myt : savedNakedTargets) { - final Target t = targetManagement.findTargetByControllerID(myt.getControllerId()); + final Target t = targetManagement.findTargetByControllerID(myt.getControllerId()).get(); assertThat(deploymentManagement.countActionsByTarget(t.getControllerId())).as("action should be empty") .isEqualTo(0L); } for (final Target myt : savedDeployedTargets) { - final Target t = targetManagement.findTargetByControllerID(myt.getControllerId()); + final Target t = targetManagement.findTargetByControllerID(myt.getControllerId()).get(); final List activeActionsByTarget = deploymentManagement .findActiveActionsByTarget(t.getControllerId()); assertThat(activeActionsByTarget).as("action should not be empty").isNotEmpty(); @@ -546,20 +565,20 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { // verifying the correctness of the assignments for (final Target t : deployResWithDsA.getDeployedTargets()) { assertThat(t.getAssignedDistributionSet().getId()).as("assignment is not correct").isEqualTo(dsA.getId()); - assertThat(targetManagement.findTargetByControllerID(t.getControllerId()).getTargetInfo() + assertThat(targetManagement.findTargetByControllerID(t.getControllerId()).get().getTargetInfo() .getInstalledDistributionSet()).as("installed ds should be null").isNull(); } for (final Target t : deployResWithDsB.getDeployedTargets()) { assertThat(t.getAssignedDistributionSet().getId()).as("assigned ds is wrong").isEqualTo(dsB.getId()); - assertThat(targetManagement.findTargetByControllerID(t.getControllerId()).getTargetInfo() + assertThat(targetManagement.findTargetByControllerID(t.getControllerId()).get().getTargetInfo() .getInstalledDistributionSet()).as("installed ds should be null").isNull(); } for (final Target t : deployResWithDsC.getDeployedTargets()) { assertThat(t.getAssignedDistributionSet().getId()).isEqualTo(dsC.getId()); - assertThat(targetManagement.findTargetByControllerID(t.getControllerId()).getTargetInfo() + assertThat(targetManagement.findTargetByControllerID(t.getControllerId()).get().getTargetInfo() .getInstalledDistributionSet()).as("installed ds should not be null").isNull(); - assertThat(targetManagement.findTargetByControllerID(t.getControllerId()).getTargetInfo().getUpdateStatus()) - .as("wrong target info update status").isEqualTo(TargetUpdateStatus.PENDING); + assertThat(targetManagement.findTargetByControllerID(t.getControllerId()).get().getTargetInfo() + .getUpdateStatus()).as("wrong target info update status").isEqualTo(TargetUpdateStatus.PENDING); } final List updatedTsDsA = testdataFactory @@ -570,12 +589,12 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { // verify, that dsA is deployed correctly assertThat(updatedTsDsA).as("ds is not deployed correctly").isEqualTo(deployResWithDsA.getDeployedTargets()); for (final Target t_ : updatedTsDsA) { - final Target t = targetManagement.findTargetByControllerID(t_.getControllerId()); + final Target t = targetManagement.findTargetByControllerID(t_.getControllerId()).get(); assertThat(t.getAssignedDistributionSet()).as("assigned ds is wrong").isEqualTo(dsA); - assertThat(targetManagement.findTargetByControllerID(t.getControllerId()).getTargetInfo() + assertThat(targetManagement.findTargetByControllerID(t.getControllerId()).get().getTargetInfo() .getInstalledDistributionSet()).as("installed ds is wrong").isEqualTo(dsA); - assertThat(targetManagement.findTargetByControllerID(t.getControllerId()).getTargetInfo().getUpdateStatus()) - .as("wrong target info update status").isEqualTo(TargetUpdateStatus.IN_SYNC); + assertThat(targetManagement.findTargetByControllerID(t.getControllerId()).get().getTargetInfo() + .getUpdateStatus()).as("wrong target info update status").isEqualTo(TargetUpdateStatus.IN_SYNC); assertThat(deploymentManagement.findActiveActionsByTarget(t.getControllerId())) .as("no actions should be active").hasSize(0); } @@ -596,12 +615,12 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { assertThat(deployed2DS).as("deployed ds is wrong").hasSameSizeAs(deployResWithDsBTargets); for (final Target t_ : deployed2DS) { - final Target t = targetManagement.findTargetByControllerID(t_.getControllerId()); + final Target t = targetManagement.findTargetByControllerID(t_.getControllerId()).get(); assertThat(t.getAssignedDistributionSet()).as("assigned ds is wrong").isEqualTo(dsA); - assertThat(targetManagement.findTargetByControllerID(t.getControllerId()).getTargetInfo() + assertThat(targetManagement.findTargetByControllerID(t.getControllerId()).get().getTargetInfo() .getInstalledDistributionSet()).as("installed ds should be null").isNull(); - assertThat(targetManagement.findTargetByControllerID(t.getControllerId()).getTargetInfo().getUpdateStatus()) - .as("wrong target info update status").isEqualTo(TargetUpdateStatus.PENDING); + assertThat(targetManagement.findTargetByControllerID(t.getControllerId()).get().getTargetInfo() + .getUpdateStatus()).as("wrong target info update status").isEqualTo(TargetUpdateStatus.PENDING); } } @@ -630,16 +649,16 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { final DeploymentResult deploymentResult = prepareComplexRepo(undeployedTargetPrefix, noOfUndeployedTargets, deployedTargetPrefix, noOfDeployedTargets, noOfDistributionSets, "myTestDS"); - DistributionSet dsA = testdataFactory.createDistributionSet(""); + final DistributionSet dsA = testdataFactory.createDistributionSet(""); distributionSetManagement.deleteDistributionSet(dsA.getId()); - dsA = distributionSetManagement.findDistributionSetById(dsA.getId()); - assertThat(dsA).as("ds should be null").isNull(); + + assertThat(distributionSetManagement.findDistributionSetById(dsA.getId()).isPresent()).isFalse(); // // verify that the ds is not physically deleted for (final DistributionSet ds : deploymentResult.getDistributionSets()) { distributionSetManagement.deleteDistributionSet(ds.getId()); - final DistributionSet foundDS = distributionSetManagement.findDistributionSetById(ds.getId()); + final DistributionSet foundDS = distributionSetManagement.findDistributionSetById(ds.getId()).get(); assertThat(foundDS).as("founded should not be null").isNotNull(); assertThat(foundDS.isDeleted()).as("found ds should be deleted").isTrue(); } @@ -711,13 +730,13 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { // doing the assignment targs = assignDistributionSet(dsA, targs).getAssignedEntity(); - Target targ = targetManagement.findTargetByControllerID(targs.iterator().next().getControllerId()); + Target targ = targetManagement.findTargetByControllerID(targs.iterator().next().getControllerId()).get(); // checking the revisions of the created entities // verifying that the revision of the object and the revision within the // DB has not changed assertThat(dsA.getOptLockRevision()).as("lock revision is wrong").isEqualTo( - distributionSetManagement.findDistributionSetByIdWithDetails(dsA.getId()).getOptLockRevision()); + distributionSetManagement.findDistributionSetByIdWithDetails(dsA.getId()).get().getOptLockRevision()); // verifying that the assignment is correct assertThat(deploymentManagement.findActiveActionsByTarget(targ.getControllerId()).size()) @@ -736,7 +755,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { controllerManagament.addUpdateActionStatus( entityFactory.actionStatus().create(updAct.getContent().get(0).getId()).status(Status.FINISHED)); - targ = targetManagement.findTargetByControllerID(targ.getControllerId()); + targ = targetManagement.findTargetByControllerID(targ.getControllerId()).get(); assertEquals("active target actions are wrong", 0, deploymentManagement.findActiveActionsByTarget(targ.getControllerId()).size()); @@ -754,11 +773,11 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { assertEquals("active actions are wrong", 1, deploymentManagement.findActiveActionsByTarget(targ.getControllerId()).size()); - assertEquals("target status is wrong", TargetUpdateStatus.PENDING, - targetManagement.findTargetByControllerID(targ.getControllerId()).getTargetInfo().getUpdateStatus()); + assertEquals("target status is wrong", TargetUpdateStatus.PENDING, targetManagement + .findTargetByControllerID(targ.getControllerId()).get().getTargetInfo().getUpdateStatus()); assertEquals("wrong assigned ds", dsB, targ.getAssignedDistributionSet()); assertEquals("Installed ds is wrong", dsA.getId(), - targetManagement.findTargetByControllerIDWithDetails(targ.getControllerId()).getTargetInfo() + targetManagement.findTargetByControllerIDWithDetails(targ.getControllerId()).get().getTargetInfo() .getInstalledDistributionSet().getId()); assertEquals("Active ds is wrong", dsB, deploymentManagement.findActiveActionsByTarget(targ.getControllerId()).get(0).getDistributionSet()); @@ -774,12 +793,12 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { final Target targ = testdataFactory.createTarget("target-id-A"); assertThat(dsA.getOptLockRevision()).as("lock revision is wrong").isEqualTo( - distributionSetManagement.findDistributionSetByIdWithDetails(dsA.getId()).getOptLockRevision()); + distributionSetManagement.findDistributionSetByIdWithDetails(dsA.getId()).get().getOptLockRevision()); assignDistributionSet(dsA, Lists.newArrayList(targ)); assertThat(dsA.getOptLockRevision()).as("lock revision is wrong").isEqualTo( - distributionSetManagement.findDistributionSetByIdWithDetails(dsA.getId()).getOptLockRevision()); + distributionSetManagement.findDistributionSetByIdWithDetails(dsA.getId()).get().getOptLockRevision()); } @Test @@ -793,16 +812,17 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { ds.getId(), ActionType.SOFT, org.eclipse.hawkbit.repository.model.RepositoryModelConstants.NO_FORCE_TIME, Lists.newArrayList(target.getControllerId())); - final Action action = deploymentManagement.findActionWithDetails(assignDistributionSet.getActions().get(0)); + final Action action = deploymentManagement.findActionWithDetails(assignDistributionSet.getActions().get(0)) + .get(); // verify preparation - Action findAction = deploymentManagement.findAction(action.getId()); + Action findAction = deploymentManagement.findAction(action.getId()).get(); assertThat(findAction.getActionType()).as("action type is wrong").isEqualTo(ActionType.SOFT); // test deploymentManagement.forceTargetAction(action.getId()); // verify test - findAction = deploymentManagement.findAction(action.getId()); + findAction = deploymentManagement.findAction(action.getId()).get(); assertThat(findAction.getActionType()).as("action type is wrong").isEqualTo(ActionType.FORCED); } @@ -817,9 +837,10 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { ds.getId(), ActionType.FORCED, org.eclipse.hawkbit.repository.model.RepositoryModelConstants.NO_FORCE_TIME, Lists.newArrayList(target.getControllerId())); - final Action action = deploymentManagement.findActionWithDetails(assignDistributionSet.getActions().get(0)); + final Action action = deploymentManagement.findActionWithDetails(assignDistributionSet.getActions().get(0)) + .get(); // verify perparation - Action findAction = deploymentManagement.findAction(action.getId()); + Action findAction = deploymentManagement.findAction(action.getId()).get(); assertThat(findAction.getActionType()).as("action type is wrong").isEqualTo(ActionType.FORCED); // test @@ -827,7 +848,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { // verify test assertThat(forceTargetAction.getActionType()).as("action type is wrong").isEqualTo(ActionType.FORCED); - findAction = deploymentManagement.findAction(action.getId()); + findAction = deploymentManagement.findAction(action.getId()).get(); assertThat(findAction.getActionType()).as("action type is wrong").isEqualTo(ActionType.FORCED); } @@ -896,7 +917,7 @@ public class DeploymentManagementTest extends AbstractJpaIntegrationTest { assertThat(event.getActionId()).as("Action id in database and event do not match") .isEqualTo(activeActionsByTarget.get(0).getId()); - assertThat(distributionSetManagement.findDistributionSetById(event.getDistributionSetId()) + assertThat(distributionSetManagement.findDistributionSetById(event.getDistributionSetId()).get() .getModules()).as("softwaremodule size is not correct") .containsOnly(ds.getModules().toArray(new SoftwareModule[ds.getModules().size()])); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DistributionSetManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DistributionSetManagementTest.java index b3640a611..b5076c1f4 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DistributionSetManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DistributionSetManagementTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import java.util.ArrayList; @@ -18,6 +18,7 @@ import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; +import org.assertj.core.api.Condition; import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.builder.DistributionSetCreate; import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetCreatedEvent; @@ -39,7 +40,6 @@ import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.test.matcher.Expect; import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents; import org.eclipse.hawkbit.repository.test.util.WithUser; -import org.fest.assertions.core.Condition; import org.junit.Test; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; @@ -64,25 +64,29 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest { public void updateUnassignedDistributionSetTypeModules() { DistributionSetType updatableType = distributionSetManagement.createDistributionSetType( entityFactory.distributionSetType().create().key("updatableType").name("to be deleted")); - assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes()) - .isEmpty(); + assertThat( + distributionSetManagement.findDistributionSetTypeByKey("updatableType").get().getMandatoryModuleTypes()) + .isEmpty(); // add OS updatableType = distributionSetManagement.assignMandatorySoftwareModuleTypes(updatableType.getId(), Sets.newHashSet(osType.getId())); - assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes()) - .containsOnly(osType); + assertThat( + distributionSetManagement.findDistributionSetTypeByKey("updatableType").get().getMandatoryModuleTypes()) + .containsOnly(osType); // add JVM updatableType = distributionSetManagement.assignMandatorySoftwareModuleTypes(updatableType.getId(), Sets.newHashSet(runtimeType.getId())); - assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes()) - .containsOnly(osType, runtimeType); + assertThat( + distributionSetManagement.findDistributionSetTypeByKey("updatableType").get().getMandatoryModuleTypes()) + .containsOnly(osType, runtimeType); // remove OS updatableType = distributionSetManagement.unassignSoftwareModuleType(updatableType.getId(), osType.getId()); - assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes()) - .containsOnly(runtimeType); + assertThat( + distributionSetManagement.findDistributionSetTypeByKey("updatableType").get().getMandatoryModuleTypes()) + .containsOnly(runtimeType); } @Test @@ -90,17 +94,18 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest { public void updateAssignedDistributionSetTypeMetaData() { final DistributionSetType nonUpdatableType = distributionSetManagement.createDistributionSetType(entityFactory .distributionSetType().create().key("updatableType").name("to be deleted").colour("test123")); - assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes()) - .isEmpty(); + assertThat( + distributionSetManagement.findDistributionSetTypeByKey("updatableType").get().getMandatoryModuleTypes()) + .isEmpty(); distributionSetManagement.createDistributionSet(entityFactory.distributionSet().create().name("newtypesoft") .version("1").type(nonUpdatableType.getKey())); distributionSetManagement.updateDistributionSetType( entityFactory.distributionSetType().update(nonUpdatableType.getId()).description("a new description")); - assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getDescription()) + assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").get().getDescription()) .isEqualTo("a new description"); - assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getColour()) + assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").get().getColour()) .isEqualTo("test123"); } @@ -109,8 +114,9 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest { public void addModuleToAssignedDistributionSetTypeFails() { final DistributionSetType nonUpdatableType = distributionSetManagement.createDistributionSetType( entityFactory.distributionSetType().create().key("updatableType").name("to be deleted")); - assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes()) - .isEmpty(); + assertThat( + distributionSetManagement.findDistributionSetTypeByKey("updatableType").get().getMandatoryModuleTypes()) + .isEmpty(); distributionSetManagement.createDistributionSet(entityFactory.distributionSet().create().name("newtypesoft") .version("1").type(nonUpdatableType.getKey())); @@ -129,8 +135,9 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest { public void removeModuleToAssignedDistributionSetTypeFails() { DistributionSetType nonUpdatableType = distributionSetManagement.createDistributionSetType( entityFactory.distributionSetType().create().key("updatableType").name("to be deleted")); - assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes()) - .isEmpty(); + assertThat( + distributionSetManagement.findDistributionSetTypeByKey("updatableType").get().getMandatoryModuleTypes()) + .isEmpty(); nonUpdatableType = distributionSetManagement.assignMandatorySoftwareModuleTypes(nonUpdatableType.getId(), Sets.newHashSet(osType.getId())); @@ -170,7 +177,8 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest { entityFactory.distributionSet().create().name("softdeleted").version("1").type(softDelete.getKey())); distributionSetManagement.deleteDistributionSetType(softDelete.getId()); - assertThat(distributionSetManagement.findDistributionSetTypeByKey("softdeleted").isDeleted()).isEqualTo(true); + assertThat(distributionSetManagement.findDistributionSetTypeByKey("softdeleted").get().isDeleted()) + .isEqualTo(true); } @Test @@ -251,7 +259,7 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest { // assign target assignDistributionSet(ds.getId(), target.getControllerId()); - ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId()); + ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId()).get(); // not allowed as it is assigned now try { @@ -264,7 +272,7 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest { // not allowed as it is assigned now try { ds = distributionSetManagement.unassignSoftwareModule(ds.getId(), - ds.findFirstModuleByType(appType).getId()); + ds.findFirstModuleByType(appType).get().getId()); fail("Expected EntityReadOnlyException"); } catch (final EntityReadOnlyException e) { @@ -303,19 +311,19 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest { // update data // legal update of module addition distributionSetManagement.assignSoftwareModules(ds.getId(), Sets.newHashSet(os.getId())); - ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId()); - assertThat(ds.findFirstModuleByType(osType)).isEqualTo(os); + ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId()).get(); + assertThat(ds.findFirstModuleByType(osType).get()).isEqualTo(os); // legal update of module removal - distributionSetManagement.unassignSoftwareModule(ds.getId(), ds.findFirstModuleByType(appType).getId()); - ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId()); - assertThat(ds.findFirstModuleByType(appType)).isNull(); + distributionSetManagement.unassignSoftwareModule(ds.getId(), ds.findFirstModuleByType(appType).get().getId()); + ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId()).get(); + assertThat(ds.findFirstModuleByType(appType).isPresent()).isFalse(); // Update description distributionSetManagement .updateDistributionSet(entityFactory.distributionSet().update(ds.getId()).name("a new name") .description("a new description").version("a new version").requiredMigrationStep(true)); - ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId()); + ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId()).get(); assertThat(ds.getDescription()).isEqualTo("a new description"); assertThat(ds.getName()).isEqualTo("a new name"); assertThat(ds.getVersion()).isEqualTo("a new version"); @@ -338,7 +346,7 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest { // create an DS meta data entry createDistributionSetMetadata(ds.getId(), new JpaDistributionSetMetadata(knownKey, ds, knownValue)); - DistributionSet changedLockRevisionDS = distributionSetManagement.findDistributionSetById(ds.getId()); + DistributionSet changedLockRevisionDS = distributionSetManagement.findDistributionSetById(ds.getId()).get(); assertThat(changedLockRevisionDS.getOptLockRevision()).isEqualTo(2); Thread.sleep(100); @@ -349,7 +357,7 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest { // we are updating the sw meta data so also modifying the base software // module so opt lock // revision must be three - changedLockRevisionDS = distributionSetManagement.findDistributionSetById(ds.getId()); + changedLockRevisionDS = distributionSetManagement.findDistributionSetById(ds.getId()).get(); assertThat(changedLockRevisionDS.getOptLockRevision()).isEqualTo(3); assertThat(changedLockRevisionDS.getLastModifiedAt()).isGreaterThan(0L); @@ -435,14 +443,14 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest { assignDistributionSet(dsDeleted, Lists.newArrayList(testdataFactory.createTargets(5))); distributionSetManagement.deleteDistributionSet(dsDeleted.getId()); - dsDeleted = distributionSetManagement.findDistributionSetById(dsDeleted.getId()); + dsDeleted = distributionSetManagement.findDistributionSetById(dsDeleted.getId()).get(); ds100Group1 = toggleTagAssignment(ds100Group1, dsTagA).getAssignedEntity(); - dsTagA = distributionSetTagRepository.findByNameEquals(dsTagA.getName()); + dsTagA = distributionSetTagRepository.findByNameEquals(dsTagA.getName()).get(); ds100Group1 = toggleTagAssignment(ds100Group1, dsTagB).getAssignedEntity(); - dsTagA = distributionSetTagRepository.findByNameEquals(dsTagA.getName()); + dsTagA = distributionSetTagRepository.findByNameEquals(dsTagA.getName()).get(); ds100Group2 = toggleTagAssignment(ds100Group2, dsTagA).getAssignedEntity(); - dsTagA = distributionSetTagRepository.findByNameEquals(dsTagA.getName()); + dsTagA = distributionSetTagRepository.findByNameEquals(dsTagA.getName()).get(); // check setup assertThat(distributionSetRepository.findAll()).hasSize(203); @@ -655,11 +663,8 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest { @Test @Description("Deltes a DS that is no in use. Expected behaviour is a hard delete on the database.") public void deleteUnassignedDistributionSet() { - DistributionSet ds1 = testdataFactory.createDistributionSet("ds-1"); - DistributionSet ds2 = testdataFactory.createDistributionSet("ds-2"); - - ds1 = distributionSetManagement.findDistributionSetByNameAndVersion(ds1.getName(), ds1.getVersion()); - ds2 = distributionSetManagement.findDistributionSetByNameAndVersion(ds2.getName(), ds2.getVersion()); + final DistributionSet ds1 = testdataFactory.createDistributionSet("ds-1"); + testdataFactory.createDistributionSet("ds-2"); // delete a ds assertThat(distributionSetRepository.findAll()).hasSize(2); @@ -707,17 +712,12 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest { @Description("Deletes a DS that is in use by either target assignment or rollout. Expected behaviour is a soft delete on the database, i.e. only marked as " + "deleted, kept as reference but unavailable for future use..") public void deleteAssignedDistributionSet() { - DistributionSet ds1 = testdataFactory.createDistributionSet("ds-1"); - DistributionSet ds2 = testdataFactory.createDistributionSet("ds-2"); - DistributionSet dsToTargetAssigned = testdataFactory.createDistributionSet("ds-3"); + testdataFactory.createDistributionSet("ds-1"); + testdataFactory.createDistributionSet("ds-2"); + final DistributionSet dsToTargetAssigned = testdataFactory.createDistributionSet("ds-3"); final DistributionSet dsToRolloutAssigned = testdataFactory.createDistributionSet("ds-4"); - ds1 = distributionSetManagement.findDistributionSetByNameAndVersion(ds1.getName(), ds1.getVersion()); - ds2 = distributionSetManagement.findDistributionSetByNameAndVersion(ds2.getName(), ds2.getVersion()); - // create assigned DS - dsToTargetAssigned = distributionSetManagement.findDistributionSetByNameAndVersion(dsToTargetAssigned.getName(), - dsToTargetAssigned.getVersion()); final Target savedTarget = testdataFactory.createTarget(); assignDistributionSet(dsToTargetAssigned.getId(), savedTarget.getControllerId()); @@ -739,11 +739,9 @@ public class DistributionSetManagementTest extends AbstractJpaIntegrationTest { @Test @Description("Verify that the DistributionSetAssignmentResult not contains already assigned targets.") public void verifyDistributionSetAssignmentResultNotContainsAlreadyAssignedTargets() { - DistributionSet dsToTargetAssigned = testdataFactory.createDistributionSet("ds-3"); + final DistributionSet dsToTargetAssigned = testdataFactory.createDistributionSet("ds-3"); // create assigned DS - dsToTargetAssigned = distributionSetManagement.findDistributionSetByNameAndVersion(dsToTargetAssigned.getName(), - dsToTargetAssigned.getVersion()); final Target savedTarget = testdataFactory.createTarget(); DistributionSetAssignmentResult assignmentResult = assignDistributionSet(dsToTargetAssigned.getId(), savedTarget.getControllerId()); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ReportManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ReportManagementTest.java index 78ccc6642..03745bb6b 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ReportManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/ReportManagementTest.java @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.jpa; -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 java.time.LocalDate; import java.time.LocalDateTime; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/RolloutManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/RolloutManagementTest.java index 86cbc206f..794f9f8a4 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/RolloutManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/RolloutManagementTest.java @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.jpa; -import static org.fest.assertions.api.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 java.util.ArrayList; import java.util.HashMap; @@ -196,7 +196,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { // Run here, because scheduler is disabled during tests rolloutManagement.checkStartingRollouts(0); - return rolloutManagement.findRolloutById(createdRollout.getId()); + return rolloutManagement.findRolloutById(createdRollout.getId()).get(); } @Step("Finish three actions of the rollout group and delete two targets") @@ -249,7 +249,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { assertThat(runningRolloutGroups.get(0).getStatus()).isEqualTo(RolloutGroupStatus.FINISHED); assertThat(runningRolloutGroups.get(1).getStatus()).isEqualTo(RolloutGroupStatus.FINISHED); assertThat(runningRolloutGroups.get(2).getStatus()).isEqualTo(RolloutGroupStatus.FINISHED); - assertThat(rolloutManagement.findRolloutById(createdRollout.getId()).getStatus()) + assertThat(rolloutManagement.findRolloutById(createdRollout.getId()).get().getStatus()) .isEqualTo(RolloutStatus.FINISHED); } @@ -284,7 +284,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { // and should execute the error action rolloutManagement.checkRunningRollouts(0); - final Rollout rollout = rolloutManagement.findRolloutById(createdRollout.getId()); + final Rollout rollout = rolloutManagement.findRolloutById(createdRollout.getId()).get(); // the rollout itself should be in paused based on the error action assertThat(rollout.getStatus()).isEqualTo(RolloutStatus.PAUSED); @@ -324,7 +324,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { // and should execute the error action rolloutManagement.checkRunningRollouts(0); - final Rollout rollout = rolloutManagement.findRolloutById(createdRollout.getId()); + final Rollout rollout = rolloutManagement.findRolloutById(createdRollout.getId()).get(); // the rollout itself should be in paused based on the error action assertThat(rollout.getStatus()).isEqualTo(RolloutStatus.PAUSED); @@ -337,7 +337,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { rolloutManagement.resumeRollout(createdRollout.getId()); // the rollout should be running again - assertThat(rolloutManagement.findRolloutById(createdRollout.getId()).getStatus()) + assertThat(rolloutManagement.findRolloutById(createdRollout.getId()).get().getStatus()) .isEqualTo(RolloutStatus.RUNNING); // checking rollouts again @@ -370,7 +370,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { rolloutManagement.checkRunningRollouts(0); // finish running actions, 2 actions should be finished assertThat(changeStatusForAllRunningActions(createdRollout, Status.FINISHED)).isEqualTo(2); - assertThat(rolloutManagement.findRolloutById(createdRollout.getId()).getStatus()) + assertThat(rolloutManagement.findRolloutById(createdRollout.getId()).get().getStatus()) .isEqualTo(RolloutStatus.RUNNING); } @@ -385,7 +385,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { .forEach(group -> assertThat(group.getStatus()).isEqualTo(RolloutGroupStatus.FINISHED)); // verify that rollout itself is in finished state - final Rollout findRolloutById = rolloutManagement.findRolloutById(createdRollout.getId()); + final Rollout findRolloutById = rolloutManagement.findRolloutById(createdRollout.getId()).get(); assertThat(findRolloutById.getStatus()).isEqualTo(RolloutStatus.FINISHED); } @@ -508,7 +508,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { // round(7/3)=2 targets running (Group 3) // round(5/2)=3 targets SCHEDULED (Group 3) // round(2/1)=2 targets SCHEDULED (Group 4) - createdRollout = rolloutManagement.findRolloutById(createdRollout.getId()); + createdRollout = rolloutManagement.findRolloutById(createdRollout.getId()).get(); final List rolloutGroups = createdRollout.getRolloutGroups(); Map expectedTargetCountStatus = createInitStatusMap(); @@ -542,7 +542,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { successCondition, errorCondition); final DistributionSet ds = createdRollout.getDistributionSet(); - createdRollout = rolloutManagement.findRolloutById(createdRollout.getId()); + createdRollout = rolloutManagement.findRolloutById(createdRollout.getId()).get(); // 5 targets are running final List runningActions = findActionsByRolloutAndStatus(createdRollout, Status.RUNNING); assertThat(runningActions.size()).isEqualTo(5); @@ -584,7 +584,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { Rollout rolloutOne = createAndStartRollout(amountTargetsForRollout, amountOtherTargets, amountGroups, successCondition, errorCondition); - rolloutOne = rolloutManagement.findRolloutById(rolloutOne.getId()); + rolloutOne = rolloutManagement.findRolloutById(rolloutOne.getId()).get(); final DistributionSet dsForRolloutTwo = testdataFactory.createDistributionSet("dsForRolloutTwo"); @@ -626,7 +626,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { successCondition, errorCondition); final DistributionSet distributionSet = rolloutOne.getDistributionSet(); - rolloutOne = rolloutManagement.findRolloutById(rolloutOne.getId()); + rolloutOne = rolloutManagement.findRolloutById(rolloutOne.getId()).get(); changeStatusForRunningActions(rolloutOne, Status.ERROR, 2); changeStatusForRunningActions(rolloutOne, Status.FINISHED, 3); rolloutManagement.checkRunningRollouts(0); @@ -643,7 +643,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { expectedTargetCountStatus.put(TotalTargetCountStatus.Status.ERROR, 6L); validateRolloutActionStatus(rolloutOne.getId(), expectedTargetCountStatus); // rollout is finished - rolloutOne = rolloutManagement.findRolloutById(rolloutOne.getId()); + rolloutOne = rolloutManagement.findRolloutById(rolloutOne.getId()).get(); assertThat(rolloutOne.getStatus()).isEqualTo(RolloutStatus.FINISHED); final int amountGroupsForRolloutTwo = 1; @@ -655,7 +655,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { // Run here, because scheduler is disabled during tests rolloutManagement.checkStartingRollouts(0); - rolloutTwo = rolloutManagement.findRolloutById(rolloutTwo.getId()); + rolloutTwo = rolloutManagement.findRolloutById(rolloutTwo.getId()).get(); // 6 error targets are know running expectedTargetCountStatus = createInitStatusMap(); expectedTargetCountStatus.put(TotalTargetCountStatus.Status.RUNNING, 6L); @@ -684,7 +684,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { Rollout rolloutOne = createAndStartRollout(amountTargetsForRollout, amountOtherTargets, amountGroups, successCondition, errorCondition); - rolloutOne = rolloutManagement.findRolloutById(rolloutOne.getId()); + rolloutOne = rolloutManagement.findRolloutById(rolloutOne.getId()).get(); changeStatusForRunningActions(rolloutOne, Status.ERROR, 2); changeStatusForRunningActions(rolloutOne, Status.FINISHED, 3); rolloutManagement.checkRunningRollouts(0); @@ -708,13 +708,13 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { Rollout rolloutOne = createAndStartRollout(amountTargetsForRollout, amountOtherTargets, amountGroups, successCondition, errorCondition); - rolloutOne = rolloutManagement.findRolloutById(rolloutOne.getId()); + rolloutOne = rolloutManagement.findRolloutById(rolloutOne.getId()).get(); changeStatusForRunningActions(rolloutOne, Status.ERROR, 2); changeStatusForRunningActions(rolloutOne, Status.FINISHED, 3); rolloutManagement.checkRunningRollouts(0); // verify: 40% error and 60% finished -> should not move to next group // because successCondition 80% - rolloutOne = rolloutManagement.findRolloutById(rolloutOne.getId()); + rolloutOne = rolloutManagement.findRolloutById(rolloutOne.getId()).get(); final List rolloutGruops = rolloutOne.getRolloutGroups(); final Map expectedTargetCountStatus = createInitStatusMap(); expectedTargetCountStatus.put(TotalTargetCountStatus.Status.SCHEDULED, 5L); @@ -733,12 +733,12 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { Rollout rolloutOne = createAndStartRollout(amountTargetsForRollout, amountOtherTargets, amountGroups, successCondition, errorCondition); - rolloutOne = rolloutManagement.findRolloutById(rolloutOne.getId()); + rolloutOne = rolloutManagement.findRolloutById(rolloutOne.getId()).get(); changeStatusForRunningActions(rolloutOne, Status.ERROR, 2); changeStatusForRunningActions(rolloutOne, Status.FINISHED, 3); rolloutManagement.checkRunningRollouts(0); // verify: 40% error -> should pause because errorCondition is 20% - rolloutOne = rolloutManagement.findRolloutById(rolloutOne.getId()); + rolloutOne = rolloutManagement.findRolloutById(rolloutOne.getId()).get(); assertThat(RolloutStatus.PAUSED).isEqualTo(rolloutOne.getStatus()); } @@ -896,7 +896,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { final Rollout rolloutCreated = createTestRolloutWithTargetsAndDistributionSet(amountTargetsForRollout, amountGroups, successCondition, errorCondition, rolloutName, "RolloutA"); - final Rollout rolloutFound = rolloutManagement.findRolloutByName(rolloutName); + final Rollout rolloutFound = rolloutManagement.findRolloutByName(rolloutName).get(); assertThat(rolloutCreated).isEqualTo(rolloutFound); } @@ -919,7 +919,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { changeStatusForRunningActions(myRollout, Status.FINISHED, 2); rolloutManagement.checkRunningRollouts(0); - myRollout = rolloutManagement.findRolloutById(myRollout.getId()); + myRollout = rolloutManagement.findRolloutById(myRollout.getId()).get(); float percent = rolloutManagement.getFinishedPercentForRunningGroup(myRollout.getId(), myRollout.getRolloutGroups().get(0).getId()); @@ -963,7 +963,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { // Run here, because scheduler is disabled during tests rolloutManagement.checkStartingRollouts(0); - myRollout = rolloutManagement.findRolloutById(myRollout.getId()); + myRollout = rolloutManagement.findRolloutById(myRollout.getId()).get(); final List rolloutGroups = myRollout.getRolloutGroups(); Page targetPage = rolloutGroupManagement.findRolloutGroupTargets(rolloutGroups.get(0).getId(), @@ -1070,7 +1070,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { assertThat(MultipleInvokeHelper.doWithTimeout(new RolloutStatusCallable(myRollout.getId()), conditionRolloutStatus, 15000, 500)).as("Rollout status").isNotNull(); - myRollout = rolloutManagement.findRolloutById(myRollout.getId()); + myRollout = rolloutManagement.findRolloutById(myRollout.getId()).get(); assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.RUNNING); final Map expectedTargetCountStatus = createInitStatusMap(); expectedTargetCountStatus.put(TotalTargetCountStatus.Status.RUNNING, 1L); @@ -1099,7 +1099,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { rolloutManagement.checkReadyRollouts(0); - myRollout = rolloutManagement.findRolloutById(myRollout.getId()); + myRollout = rolloutManagement.findRolloutById(myRollout.getId()).get(); assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.READY); rolloutManagement.startRollout(myRollout.getId()); @@ -1112,7 +1112,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { assertThat(MultipleInvokeHelper.doWithTimeout(new RolloutStatusCallable(myRollout.getId()), conditionRolloutTargetCount, 15000, 500)).as("Rollout status").isNotNull(); - myRollout = rolloutManagement.findRolloutById(myRollout.getId()); + myRollout = rolloutManagement.findRolloutById(myRollout.getId()).get(); assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.RUNNING); final Map expectedTargetCountStatus = createInitStatusMap(); expectedTargetCountStatus.put(TotalTargetCountStatus.Status.RUNNING, 100L); @@ -1144,15 +1144,15 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { rolloutManagement.checkReadyRollouts(0); // rollout should not have been started - myRollout = rolloutManagement.findRolloutById(myRollout.getId()); + myRollout = rolloutManagement.findRolloutById(myRollout.getId()).get(); assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.READY); // schedule to now - rolloutManagement.updateRollout( - entityFactory.rollout().update(myRollout.getId()).startAt(System.currentTimeMillis())); + rolloutManagement + .updateRollout(entityFactory.rollout().update(myRollout.getId()).startAt(System.currentTimeMillis())); rolloutManagement.checkReadyRollouts(0); - myRollout = rolloutManagement.findRolloutById(myRollout.getId()); + myRollout = rolloutManagement.findRolloutById(myRollout.getId()).get(); assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.STARTING); // Run here, because scheduler is disabled during tests @@ -1163,7 +1163,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { assertThat(MultipleInvokeHelper.doWithTimeout(new RolloutStatusCallable(myRollout.getId()), conditionRolloutTargetCount, 15000, 500)).as("Rollout status").isNotNull(); - myRollout = rolloutManagement.findRolloutById(myRollout.getId()); + myRollout = rolloutManagement.findRolloutById(myRollout.getId()).get(); assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.RUNNING); final Map expectedTargetCountStatus = createInitStatusMap(); expectedTargetCountStatus.put(TotalTargetCountStatus.Status.RUNNING, 100L); @@ -1200,7 +1200,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { rolloutGroups.add(generateRolloutGroup(2, percentTargetsInGroup3, null)); Rollout myRollout = rolloutManagement.createRollout(rolloutcreate, rolloutGroups, conditions); - myRollout = rolloutManagement.findRolloutById(myRollout.getId()); + myRollout = rolloutManagement.findRolloutById(myRollout.getId()).get(); assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.CREATING); for (final RolloutGroup group : myRollout.getRolloutGroups()) { @@ -1214,7 +1214,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { rolloutManagement.fillRolloutGroupsWithTargets(myRollout.getId()); - myRollout = rolloutManagement.findRolloutById(myRollout.getId()); + myRollout = rolloutManagement.findRolloutById(myRollout.getId()).get(); assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.READY); assertThat(myRollout.getTotalTargets()).isEqualTo(amountTargetsInGroup1and2 + amountTargetsInGroup1); @@ -1318,7 +1318,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { .set(distributionSet); Rollout myRollout = rolloutManagement.createRollout(rolloutToCreate, amountGroups, conditions); - myRollout = rolloutManagement.findRolloutById(myRollout.getId()); + myRollout = rolloutManagement.findRolloutById(myRollout.getId()).get(); assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.CREATING); @@ -1351,13 +1351,13 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { private void validateRolloutGroupActionStatus(final RolloutGroup rolloutGroup, final Map expectedTargetCountStatus) { final RolloutGroup rolloutGroupWithDetail = rolloutGroupManagement - .findRolloutGroupWithDetailedStatus(rolloutGroup.getId()); + .findRolloutGroupWithDetailedStatus(rolloutGroup.getId()).get(); validateStatus(rolloutGroupWithDetail.getTotalTargetCountStatus(), expectedTargetCountStatus); } private void validateRolloutActionStatus(final Long rolloutId, final Map expectedTargetCountStatus) { - final Rollout rolloutWithDetail = rolloutManagement.findRolloutWithDetailedStatus(rolloutId); + final Rollout rolloutWithDetail = rolloutManagement.findRolloutWithDetailedStatus(rolloutId).get(); validateStatus(rolloutWithDetail.getTotalTargetCountStatus(), expectedTargetCountStatus); } @@ -1447,7 +1447,7 @@ public class RolloutManagementTest extends AbstractJpaIntegrationTest { @Override public RolloutStatus call() throws Exception { - final Rollout myRollout = rolloutManagement.findRolloutById(rolloutId); + final Rollout myRollout = rolloutManagement.findRolloutById(rolloutId).get(); return myRollout.getStatus(); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SoftwareManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SoftwareManagementTest.java index d2904d9b2..7ae99fdcd 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SoftwareManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SoftwareManagementTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa; -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.junit.Assert.fail; @@ -23,7 +23,6 @@ import javax.validation.ConstraintViolationException; import org.apache.commons.lang3.RandomUtils; import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeCreate; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; -import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.jpa.model.JpaArtifact; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleMetadata; @@ -187,11 +186,11 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest { private Action assignSet(final JpaTarget target, final JpaDistributionSet ds) { assignDistributionSet(ds.getId(), target.getControllerId()); + assertThat(targetManagement.findTargetByControllerID(target.getControllerId()).get().getTargetInfo() + .getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING); assertThat( - targetManagement.findTargetByControllerID(target.getControllerId()).getTargetInfo().getUpdateStatus()) - .isEqualTo(TargetUpdateStatus.PENDING); - assertThat(targetManagement.findTargetByControllerID(target.getControllerId()).getAssignedDistributionSet()) - .isEqualTo(ds); + targetManagement.findTargetByControllerID(target.getControllerId()).get().getAssignedDistributionSet()) + .isEqualTo(ds); final Action action = actionRepository.findByTargetAndDistributionSet(pageReq, target, ds).getContent().get(0); assertThat(action).isNotNull(); return action; @@ -290,7 +289,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest { // [VERIFY EXPECTED RESULT]: // verify: SoftwareModule is deleted assertThat(softwareModuleRepository.findAll()).hasSize(0); - assertThat(softwareManagement.findSoftwareModuleById(unassignedModule.getId())).isNull(); + assertThat(softwareManagement.findSoftwareModuleById(unassignedModule.getId()).isPresent()).isFalse(); // verify: binary data of artifact is deleted assertArtfiactNull(artifact1, artifact2); @@ -315,7 +314,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest { // [VERIFY EXPECTED RESULT]: // verify: assignedModule is marked as deleted - assignedModule = softwareManagement.findSoftwareModuleById(assignedModule.getId()); + assignedModule = softwareManagement.findSoftwareModuleById(assignedModule.getId()).get(); assertTrue("The module should be flagged as deleted", assignedModule.isDeleted()); assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); assertThat(softwareModuleRepository.findAll()).hasSize(1); @@ -355,7 +354,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest { // [VERIFY EXPECTED RESULT]: // verify: assignedModule is marked as deleted - assignedModule = softwareManagement.findSoftwareModuleById(assignedModule.getId()); + assignedModule = softwareManagement.findSoftwareModuleById(assignedModule.getId()).get(); assertTrue("The found module should be flagged deleted", assignedModule.isDeleted()); assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0); assertThat(softwareModuleRepository.findAll()).hasSize(1); @@ -383,7 +382,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest { // [STEP2]: Create newArtifactX and add it to SoftwareModuleX artifactManagement.createArtifact(new ByteArrayInputStream(source), moduleX.getId(), "artifactx", false); - moduleX = softwareManagement.findSoftwareModuleById(moduleX.getId()); + moduleX = softwareManagement.findSoftwareModuleById(moduleX.getId()).get(); final Artifact artifactX = moduleX.getArtifacts().iterator().next(); // [STEP3]: Create SoftwareModuleY and add the same ArtifactX @@ -391,7 +390,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest { // [STEP4]: Assign the same ArtifactX to SoftwareModuleY artifactManagement.createArtifact(new ByteArrayInputStream(source), moduleY.getId(), "artifactx", false); - moduleY = softwareManagement.findSoftwareModuleById(moduleY.getId()); + moduleY = softwareManagement.findSoftwareModuleById(moduleY.getId()).get(); final Artifact artifactY = moduleY.getArtifacts().iterator().next(); // [STEP5]: Delete SoftwareModuleX @@ -400,8 +399,8 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest { // [VERIFY EXPECTED RESULT]: // verify: SoftwareModuleX is deleted, and ModuelY still exists assertThat(softwareModuleRepository.findAll()).hasSize(1); - assertThat(softwareManagement.findSoftwareModuleById(moduleX.getId())).isNull(); - assertThat(softwareManagement.findSoftwareModuleById(moduleY.getId())).isNotNull(); + assertThat(softwareManagement.findSoftwareModuleById(moduleX.getId()).isPresent()).isFalse(); + assertThat(softwareManagement.findSoftwareModuleById(moduleY.getId()).isPresent()).isTrue(); // verify: binary data of artifact is not deleted assertArtfiactNotNull(artifactY); @@ -425,14 +424,14 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest { SoftwareModule moduleX = createSoftwareModuleWithArtifacts(osType, "modulex", "v1.0", 0); artifactManagement.createArtifact(new ByteArrayInputStream(source), moduleX.getId(), "artifactx", false); - moduleX = softwareManagement.findSoftwareModuleById(moduleX.getId()); + moduleX = softwareManagement.findSoftwareModuleById(moduleX.getId()).get(); final Artifact artifactX = moduleX.getArtifacts().iterator().next(); // [STEP2]: Create SoftwareModuleY and add the same ArtifactX SoftwareModule moduleY = createSoftwareModuleWithArtifacts(osType, "moduley", "v1.0", 0); artifactManagement.createArtifact(new ByteArrayInputStream(source), moduleY.getId(), "artifactx", false); - moduleY = softwareManagement.findSoftwareModuleById(moduleY.getId()); + moduleY = softwareManagement.findSoftwareModuleById(moduleY.getId()).get(); final Artifact artifactY = moduleY.getArtifacts().iterator().next(); // [STEP3]: Assign SoftwareModuleX to DistributionSetX and to target @@ -450,8 +449,8 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest { softwareManagement.deleteSoftwareModule(moduleY.getId()); // [VERIFY EXPECTED RESULT]: - moduleX = softwareManagement.findSoftwareModuleById(moduleX.getId()); - moduleY = softwareManagement.findSoftwareModuleById(moduleY.getId()); + moduleX = softwareManagement.findSoftwareModuleById(moduleX.getId()).get(); + moduleY = softwareManagement.findSoftwareModuleById(moduleY.getId()).get(); // verify: SoftwareModuleX and SofwtareModule are marked as deleted assertThat(moduleX).isNotNull(); @@ -483,7 +482,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest { } // Verify correct Creation of SoftwareModule and corresponding artifacts - softwareModule = softwareManagement.findSoftwareModuleById(softwareModule.getId()); + softwareModule = softwareManagement.findSoftwareModuleById(softwareModule.getId()).get(); assertThat(softwareModuleRepository.findAll()).hasSize((int) countSoftwareModule + 1); final List artifacts = softwareModule.getArtifacts(); @@ -623,7 +622,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest { softwareManagement.createSoftwareModuleType( entityFactory.softwareModuleType().create().key("thetype2").name("anothername")); - assertThat(softwareManagement.findSoftwareModuleTypeByName("thename")).as("Type with given name") + assertThat(softwareManagement.findSoftwareModuleTypeByName("thename").get()).as("Type with given name") .isEqualTo(found); } @@ -718,7 +717,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest { final List softwareModuleMetadata = softwareManagement .createSoftwareModuleMetadata(ah.getId(), Lists.newArrayList(swMetadata1, swMetadata2)); - final SoftwareModule changedLockRevisionModule = softwareManagement.findSoftwareModuleById(ah.getId()); + final SoftwareModule changedLockRevisionModule = softwareManagement.findSoftwareModuleById(ah.getId()).get(); assertThat(changedLockRevisionModule.getOptLockRevision()).isEqualTo(2); assertThat(softwareModuleMetadata).hasSize(2); @@ -770,7 +769,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest { // base software module should have now the opt lock revision one // because we are modifying the // base software module - SoftwareModule changedLockRevisionModule = softwareManagement.findSoftwareModuleById(ah.getId()); + SoftwareModule changedLockRevisionModule = softwareManagement.findSoftwareModuleById(ah.getId()).get(); assertThat(changedLockRevisionModule.getOptLockRevision()).isEqualTo(2); // update the software module metadata @@ -780,7 +779,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest { // we are updating the sw meta data so also modiying the base software // module so opt lock // revision must be two - changedLockRevisionModule = softwareManagement.findSoftwareModuleById(ah.getId()); + changedLockRevisionModule = softwareManagement.findSoftwareModuleById(ah.getId()).get(); assertThat(changedLockRevisionModule.getOptLockRevision()).isEqualTo(3); // verify updated meta data contains the updated value @@ -823,12 +822,7 @@ public class SoftwareManagementTest extends AbstractJpaIntegrationTest { .createSoftwareModuleMetadata(ah.getId(), entityFactory.generateMetadata(knownKey1, knownValue1)) .getSoftwareModule(); - try { - softwareManagement.findSoftwareModuleMetadata(ah.getId(), "doesnotexist"); - fail("should not have worked as module metadata with that key does not exist"); - } catch (final EntityNotFoundException e) { - - } + assertThat(softwareManagement.findSoftwareModuleMetadata(ah.getId(), "doesnotexist").isPresent()).isFalse(); } @Test diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SystemManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SystemManagementTest.java index b488ee14d..7002a96f9 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SystemManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/SystemManagementTest.java @@ -8,15 +8,15 @@ */ package org.eclipse.hawkbit.repository.jpa; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayInputStream; import java.util.List; import java.util.Random; import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; -import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.report.model.TenantUsage; import org.eclipse.hawkbit.repository.test.util.WithSpringAuthorityRule; @@ -131,9 +131,7 @@ public class SystemManagementTest extends AbstractJpaIntegrationTest { } private void createTestArtifact(final byte[] random) { - JpaSoftwareModule sm = new JpaSoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", - "version 1", null, null); - sm = softwareModuleRepository.save(sm); + final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); artifactManagement.createArtifact(new ByteArrayInputStream(random), sm.getId(), "file1", false); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TagManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TagManagementTest.java index 0e0814565..9def440cc 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TagManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TagManagementTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa; -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.fail; @@ -72,18 +72,18 @@ public class TagManagementTest extends AbstractJpaIntegrationTest { toggleTagAssignment(dsBs, tagB); toggleTagAssignment(dsCs, tagC); - toggleTagAssignment(dsABs, tagManagement.findDistributionSetTag(tagA.getName())); - toggleTagAssignment(dsABs, tagManagement.findDistributionSetTag(tagB.getName())); + toggleTagAssignment(dsABs, tagManagement.findDistributionSetTag(tagA.getName()).get()); + toggleTagAssignment(dsABs, tagManagement.findDistributionSetTag(tagB.getName()).get()); - toggleTagAssignment(dsACs, tagManagement.findDistributionSetTag(tagA.getName())); - toggleTagAssignment(dsACs, tagManagement.findDistributionSetTag(tagC.getName())); + toggleTagAssignment(dsACs, tagManagement.findDistributionSetTag(tagA.getName()).get()); + toggleTagAssignment(dsACs, tagManagement.findDistributionSetTag(tagC.getName()).get()); - toggleTagAssignment(dsBCs, tagManagement.findDistributionSetTag(tagB.getName())); - toggleTagAssignment(dsBCs, tagManagement.findDistributionSetTag(tagC.getName())); + toggleTagAssignment(dsBCs, tagManagement.findDistributionSetTag(tagB.getName()).get()); + toggleTagAssignment(dsBCs, tagManagement.findDistributionSetTag(tagC.getName()).get()); - toggleTagAssignment(dsABCs, tagManagement.findDistributionSetTag(tagA.getName())); - toggleTagAssignment(dsABCs, tagManagement.findDistributionSetTag(tagB.getName())); - toggleTagAssignment(dsABCs, tagManagement.findDistributionSetTag(tagC.getName())); + toggleTagAssignment(dsABCs, tagManagement.findDistributionSetTag(tagA.getName()).get()); + toggleTagAssignment(dsABCs, tagManagement.findDistributionSetTag(tagB.getName()).get()); + toggleTagAssignment(dsABCs, tagManagement.findDistributionSetTag(tagC.getName()).get()); DistributionSetFilterBuilder distributionSetFilterBuilder; @@ -259,9 +259,11 @@ public class TagManagementTest extends AbstractJpaIntegrationTest { final Tag tag = tagManagement .createTargetTag(entityFactory.tag().create().name("kai1").description("kai2").colour("colour")); - assertThat(targetTagRepository.findByNameEquals("kai1").getDescription()).as("wrong tag ed").isEqualTo("kai2"); - assertThat(tagManagement.findTargetTag("kai1").getColour()).as("wrong tag found").isEqualTo("colour"); - assertThat(tagManagement.findTargetTagById(tag.getId()).getColour()).as("wrong tag found").isEqualTo("colour"); + assertThat(targetTagRepository.findByNameEquals("kai1").get().getDescription()).as("wrong tag ed") + .isEqualTo("kai2"); + assertThat(tagManagement.findTargetTag("kai1").get().getColour()).as("wrong tag found").isEqualTo("colour"); + assertThat(tagManagement.findTargetTagById(tag.getId()).get().getColour()).as("wrong tag found") + .isEqualTo("colour"); } @Test @@ -273,7 +275,7 @@ public class TagManagementTest extends AbstractJpaIntegrationTest { final TargetTag toDelete = tags.iterator().next(); for (final Target target : targetRepository.findAll()) { - assertThat(targetManagement.findTargetByControllerID(target.getControllerId()).getTags()) + assertThat(targetManagement.findTargetByControllerID(target.getControllerId()).get().getTags()) .contains(toDelete); } @@ -282,7 +284,7 @@ public class TagManagementTest extends AbstractJpaIntegrationTest { // check for (final Target target : targetRepository.findAll()) { - assertThat(targetManagement.findTargetByControllerID(target.getControllerId()).getTags()) + assertThat(targetManagement.findTargetByControllerID(target.getControllerId()).get().getTags()) .doesNotContain(toDelete); } assertThat(targetTagRepository.findOne(toDelete.getId())).as("No tag should be found").isNull(); @@ -314,10 +316,11 @@ public class TagManagementTest extends AbstractJpaIntegrationTest { final Tag tag = tagManagement.createDistributionSetTag( entityFactory.tag().create().name("kai1").description("kai2").colour("colour")); - assertThat(distributionSetTagRepository.findByNameEquals("kai1").getDescription()).as("wrong tag found") + assertThat(distributionSetTagRepository.findByNameEquals("kai1").get().getDescription()).as("wrong tag found") .isEqualTo("kai2"); - assertThat(tagManagement.findDistributionSetTag("kai1").getColour()).as("wrong tag found").isEqualTo("colour"); - assertThat(tagManagement.findDistributionSetTagById(tag.getId()).getColour()).as("wrong tag found") + assertThat(tagManagement.findDistributionSetTag("kai1").get().getColour()).as("wrong tag found") + .isEqualTo("colour"); + assertThat(tagManagement.findDistributionSetTagById(tag.getId()).get().getColour()).as("wrong tag found") .isEqualTo("colour"); } @@ -337,7 +340,7 @@ public class TagManagementTest extends AbstractJpaIntegrationTest { final DistributionSetTag toDelete = tags.iterator().next(); for (final DistributionSet set : distributionSetRepository.findAll()) { - assertThat(distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()).getTags()) + assertThat(distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()).get().getTags()) .as("Wrong tag found").contains(toDelete); } @@ -348,7 +351,7 @@ public class TagManagementTest extends AbstractJpaIntegrationTest { assertThat(distributionSetTagRepository.findOne(toDelete.getId())).as("Deleted tag should be null").isNull(); assertThat(tagManagement.findAllDistributionSetTags()).as("Wrong size of tags after deletion").hasSize(19); for (final DistributionSet set : distributionSetRepository.findAll()) { - assertThat(distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()).getTags()) + assertThat(distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()).get().getTags()) .as("Wrong found tags").doesNotContain(toDelete); } } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryManagementTest.java index 5f7a4cfdd..ecaea960f 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetFilterQueryManagementTest.java @@ -8,8 +8,9 @@ */ package org.eclipse.hawkbit.repository.jpa; -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.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -47,7 +48,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement.createTargetFilterQuery( entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001")); assertEquals("Retrieved newly created custom target filter", targetFilterQuery, - targetFilterQueryManagement.findTargetFilterQueryByName(filterName)); + targetFilterQueryManagement.findTargetFilterQueryByName(filterName).get()); } @Test @@ -98,8 +99,8 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement.createTargetFilterQuery( entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001")); targetFilterQueryManagement.deleteTargetFilterQuery(targetFilterQuery.getId()); - assertEquals("Returns null as the target filter is deleted", null, - targetFilterQueryManagement.findTargetFilterQueryById(targetFilterQuery.getId())); + assertFalse("Returns null as the target filter is deleted", + targetFilterQueryManagement.findTargetFilterQueryById(targetFilterQuery.getId()).isPresent()); } @@ -114,7 +115,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest targetFilterQueryManagement.updateTargetFilterQuery( entityFactory.targetFilterQuery().update(targetFilterQuery.getId()).query(newQuery)); assertEquals("Returns updated target filter query", newQuery, - targetFilterQueryManagement.findTargetFilterQueryByName(filterName).getQuery()); + targetFilterQueryManagement.findTargetFilterQueryByName(filterName).get().getQuery()); } @@ -130,7 +131,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest targetFilterQueryManagement.updateTargetFilterQueryAutoAssignDS(targetFilterQuery.getId(), distributionSet.getId()); - final TargetFilterQuery tfq = targetFilterQueryManagement.findTargetFilterQueryByName(filterName); + final TargetFilterQuery tfq = targetFilterQueryManagement.findTargetFilterQueryByName(filterName).get(); assertEquals("Returns correct distribution set", distributionSet, tfq.getAutoAssignDistributionSet()); @@ -149,13 +150,13 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest distributionSet.getId()); // Check if target filter query is there - TargetFilterQuery tfq = targetFilterQueryManagement.findTargetFilterQueryByName(filterName); + TargetFilterQuery tfq = targetFilterQueryManagement.findTargetFilterQueryByName(filterName).get(); assertEquals("Returns correct distribution set", distributionSet, tfq.getAutoAssignDistributionSet()); distributionSetManagement.deleteDistributionSet(distributionSet.getId()); // Check if auto assign distribution set is null - tfq = targetFilterQueryManagement.findTargetFilterQueryByName(filterName); + tfq = targetFilterQueryManagement.findTargetFilterQueryByName(filterName).get(); assertNotNull("Returns target filter query", tfq); assertNull("Returns distribution set as null", tfq.getAutoAssignDistributionSet()); @@ -178,17 +179,17 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest .getId(), distributionSet.getId()); // Check if target filter query is there with the distribution set - TargetFilterQuery tfq = targetFilterQueryManagement.findTargetFilterQueryByName(filterName); + TargetFilterQuery tfq = targetFilterQueryManagement.findTargetFilterQueryByName(filterName).get(); assertEquals("Returns correct distribution set", distributionSet, tfq.getAutoAssignDistributionSet()); distributionSetManagement.deleteDistributionSet(distributionSet.getId()); // Check if distribution set is still in the database with deleted flag assertTrue("Distribution set should be deleted", - distributionSetManagement.findDistributionSetById(distributionSet.getId()).isDeleted()); + distributionSetManagement.findDistributionSetById(distributionSet.getId()).get().isDeleted()); // Check if auto assign distribution set is null - tfq = targetFilterQueryManagement.findTargetFilterQueryByName(filterName); + tfq = targetFilterQueryManagement.findTargetFilterQueryByName(filterName).get(); assertNotNull("Returns target filter query", tfq); assertNull("Returns distribution set as null", tfq.getAutoAssignDistributionSet()); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementSearchTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementSearchTest.java index 54c8d0119..c1f72e6a6 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementSearchTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementSearchTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.time.Instant; import java.util.ArrayList; @@ -118,12 +118,13 @@ public class TargetManagementSearchTest extends AbstractJpaIntegrationTest { verifyThatRepositoryContains400Targets(); verifyThat200TargetsHaveTagD(targTagW, concat(targBs, targCs)); verifyThat100TargetsContainsGivenTextAndHaveTagAssigned(targTagY, targTagW, targBs); - verifyThat1TargetHasTagHasDescOrNameAndDs(targTagW, setA, targetManagement.findTargetByControllerID(assignedC)); + verifyThat1TargetHasTagHasDescOrNameAndDs(targTagW, setA, + targetManagement.findTargetByControllerID(assignedC).get()); verifyThat0TargetsWithTagAndDescOrNameHasDS(targTagW, setA); verifyThat0TargetsWithNameOrdescAndDSHaveTag(targTagX, setA); verifyThat3TargetsHaveDSAssigned(setA, targetManagement.findTargetByControllerID(Lists.newArrayList(assignedA, assignedB, assignedC))); - verifyThat1TargetWithDescOrNameHasDS(setA, targetManagement.findTargetByControllerID(assignedA)); + verifyThat1TargetWithDescOrNameHasDS(setA, targetManagement.findTargetByControllerID(assignedA).get()); List expected = concat(targAs, targBs, targCs, targDs); expected.removeAll( targetManagement.findTargetByControllerID(Lists.newArrayList(assignedA, assignedB, assignedC))); @@ -133,26 +134,26 @@ public class TargetManagementSearchTest extends AbstractJpaIntegrationTest { verifyThat198TargetsAreInStatusUnknownAndHaveGivenTags(targTagY, targTagW, unknown, expected); verfyThat0TargetsAreInStatusUnknownAndHaveDSAssigned(setA, unknown); expected = concat(targAs); - expected.remove(targetManagement.findTargetByControllerID(assignedA)); + expected.remove(targetManagement.findTargetByControllerID(assignedA).get()); verifyThat99TargetsWithNameOrDescriptionAreInGivenStatus(unknown, expected); expected = concat(targBs); - expected.remove(targetManagement.findTargetByControllerID(assignedB)); + expected.remove(targetManagement.findTargetByControllerID(assignedB).get()); verifyThat99TargetsWithGivenNameOrDescAndTagAreInStatusUnknown(targTagW, unknown, expected); verifyThat3TargetsAreInStatusPending(pending, targetManagement.findTargetByControllerID(Lists.newArrayList(assignedA, assignedB, assignedC))); verifyThat3TargetsWithGivenDSAreInPending(setA, pending, targetManagement.findTargetByControllerID(Lists.newArrayList(assignedA, assignedB, assignedC))); verifyThat1TargetWithGivenNameOrDescAndDSIsInPending(setA, pending, - targetManagement.findTargetByControllerID(assignedA)); + targetManagement.findTargetByControllerID(assignedA).get()); verifyThat1TargetWithGivenNameOrDescAndTagAndDSIsInPending(targTagW, setA, pending, - targetManagement.findTargetByControllerID(assignedB)); + targetManagement.findTargetByControllerID(assignedB).get()); verifyThat2TargetsWithGivenTagAndDSIsInPending(targTagW, setA, pending, targetManagement.findTargetByControllerID(Lists.newArrayList(assignedB, assignedC))); verifyThat2TargetsWithGivenTagAreInPending(targTagW, pending, targetManagement.findTargetByControllerID(Lists.newArrayList(assignedB, assignedC))); verifyThat200targetsWithGivenTagAreInStatusPendingorUnknown(targTagW, both, concat(targBs, targCs)); verfiyThat1TargetAIsInStatusPendingAndHasDSInstalled(installedSet, pending, - targetManagement.findTargetByControllerID(installedC)); + targetManagement.findTargetByControllerID(installedC).get()); expected = concat(targBs, targCs); expected.removeAll(targetManagement.findTargetByControllerID(Lists.newArrayList(assignedB, assignedC))); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementTest.java index 24c9df37a..9eeb2c6ac 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TargetManagementTest.java @@ -12,7 +12,7 @@ import static com.google.common.collect.Iterables.limit; import static com.google.common.collect.Iterables.toArray; import static com.google.common.collect.Lists.newArrayList; import static java.util.stream.Collectors.toList; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; @@ -197,7 +197,7 @@ public class TargetManagementTest extends AbstractJpaIntegrationTest { assertThat(assignedTargets.size()).as("Assigned targets are wrong").isEqualTo(4); assignedTargets.forEach(target -> assertThat(target.getTags().size()).isEqualTo(1)); - TargetTag findTargetTag = tagManagement.findTargetTag("Tag1"); + TargetTag findTargetTag = tagManagement.findTargetTag("Tag1").get(); assertThat(assignedTargets.size()).as("Assigned targets are wrong") .isEqualTo(findTargetTag.getAssignedToTargets().size()); @@ -207,11 +207,11 @@ public class TargetManagementTest extends AbstractJpaIntegrationTest { final Target unAssignTarget = targetManagement.unAssignTag("targetId123", findTargetTag.getId()); assertThat(unAssignTarget.getControllerId()).as("Controller id is wrong").isEqualTo("targetId123"); assertThat(unAssignTarget.getTags()).as("Tag size is wrong").isEmpty(); - findTargetTag = tagManagement.findTargetTag("Tag1"); + findTargetTag = tagManagement.findTargetTag("Tag1").get(); assertThat(findTargetTag.getAssignedToTargets()).as("Assigned targets are wrong").hasSize(3); final List unAssignTargets = targetManagement.unAssignAllTargetsByTag(findTargetTag.getId()); - findTargetTag = tagManagement.findTargetTag("Tag1"); + findTargetTag = tagManagement.findTargetTag("Tag1").get(); assertThat(findTargetTag.getAssignedToTargets()).as("Unassigned targets are wrong").isEmpty(); assertThat(unAssignTargets).as("Unassigned targets are wrong").hasSize(3); unAssignTargets.forEach(target -> assertThat(target.getTags().size()).isEqualTo(0)); @@ -250,7 +250,7 @@ public class TargetManagementTest extends AbstractJpaIntegrationTest { targetManagement.createTarget(entityFactory.target().create().controllerId(controllerId)); controllerManagament.updateControllerAttributes(controllerId, testData); - final Target target = targetManagement.findTargetByControllerIDWithDetails(controllerId); + final Target target = targetManagement.findTargetByControllerIDWithDetails(controllerId).get(); assertThat(target.getTargetInfo().getControllerAttributes()).as("Controller Attributes are wrong") .isEqualTo(testData); return target; @@ -287,7 +287,7 @@ public class TargetManagementTest extends AbstractJpaIntegrationTest { entityFactory.actionStatus().create(result.getActions().get(0)).status(Status.FINISHED)); assignDistributionSet(set2.getId(), "4711"); - target = targetManagement.findTargetByControllerIDWithDetails("4711"); + target = targetManagement.findTargetByControllerIDWithDetails("4711").get(); // read data assertThat(targetManagement.countTargetByAssignedDistributionSet(set.getId())).as("Target count is wrong") @@ -308,7 +308,7 @@ public class TargetManagementTest extends AbstractJpaIntegrationTest { @Test @Description("Ensures that repositoy returns null if given controller ID does not exist without exception.") public void findTargetByControllerIDWithDetailsReturnsNullForNonexisting() { - assertThat(targetManagement.findTargetByControllerIDWithDetails("dsfsdfsdfsd")).as("Expected as").isNull(); + assertThat(targetManagement.findTargetByControllerIDWithDetails("dsfsdfsdfsd").isPresent()).isFalse(); } @Test @@ -354,7 +354,7 @@ public class TargetManagementTest extends AbstractJpaIntegrationTest { */ private void checkTargetHasTags(final boolean strict, final Iterable targets, final TargetTag... tags) { _target: for (final Target tl : targets) { - final Target t = targetManagement.findTargetByControllerID(tl.getControllerId()); + final Target t = targetManagement.findTargetByControllerID(tl.getControllerId()).get(); for (final Tag tt : t.getTags()) { for (final Tag tag : tags) { @@ -372,7 +372,7 @@ public class TargetManagementTest extends AbstractJpaIntegrationTest { private void checkTargetHasNotTags(final Iterable targets, final TargetTag... tags) { for (final Target tl : targets) { - final Target t = targetManagement.findTargetByControllerID(tl.getControllerId()); + final Target t = targetManagement.findTargetByControllerID(tl.getControllerId()).get(); for (final Tag tag : tags) { for (final Tag tt : t.getTags()) { @@ -412,7 +412,7 @@ public class TargetManagementTest extends AbstractJpaIntegrationTest { .isNotEqualTo(savedTarget.getLastModifiedAt()); modifiedAt = savedTarget.getLastModifiedAt(); - final Target foundTarget = targetManagement.findTargetByControllerID(savedTarget.getControllerId()); + final Target foundTarget = targetManagement.findTargetByControllerID(savedTarget.getControllerId()).get(); assertNotNull("The target should not be null", foundTarget); assertThat(myCtrlID).as("ControllerId compared with saved controllerId") .isEqualTo(foundTarget.getControllerId()); @@ -506,12 +506,12 @@ public class TargetManagementTest extends AbstractJpaIntegrationTest { final List t2Tags = testdataFactory.createTargetTags(noT2Tags, "tag2"); t2Tags.forEach(tag -> targetManagement.assignTag(Lists.newArrayList(t2.getControllerId()), tag.getId())); - final Target t11 = targetManagement.findTargetByControllerID(t1.getControllerId()); + final Target t11 = targetManagement.findTargetByControllerID(t1.getControllerId()).get(); assertThat(t11.getTags()).as("Tag size is wrong").hasSize(noT1Tags).containsAll(t1Tags); assertThat(t11.getTags()).as("Tag size is wrong").hasSize(noT1Tags) .doesNotContain(Iterables.toArray(t2Tags, TargetTag.class)); - final Target t21 = targetManagement.findTargetByControllerID(t2.getControllerId()); + final Target t21 = targetManagement.findTargetByControllerID(t2.getControllerId()).get(); assertThat(t21.getTags()).as("Tag size is wrong").hasSize(noT2Tags).containsAll(t2Tags); assertThat(t21.getTags()).as("Tag size is wrong").hasSize(noT2Tags) .doesNotContain(Iterables.toArray(t1Tags, TargetTag.class)); @@ -697,7 +697,8 @@ public class TargetManagementTest extends AbstractJpaIntegrationTest { controllerManagament.findOrRegisterTargetIfItDoesNotexist(knownTargetControllerId, new URI("http://127.0.0.1")); securityRule.runAs(WithSpringAuthorityRule.withUser("bumlux", "READ_TARGET"), () -> { - final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownTargetControllerId); + final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownTargetControllerId) + .get(); assertThat(findTargetByControllerID).isNotNull(); assertThat(findTargetByControllerID.getTargetInfo()).isNotNull(); assertThat(findTargetByControllerID.getTargetInfo().getPollStatus()).isNotNull(); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TenantConfigurationManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TenantConfigurationManagementTest.java index ea79e77ca..a25862f96 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TenantConfigurationManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/TenantConfigurationManagementTest.java @@ -8,8 +8,8 @@ */ package org.eclipse.hawkbit.repository.jpa; -import static org.fest.assertions.api.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 java.io.Serializable; import java.time.Duration; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/autoassign/AutoAssignCheckerTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/autoassign/AutoAssignCheckerTest.java index cde3a78d2..3fb91a5a5 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/autoassign/AutoAssignCheckerTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/autoassign/AutoAssignCheckerTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa.autoassign; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.stream.Collectors; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/event/RepositoryEntityEventTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/event/RepositoryEntityEventTest.java index da2205b46..a305bb286 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/event/RepositoryEntityEventTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/event/RepositoryEntityEventTest.java @@ -8,12 +8,13 @@ */ package org.eclipse.hawkbit.repository.jpa.event; -import static org.fest.assertions.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; +import org.assertj.core.api.Assertions; import org.eclipse.hawkbit.repository.event.TenantAwareEvent; import org.eclipse.hawkbit.repository.event.remote.DistributionSetDeletedEvent; import org.eclipse.hawkbit.repository.event.remote.SoftwareModuleDeletedEvent; @@ -28,7 +29,6 @@ import org.eclipse.hawkbit.repository.jpa.event.RepositoryEntityEventTest.Reposi import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.Target; -import org.fest.assertions.api.Assertions; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/model/EntityInterceptorListenerTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/model/EntityInterceptorListenerTest.java index faf6668d4..4c9f6d452 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/model/EntityInterceptorListenerTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/model/EntityInterceptorListenerTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa.model; -import static org.fest.assertions.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; import org.eclipse.hawkbit.repository.jpa.model.helper.EntityInterceptorHolder; @@ -54,7 +54,8 @@ public class EntityInterceptorListenerTest extends AbstractJpaIntegrationTest { final Target targetToBeCreated = testdataFactory.createTarget("targetToBeCreated"); - final Target loadedTarget = targetManagement.findTargetByControllerID(targetToBeCreated.getControllerId()); + final Target loadedTarget = targetManagement.findTargetByControllerID(targetToBeCreated.getControllerId()) + .get(); assertThat(postLoadEntityListener.getEntity()).isNotNull(); assertThat(postLoadEntityListener.getEntity()).isEqualTo(loadedTarget); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/model/ModelEqualsHashcodeTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/model/ModelEqualsHashcodeTest.java index 48e49425f..5eabde3d1 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/model/ModelEqualsHashcodeTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/model/ModelEqualsHashcodeTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa.model; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLActionFieldsTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLActionFieldsTest.java index e68cc2250..9d5a7ba6a 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLActionFieldsTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLActionFieldsTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa.rsql; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import org.eclipse.hawkbit.repository.ActionFields; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetFieldTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetFieldTest.java index 18e6501b9..aab2ce6ac 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetFieldTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetFieldTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa.rsql; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import java.util.Arrays; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetMetadataFieldsTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetMetadataFieldsTest.java index b62a41e68..446ca0379 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetMetadataFieldsTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLDistributionSetMetadataFieldsTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa.rsql; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLRolloutGroupFields.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLRolloutGroupFields.java index 230e08139..927d7c969 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLRolloutGroupFields.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLRolloutGroupFields.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa.rsql; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import org.eclipse.hawkbit.repository.RolloutGroupFields; import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; @@ -39,7 +39,7 @@ public class RSQLRolloutGroupFields extends AbstractJpaIntegrationTest { testdataFactory.createTargets(amountTargets, "rollout", "rollout"); final DistributionSet dsA = testdataFactory.createDistributionSet(""); rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*"); - rollout = rolloutManagement.findRolloutById(rollout.getId()); + rollout = rolloutManagement.findRolloutById(rollout.getId()).get(); this.rolloutGroupId = rollout.getRolloutGroups().get(0).getId(); } @@ -84,7 +84,7 @@ public class RSQLRolloutGroupFields extends AbstractJpaIntegrationTest { final String targetFilterQuery) { return rolloutManagement.createRollout( entityFactory.rollout().create() - .set(distributionSetManagement.findDistributionSetById(distributionSetId)).name(name) + .set(distributionSetManagement.findDistributionSetById(distributionSetId).get()).name(name) .targetFilterQuery(targetFilterQuery), amountGroups, new RolloutGroupConditionBuilder().withDefaults() .successCondition(RolloutGroupSuccessCondition.THRESHOLD, "100").build()); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleFieldTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleFieldTest.java index 22b771425..51b57e936 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleFieldTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleFieldTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa.rsql; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import org.eclipse.hawkbit.repository.SoftwareModuleFields; import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleMetadataFieldsTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleMetadataFieldsTest.java index 2775aed02..c16b1e161 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleMetadataFieldsTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleMetadataFieldsTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa.rsql; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleTypeFieldsTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleTypeFieldsTest.java index 344d0e320..57ffe8999 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleTypeFieldsTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLSoftwareModuleTypeFieldsTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa.rsql; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import org.eclipse.hawkbit.repository.Constants; import org.eclipse.hawkbit.repository.SoftwareModuleTypeFields; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTagFieldsTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTagFieldsTest.java index 7781283d5..239556aae 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTagFieldsTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTagFieldsTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa.rsql; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import org.eclipse.hawkbit.repository.TagFields; import org.eclipse.hawkbit.repository.builder.TagCreate; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTargetFieldTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTargetFieldTest.java index 1d8f03b06..26d92a652 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTargetFieldTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RSQLTargetFieldTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa.rsql; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import java.util.Arrays; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RsqlParserValidationOracleTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RsqlParserValidationOracleTest.java index c1b43eecd..c506c8aa0 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RsqlParserValidationOracleTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RsqlParserValidationOracleTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa.rsql; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.List; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/specifications/SpecificationsBuilderTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/specifications/SpecificationsBuilderTest.java index b5fc5dc4a..5e077c736 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/specifications/SpecificationsBuilderTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/specifications/SpecificationsBuilderTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.repository.jpa.specifications; -import static org.fest.assertions.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/tenancy/MultiTenancyEntityTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/tenancy/MultiTenancyEntityTest.java index 101372242..56a223496 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/tenancy/MultiTenancyEntityTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/tenancy/MultiTenancyEntityTest.java @@ -8,10 +8,12 @@ */ package org.eclipse.hawkbit.repository.jpa.tenancy; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.Collection; +import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.Target; @@ -126,7 +128,13 @@ public class MultiTenancyEntityTest extends AbstractJpaIntegrationTest { final Target createTargetForTenant = createTargetForTenant(controllerAnotherTenant, anotherTenant); // ensure target cannot be deleted by 'mytenant' - targetManagement.deleteTargets(Lists.newArrayList(createTargetForTenant.getId())); + try { + targetManagement.deleteTargets(Lists.newArrayList(createTargetForTenant.getId())); + fail("mytenant should not have been able to delete target of anotherTenant"); + } catch (final EntityNotFoundException ex) { + // ok + } + Slice targetsForAnotherTenant = findTargetsForTenant(anotherTenant); assertThat(targetsForAnotherTenant).hasSize(1); diff --git a/hawkbit-repository/hawkbit-repository-test/pom.xml b/hawkbit-repository/hawkbit-repository-test/pom.xml index c00e25f98..bfc953477 100644 --- a/hawkbit-repository/hawkbit-repository-test/pom.xml +++ b/hawkbit-repository/hawkbit-repository-test/pom.xml @@ -109,11 +109,6 @@ io.protostuff protostuff-runtime - - org.easytesting - fest-assert-core - test - com.jayway.awaitility awaitility diff --git a/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/AbstractIntegrationTest.java b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/AbstractIntegrationTest.java index 6e6368732..54d1ab57c 100644 --- a/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/AbstractIntegrationTest.java +++ b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/AbstractIntegrationTest.java @@ -254,7 +254,7 @@ public abstract class AbstractIntegrationTest implements EnvironmentAware { } protected Long getOsModule(final DistributionSet ds) { - return ds.findFirstModuleByType(osType).getId(); + return ds.findFirstModuleByType(osType).get().getId(); } protected Action prepareFinishedUpdate() { @@ -291,7 +291,7 @@ public abstract class AbstractIntegrationTest implements EnvironmentAware { // Run here, because Scheduler is disabled during tests rolloutManagement.fillRolloutGroupsWithTargets(rollout.getId()); - return rolloutManagement.findRolloutById(rollout.getId()); + return rolloutManagement.findRolloutById(rollout.getId()).get(); } @Before diff --git a/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/TestdataFactory.java b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/TestdataFactory.java index fd9892a0b..50f74443a 100644 --- a/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/TestdataFactory.java +++ b/hawkbit-repository/hawkbit-repository-test/src/main/java/org/eclipse/hawkbit/repository/test/util/TestdataFactory.java @@ -314,7 +314,7 @@ public class TestdataFactory { tags.forEach(tag -> distributionSetManagement.toggleTagAssignment(Arrays.asList(set.getId()), tag.getName())); - return distributionSetManagement.findDistributionSetById(set.getId()); + return distributionSetManagement.findDistributionSetById(set.getId()).get(); } @@ -529,7 +529,7 @@ public class TestdataFactory { entityFactory.softwareModule().update(module.getId()).description("Updated " + DEFAULT_DESCRIPTION))); // load also lazy stuff - return distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()); + return distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()).get(); } /** @@ -560,15 +560,9 @@ public class TestdataFactory { * @return persisted {@link DistributionSetType} */ public DistributionSetType findOrCreateDistributionSetType(final String dsTypeKey, final String dsTypeName) { - final DistributionSetType findDistributionSetTypeByname = distributionSetManagement - .findDistributionSetTypeByKey(dsTypeKey); - - if (findDistributionSetTypeByname != null) { - return findDistributionSetTypeByname; - } - - return distributionSetManagement.createDistributionSetType(entityFactory.distributionSetType().create() - .key(dsTypeKey).name(dsTypeName).description(LOREM.words(10)).colour("black")); + return distributionSetManagement.findDistributionSetTypeByKey(dsTypeKey) + .orElseGet(() -> distributionSetManagement.createDistributionSetType(entityFactory.distributionSetType() + .create().key(dsTypeKey).name(dsTypeName).description(LOREM.words(10)).colour("black"))); } /** @@ -588,17 +582,11 @@ public class TestdataFactory { */ public DistributionSetType findOrCreateDistributionSetType(final String dsTypeKey, final String dsTypeName, final Collection mandatory, final Collection optional) { - final DistributionSetType findDistributionSetTypeByname = distributionSetManagement - .findDistributionSetTypeByKey(dsTypeKey); - - if (findDistributionSetTypeByname != null) { - return findDistributionSetTypeByname; - } - - return distributionSetManagement.createDistributionSetType(entityFactory.distributionSetType().create() - .key(dsTypeKey).name(dsTypeName).description(LOREM.words(10)).colour("black") - .optional(optional.stream().map(SoftwareModuleType::getId).collect(Collectors.toList())) - .mandatory(mandatory.stream().map(SoftwareModuleType::getId).collect(Collectors.toList()))); + return distributionSetManagement.findDistributionSetTypeByKey(dsTypeKey) + .orElseGet(() -> distributionSetManagement.createDistributionSetType(entityFactory.distributionSetType() + .create().key(dsTypeKey).name(dsTypeName).description(LOREM.words(10)).colour("black") + .optional(optional.stream().map(SoftwareModuleType::getId).collect(Collectors.toList())) + .mandatory(mandatory.stream().map(SoftwareModuleType::getId).collect(Collectors.toList())))); } /** @@ -627,12 +615,9 @@ public class TestdataFactory { * @return persisted {@link SoftwareModuleType} */ public SoftwareModuleType findOrCreateSoftwareModuleType(final String key, final int maxAssignments) { - final SoftwareModuleType findSoftwareModuleTypeByKey = softwareManagement.findSoftwareModuleTypeByKey(key); - if (findSoftwareModuleTypeByKey != null) { - return findSoftwareModuleTypeByKey; - } - return softwareManagement.createSoftwareModuleType(entityFactory.softwareModuleType().create().key(key) - .name(key).description(LOREM.words(10)).maxAssignments(maxAssignments)); + return softwareManagement.findSoftwareModuleTypeByKey(key) + .orElseGet(() -> softwareManagement.createSoftwareModuleType(entityFactory.softwareModuleType().create() + .key(key).name(key).description(LOREM.words(10)).maxAssignments(maxAssignments))); } /** diff --git a/hawkbit-rest-core/pom.xml b/hawkbit-rest-core/pom.xml index bb511839c..567b8e179 100644 --- a/hawkbit-rest-core/pom.xml +++ b/hawkbit-rest-core/pom.xml @@ -62,11 +62,6 @@ hawkbit-repository-test ${project.version} test - - - org.easytesting - fest-assert - test ru.yandex.qatools.allure diff --git a/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/json/model/ExceptionInfoTest.java b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/json/model/ExceptionInfoTest.java index 901702795..46876debc 100644 --- a/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/json/model/ExceptionInfoTest.java +++ b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/json/model/ExceptionInfoTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.rest.json.model; -import static org.fest.assertions.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; diff --git a/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/SortUtilityTest.java b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/SortUtilityTest.java index 8f1b814bf..5c8d444be 100644 --- a/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/SortUtilityTest.java +++ b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/SortUtilityTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.rest.util; -import static org.fest.assertions.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import java.util.List; diff --git a/hawkbit-security-core/pom.xml b/hawkbit-security-core/pom.xml index 1297ae68b..8567648e2 100644 --- a/hawkbit-security-core/pom.xml +++ b/hawkbit-security-core/pom.xml @@ -71,16 +71,6 @@ spring-boot-starter-test test - - org.easytesting - fest-assert-core - test - - - org.easytesting - fest-assert - test - ru.yandex.qatools.allure allure-junit-adaptor diff --git a/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/im/authentication/PermissionTest.java b/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/im/authentication/PermissionTest.java index 2c948206e..669cae1a6 100644 --- a/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/im/authentication/PermissionTest.java +++ b/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/im/authentication/PermissionTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.im.authentication; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Collection; import java.util.List; diff --git a/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/security/ExcludePathAwareShallowETagFilterTest.java b/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/security/ExcludePathAwareShallowETagFilterTest.java index cd7cf5d0d..bda11acde 100644 --- a/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/security/ExcludePathAwareShallowETagFilterTest.java +++ b/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/security/ExcludePathAwareShallowETagFilterTest.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.mockito.Mockito.mockingDetails; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; diff --git a/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/util/IpUtilTest.java b/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/util/IpUtilTest.java index 836a9f13e..b6f2b8c0c 100644 --- a/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/util/IpUtilTest.java +++ b/hawkbit-security-core/src/test/java/org/eclipse/hawkbit/util/IpUtilTest.java @@ -9,7 +9,7 @@ package org.eclipse.hawkbit.util; import static com.google.common.net.HttpHeaders.X_FORWARDED_FOR; -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.assertFalse; import static org.junit.Assert.assertTrue; diff --git a/hawkbit-security-integration/pom.xml b/hawkbit-security-integration/pom.xml index 401d6b0bc..fe931ac88 100644 --- a/hawkbit-security-integration/pom.xml +++ b/hawkbit-security-integration/pom.xml @@ -49,23 +49,8 @@ test - junit - junit - test - - - org.easytesting - fest-assert-core - test - - - org.easytesting - fest-assert - test - - - org.mockito - mockito-core + org.springframework.boot + spring-boot-starter-test test diff --git a/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticateSecurityTokenFilter.java b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticateSecurityTokenFilter.java index 1ef75d48d..5c51b6fc1 100644 --- a/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticateSecurityTokenFilter.java +++ b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/ControllerPreAuthenticateSecurityTokenFilter.java @@ -78,27 +78,24 @@ public class ControllerPreAuthenticateSecurityTokenFilter extends AbstractContro @Override public HeaderAuthentication getPreAuthenticatedCredentials(final TenantSecurityToken securityToken) { - final Target target = systemSecurityContext.runAsSystemAsTenant(() -> { + final Optional target = systemSecurityContext.runAsSystemAsTenant(() -> { if (securityToken.getTargetId() != null) { return controllerManagement.findByTargetId(securityToken.getTargetId()); } return controllerManagement.findByControllerId(securityToken.getControllerId()); }, securityToken.getTenant()); - if (target == null) { - return null; - } - final String targetSecurityToken = systemSecurityContext.runAsSystemAsTenant(() -> target.getSecurityToken(), - securityToken.getTenant()); - return new HeaderAuthentication(target.getControllerId(), targetSecurityToken); + return target.map(t -> new HeaderAuthentication(t.getControllerId(), + systemSecurityContext.runAsSystemAsTenant(() -> t.getSecurityToken(), securityToken.getTenant()))) + .orElse(null); } private String resolveControllerId(final TenantSecurityToken securityToken) { if (securityToken.getControllerId() != null) { return securityToken.getControllerId(); } - final Optional foundTarget = Optional.ofNullable(systemSecurityContext.runAsSystemAsTenant( - () -> controllerManagement.findByTargetId(securityToken.getTargetId()), securityToken.getTenant())); + final Optional foundTarget = systemSecurityContext.runAsSystemAsTenant( + () -> controllerManagement.findByTargetId(securityToken.getTargetId()), securityToken.getTenant()); if (!foundTarget.isPresent()) { return null; } diff --git a/hawkbit-security-integration/src/test/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedAnonymousDownloadTest.java b/hawkbit-security-integration/src/test/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedAnonymousDownloadTest.java index b8195d023..c2ad66a93 100644 --- a/hawkbit-security-integration/src/test/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedAnonymousDownloadTest.java +++ b/hawkbit-security-integration/src/test/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedAnonymousDownloadTest.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 org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; diff --git a/hawkbit-security-integration/src/test/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedSecurityHeaderFilterTest.java b/hawkbit-security-integration/src/test/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedSecurityHeaderFilterTest.java index d21d4e63a..7a8e61bb3 100644 --- a/hawkbit-security-integration/src/test/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedSecurityHeaderFilterTest.java +++ b/hawkbit-security-integration/src/test/java/org/eclipse/hawkbit/security/ControllerPreAuthenticatedSecurityHeaderFilterTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.security; -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.mockito.Matchers.eq; import static org.mockito.Mockito.when; diff --git a/hawkbit-ui/pom.xml b/hawkbit-ui/pom.xml index 008581f9a..f263b87f8 100644 --- a/hawkbit-ui/pom.xml +++ b/hawkbit-ui/pom.xml @@ -262,8 +262,8 @@ test - org.mockito - mockito-core + org.springframework.boot + spring-boot-starter-test test @@ -271,16 +271,6 @@ gwtmockito test - - org.easytesting - fest-assert-core - test - - - org.easytesting - fest-assert - test - ru.yandex.qatools.allure allure-junit-adaptor diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/DispatcherRunnable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/DispatcherRunnable.java deleted file mode 100644 index 16f8aed19..000000000 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/DispatcherRunnable.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright (c) 2015 Bosch Software Innovations GmbH and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - */ -package org.eclipse.hawkbit.ui; - -import org.eclipse.hawkbit.repository.event.TenantAwareEvent; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; -import org.vaadin.spring.events.EventBus; - -import com.vaadin.server.VaadinSession; -import com.vaadin.ui.UI; -import com.vaadin.util.CurrentInstance; - -/** - * A {@link Runnable} implementation for the {@link UI#access(Runnable)} to - * dispatch events to the UI in the UI thread. - */ -public class DispatcherRunnable implements Runnable { - - private final SecurityContext userContext; - private final TenantAwareEvent event; - private final VaadinSession session; - private final EventBus eventBus; - - /** - * @param eventBus - * the event bus to distribute the event to - * @param session - * the current Vaadin session - * @param userContext - * the context of the currently logged in user to distribute the - * event to - * @param event - * the event which is distributed to the UI. - */ - public DispatcherRunnable(final EventBus eventBus, final VaadinSession session, final SecurityContext userContext, - final TenantAwareEvent event) { - this.eventBus = eventBus; - this.session = session; - this.userContext = userContext; - this.event = event; - } - - @Override - public void run() { - CurrentInstance.setCurrent(session.getUIs().iterator().next()); - CurrentInstance.setCurrent(session); - SecurityContextHolder.setContext(userContext); - eventBus.publish(this, event); - } -} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadStatusEvent.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadStatusEvent.java index 2eaa5fd6b..cc6b3ca5c 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadStatusEvent.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadStatusEvent.java @@ -16,8 +16,8 @@ package org.eclipse.hawkbit.ui.artifacts.event; public class UploadStatusEvent { /** - * TenantAwareEvent type definition of events during the artifact upload life-cycle - * from receiving the upload until the process end. + * TenantAwareEvent type definition of events during the artifact upload + * life-cycle from receiving the upload until the process end. */ public enum UploadStatusEventType { RECEIVE_UPLOAD, UPLOAD_FAILED, UPLOAD_IN_PROGRESS, UPLOAD_STARTED, UPLOAD_FINISHED, UPLOAD_SUCCESSFUL, UPLOAD_STREAMING_FAILED, UPLOAD_STREAMING_FINISHED, ABORT_UPLOAD diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/footer/UploadViewConfirmationWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/footer/UploadViewConfirmationWindowLayout.java index 98a566506..52fac3e20 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/footer/UploadViewConfirmationWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/footer/UploadViewConfirmationWindowLayout.java @@ -240,7 +240,7 @@ public class UploadViewConfirmationWindowLayout extends AbstractConfirmationWind for (final String swModuleTypeName : artifactUploadState.getSelectedDeleteSWModuleTypes()) { softwareManagement.deleteSoftwareModuleType( - softwareManagement.findSoftwareModuleTypeByName(swModuleTypeName).getId()); + softwareManagement.findSoftwareModuleTypeByName(swModuleTypeName).get().getId()); } addToConsolitatedMsg(FontAwesome.TASKS.getHtml() + SPUILabelDefinitions.HTML_SPACE + i18n.get("message.sw.module.type.delete", new Object[] { deleteSWModuleTypeCount })); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleAddUpdateWindow.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleAddUpdateWindow.java index 626258670..06112648b 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleAddUpdateWindow.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleAddUpdateWindow.java @@ -225,7 +225,7 @@ public class SoftwareModuleAddUpdateWindow extends CustomComponent { final String type = typeComboBox.getValue() != null ? typeComboBox.getValue().toString() : null; final SoftwareModuleCreate softwareModule = entityFactory.softwareModule().create() - .type(softwareManagement.findSoftwareModuleTypeByName(type)).name(name).version(version) + .type(softwareManagement.findSoftwareModuleTypeByName(type).get()).name(name).version(version) .description(description).vendor(vendor); final SoftwareModule newSoftwareModule = softwareManagement.createSoftwareModule(softwareModule); @@ -243,10 +243,9 @@ public class SoftwareModuleAddUpdateWindow extends CustomComponent { final String type = typeComboBox.getValue() != null ? typeComboBox.getValue().toString() : null; final SoftwareManagement swMgmtService = SpringContextHelper.getBean(SoftwareManagement.class); - final SoftwareModule swModule = swMgmtService.findSoftwareModuleByNameAndVersion(name, version, - swMgmtService.findSoftwareModuleTypeByName(type).getId()); - if (swModule != null) { + if (swMgmtService.findSoftwareModuleByNameAndVersion(name, version, + swMgmtService.findSoftwareModuleTypeByName(type).get().getId()).isPresent()) { uiNotifcation.displayValidationError( i18n.get("message.duplicate.softwaremodule", new Object[] { name, version })); return true; @@ -276,7 +275,7 @@ public class SoftwareModuleAddUpdateWindow extends CustomComponent { return; } editSwModule = Boolean.TRUE; - final SoftwareModule swModule = softwareManagement.findSoftwareModuleById(baseSwModuleId); + final SoftwareModule swModule = softwareManagement.findSoftwareModuleById(baseSwModuleId).get(); nameTextField.setValue(swModule.getName()); versionTextField.setValue(swModule.getVersion()); vendorTextField.setValue(HawkbitCommonUtil.trimAndNullIfEmpty(swModule.getVendor())); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleDetails.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleDetails.java index 61dfd6aca..674c1f01f 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleDetails.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleDetails.java @@ -201,7 +201,7 @@ public class SoftwareModuleDetails extends AbstractNamedVersionedEntityTableDeta @Override protected void showMetadata(final ClickEvent event) { - final SoftwareModule swmodule = softwareManagement.findSoftwareModuleById(getSelectedBaseEntityId()); + final SoftwareModule swmodule = softwareManagement.findSoftwareModuleById(getSelectedBaseEntityId()).get(); /* display the window */ UI.getCurrent().addWindow(swMetadataPopupLayout.getWindow(swmodule, null)); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleTable.java index 00cb630cf..5fc3f4f47 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleTable.java @@ -10,6 +10,7 @@ package org.eclipse.hawkbit.ui.artifacts.smtable; import java.util.List; import java.util.Map; +import java.util.Optional; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.model.SoftwareModule; @@ -148,7 +149,7 @@ public class SoftwareModuleTable extends AbstractNamedVersionTable findEntityByTableValue(final Long entityTableId) { return softwareManagement.findSoftwareModuleById(entityTableId); } @@ -259,7 +260,7 @@ public class SoftwareModuleTable extends AbstractNamedVersionTable typeSelected = swTypeManagementService .findSoftwareModuleTypeByName(tagNameComboBox.getValue().toString()); - if (null != typeSelected) { - return typeSelected.getColour() != null ? ColorPickerHelper.rgbToColorConverter(typeSelected.getColour()) + if (typeSelected.isPresent()) { + return typeSelected.get().getColour() != null + ? ColorPickerHelper.rgbToColorConverter(typeSelected.get().getColour()) : ColorPickerHelper.rgbToColorConverter(ColorPickerConstants.DEFAULT_COLOR); } return ColorPickerHelper.rgbToColorConverter(ColorPickerConstants.DEFAULT_COLOR); @@ -195,9 +197,7 @@ public class CreateUpdateSoftwareTypeLayout extends CreateUpdateTypeLayout { tagDesc.setValue(selectedTypeTag.getDescription()); typeKey.setValue(selectedTypeTag.getKey()); if (selectedTypeTag.getMaxAssignments() == 1) { @@ -206,7 +206,7 @@ public class CreateUpdateSoftwareTypeLayout extends CreateUpdateTypeLayout findEntityByKey() { return swTypeManagementService.findSoftwareModuleTypeByKey(typeKey.getValue()); } @Override - protected SoftwareModuleType findEntityByName() { + protected Optional findEntityByName() { return swTypeManagementService.findSoftwareModuleTypeByName(tagName.getValue()); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/SMTypeFilterButtonClick.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/SMTypeFilterButtonClick.java index 6e4771b0b..6b0c25e00 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/SMTypeFilterButtonClick.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/SMTypeFilterButtonClick.java @@ -49,7 +49,7 @@ public class SMTypeFilterButtonClick extends AbstractFilterSingleButtonClick imp @Override protected void filterClicked(final Button clickedButton) { final SoftwareModuleType softwareModuleType = softwareManagement - .findSoftwareModuleTypeByName(clickedButton.getData().toString()); + .findSoftwareModuleTypeByName(clickedButton.getData().toString()).get(); artifactUploadState.getSoftwareModuleFilters().setSoftwareModuleType(softwareModuleType); eventBus.publish(this, SMFilterEvent.FILTER_BY_TYPE); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/SMTypeFilterButtons.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/SMTypeFilterButtons.java index a761800d5..8a0f11f0a 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/SMTypeFilterButtons.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/SMTypeFilterButtons.java @@ -41,7 +41,7 @@ public class SMTypeFilterButtons extends AbstractFilterButtons { private final ArtifactUploadState artifactUploadState; private final UploadViewClientCriterion uploadViewClientCriterion; - + SMTypeFilterButtons(final UIEventBus eventBus, final ArtifactUploadState artifactUploadState, final UploadViewClientCriterion uploadViewClientCriterion, final SoftwareManagement softwareManagement) { super(eventBus, new SMTypeFilterButtonClick(eventBus, artifactUploadState, softwareManagement)); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadConfirmationWindow.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadConfirmationWindow.java index ea2c98e3c..151c2a3b3 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadConfirmationWindow.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadConfirmationWindow.java @@ -17,6 +17,7 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import org.eclipse.hawkbit.repository.ArtifactManagement; import org.eclipse.hawkbit.repository.exception.ArtifactUploadFailedException; @@ -196,8 +197,8 @@ public class UploadConfirmationWindow implements Button.ClickListener { final Item item = uploadDetailsTable.getItem(itemId); if (HawkbitCommonUtil.trimAndNullIfEmpty(fileName) != null) { final Long baseSwId = (Long) item.getItemProperty(BASE_SOFTWARE_ID).getValue(); - final List artifactList = artifactManagement.findByFilenameAndSoftwareModule(fileName, baseSwId); - if (!artifactList.isEmpty()) { + final Optional artifact = artifactManagement.findByFilenameAndSoftwareModule(fileName, baseSwId); + if (artifact.isPresent()) { warningIconLabel.setVisible(true); if (isErrorIcon(warningIconLabel)) { warningIconLabel.removeStyleName(SPUIStyleDefinitions.ERROR_LABEL); @@ -438,11 +439,11 @@ public class UploadConfirmationWindow implements Button.ClickListener { final Label errorLabel, final String oldFileName, final Long currentSwId) { if (warningLabel == null && (errorLabelCount > 1 || (duplicateCount == 1 && errorLabelCount == 1))) { - final List artifactList = artifactManagement.findByFilenameAndSoftwareModule(oldFileName, + final Optional artifactList = artifactManagement.findByFilenameAndSoftwareModule(oldFileName, currentSwId); errorLabel.removeStyleName(SPUIStyleDefinitions.ERROR_LABEL); errorLabel.setDescription(i18n.get(ALREADY_EXISTS_MSG)); - if (artifactList.isEmpty()) { + if (!artifactList.isPresent()) { errorLabel.setVisible(false); } redErrorLabelCount--; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/AbstractMetadataPopupLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/AbstractMetadataPopupLayout.java index 831126c55..ca5462993 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/AbstractMetadataPopupLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/AbstractMetadataPopupLayout.java @@ -12,7 +12,6 @@ import java.util.List; import java.util.Set; import org.apache.commons.lang3.StringUtils; -import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.model.MetaData; import org.eclipse.hawkbit.repository.model.NamedVersionedEntity; import org.eclipse.hawkbit.ui.SpPermissionChecker; @@ -162,7 +161,7 @@ public abstract class AbstractMetadataPopupLayout itemsSelected = event.getSelected(); if (!itemsSelected.isEmpty()) { - final Object itemSelected = itemsSelected.stream().findFirst().isPresent() - ? itemsSelected.stream().findFirst().get() : null; - popualateKeyValue(itemSelected); + popualateKeyValue(itemsSelected.iterator().next()); addIcon.setEnabled(true); } else { keyTextField.clear(); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/DistributionSetMetadatadetailslayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/DistributionSetMetadatadetailslayout.java index 57bda736c..7dcbb076d 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/DistributionSetMetadatadetailslayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/DistributionSetMetadatadetailslayout.java @@ -9,6 +9,7 @@ package org.eclipse.hawkbit.ui.common.detailslayout; import java.util.List; +import java.util.Optional; import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.EntityFactory; @@ -22,6 +23,7 @@ import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; import org.eclipse.hawkbit.ui.utils.UIComponentIdProvider; import org.eclipse.hawkbit.ui.utils.UINotification; +import org.springframework.data.domain.PageRequest; import com.vaadin.data.Item; import com.vaadin.data.util.IndexedContainer; @@ -83,7 +85,8 @@ public class DistributionSetMetadatadetailslayout extends Table { } selectedDistSetId = distributionSet.getId(); final List dsMetadataList = distributionSetManagement - .findDistributionSetMetadataByDistributionSetId(selectedDistSetId); + .findDistributionSetMetadataByDistributionSetId(selectedDistSetId, new PageRequest(0, 500)) + .getContent(); if (null != dsMetadataList && !dsMetadataList.isEmpty()) { dsMetadataList.forEach(dsMetadata -> setDSMetadataProperties(dsMetadata)); } @@ -108,7 +111,7 @@ public class DistributionSetMetadatadetailslayout extends Table { private IndexedContainer getDistSetContainer() { final IndexedContainer container = new IndexedContainer(); container.addContainerProperty(METADATA_KEY, String.class, ""); - setColumnExpandRatio(METADATA_KEY, 0.7f); + setColumnExpandRatio(METADATA_KEY, 0.7F); setColumnAlignment(METADATA_KEY, Align.LEFT); if (permissionChecker.hasUpdateDistributionPermission()) { @@ -148,15 +151,15 @@ public class DistributionSetMetadatadetailslayout extends Table { } private void showMetadataDetails(final Long selectedDistSetId, final String metadataKey) { - final DistributionSet distSet = distributionSetManagement.findDistributionSetById(selectedDistSetId); - if (distSet == null) { + final Optional distSet = distributionSetManagement.findDistributionSetById(selectedDistSetId); + if (!distSet.isPresent()) { notification.displayWarning(i18n.get("distributionset.not.exists")); return; } /* display the window */ - UI.getCurrent() - .addWindow(dsMetadataPopupLayout.getWindow(distSet, entityFactory.generateMetadata(metadataKey, ""))); + UI.getCurrent().addWindow( + dsMetadataPopupLayout.getWindow(distSet.get(), entityFactory.generateMetadata(metadataKey, ""))); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/SoftwareModuleMetadatadetailslayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/SoftwareModuleMetadatadetailslayout.java index 2691773d2..9c9cf4b13 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/SoftwareModuleMetadatadetailslayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/SoftwareModuleMetadatadetailslayout.java @@ -174,7 +174,7 @@ public class SoftwareModuleMetadatadetailslayout extends Table { } private void showMetadataDetails(final Long selectedSWModuleId, final String metadataKey) { - final SoftwareModule swmodule = softwareManagement.findSoftwareModuleById(selectedSWModuleId); + final SoftwareModule swmodule = softwareManagement.findSoftwareModuleById(selectedSWModuleId).get(); /* display the window */ UI.getCurrent() .addWindow(swMetadataPopupLayout.getWindow(swmodule, entityFactory.generateMetadata(metadataKey, ""))); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/AbstractTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/AbstractTable.java index 378bd2ace..c69651ffd 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/AbstractTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/AbstractTable.java @@ -12,6 +12,8 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; +import java.util.Objects; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -99,7 +101,7 @@ public abstract class AbstractTable extends Table impl if (values == null) { values = Collections.emptySet(); } - return values.stream().filter(item -> item != null).collect(Collectors.toSet()); + return values.stream().filter(Objects::nonNull).collect(Collectors.toSet()); } private void onValueChange() { @@ -107,14 +109,15 @@ public abstract class AbstractTable extends Table impl final Set values = getTableValue(this); - E entity = null; I lastId = null; if (!values.isEmpty()) { lastId = Iterables.getLast(values); - entity = findEntityByTableValue(lastId); } setManagementEntitiyStateValues(values, lastId); - publishEntityAfterValueChange(entity); + + if (lastId != null) { + findEntityByTableValue(lastId).ifPresent(this::publishEntityAfterValueChange); + } } protected void setManagementEntitiyStateValues(final Set values, final I lastId) { @@ -255,7 +258,7 @@ public abstract class AbstractTable extends Table impl return ids; } - protected abstract E findEntityByTableValue(I lastSelectedId); + protected abstract Optional findEntityByTableValue(I lastSelectedId); protected abstract void publishEntityAfterValueChange(E selectedLastEntity); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/AbstractTagToken.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/AbstractTagToken.java index ede305c68..d82553340 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/AbstractTagToken.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/AbstractTagToken.java @@ -252,7 +252,7 @@ public abstract class AbstractTagToken implements Serializ } protected Long getTagIdByTagName(final Long tagId) { - return tagDetails.entrySet().stream().filter(entry -> entry.getValue().getId().equals(tagId)).findFirst() + return tagDetails.entrySet().stream().filter(entry -> entry.getValue().getId().equals(tagId)).findAny() .map(entry -> entry.getKey()).orElse(null); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/TargetTagToken.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/TargetTagToken.java index 238b36d25..c840857fd 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/TargetTagToken.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/TargetTagToken.java @@ -23,6 +23,7 @@ import org.eclipse.hawkbit.ui.management.state.ManagementUIState; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.UINotification; +import org.springframework.data.domain.PageRequest; import org.vaadin.spring.events.EventBus.UIEventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -36,6 +37,8 @@ public class TargetTagToken extends AbstractTargetTagToken { private static final long serialVersionUID = 7124887018280196721L; + private static final int MAX_TAGS = 500; + // To Be Done : have to set this value based on view??? private static final Boolean NOTAGS_SELECTED = Boolean.FALSE; @@ -106,7 +109,7 @@ public class TargetTagToken extends AbstractTargetTagToken { protected void populateContainer() { container.removeAllItems(); tagDetails.clear(); - for (final TargetTag tag : tagManagement.findAllTargetTags()) { + for (final TargetTag tag : tagManagement.findAllTargetTags(new PageRequest(0, MAX_TAGS))) { setContainerPropertValues(tag.getId(), tag.getName(), tag.getColour()); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/SPUITableHorizonatlLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/SPUITableHorizonatlLayout.java deleted file mode 100644 index c1a8b7c2e..000000000 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/SPUITableHorizonatlLayout.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (c) 2015 Bosch Software Innovations GmbH and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - */ -package org.eclipse.hawkbit.ui.components; - -import com.vaadin.ui.HorizontalLayout; - -/** - * Table Horizonatl layout with Style. - * - * - * - */ -public class SPUITableHorizonatlLayout { - - private HorizontalLayout tableHorizonatlLayout; - - /** - * Constructor. - */ - public SPUITableHorizonatlLayout() { - tableHorizonatlLayout = new HorizontalLayout(); - decorate(); - } - - /** - * Decorate. - */ - private void decorate() { - tableHorizonatlLayout.setSpacing(false); - tableHorizonatlLayout.setMargin(false); - } - - public HorizontalLayout getTableHorizonatlLayout() { - return tableHorizonatlLayout; - } -} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/SPUIUpdateLogLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/SPUIUpdateLogLayout.java deleted file mode 100644 index 9faf7b87e..000000000 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/SPUIUpdateLogLayout.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Copyright (c) 2015 Bosch Software Innovations GmbH and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - */ -package org.eclipse.hawkbit.ui.components; - -import org.eclipse.hawkbit.ui.utils.I18N; -import org.eclipse.hawkbit.ui.utils.SPDateTimeUtil; -import org.eclipse.hawkbit.ui.utils.SpringContextHelper; - -import com.vaadin.ui.VerticalLayout; - -/** - * ChangeLog Vertical layout for Target and Distribution. - * - * - * - */ -public class SPUIUpdateLogLayout { - private final VerticalLayout changeLogLayout; - - /** - * Parametric constructor. - * - * @param changeLogLayout - * as layout - * @param lastModifiedAt - * as Date - * @param lastModifiedBy - * as string - * @param createdAt - * as date - * @param createdBy - * as string - */ - public SPUIUpdateLogLayout(final VerticalLayout changeLogLayout, final Long lastModifiedAt, - final String lastModifiedBy, final Long createdAt, final String createdBy) { - this.changeLogLayout = changeLogLayout; - changeLogLayout.setSpacing(true); - changeLogLayout.setMargin(true); - decorate(lastModifiedAt, lastModifiedBy, createdAt, createdBy); - } - - /** - * Decorate. - * - * @param lastModifiedAt - * @param lastModifiedBy - * @param createdAt - * @param createdBy - */ - private void decorate(final Long lastModifiedAt, final String lastModifiedBy, final Long createdAt, - final String createdBy) { - final I18N i18n = SpringContextHelper.getBean(I18N.class); - changeLogLayout.addComponent(SPUIComponentProvider.createNameValueLabel(i18n.get("label.created.at"), - createdAt == null ? "" : SPDateTimeUtil.getFormattedDate(createdAt))); - - changeLogLayout.addComponent(SPUIComponentProvider.createNameValueLabel(i18n.get("label.created.by"), - createdBy == null ? "" : createdBy)); - - if (null != lastModifiedAt) { - changeLogLayout.addComponent(SPUIComponentProvider.createNameValueLabel(i18n.get("label.modified.date"), - SPDateTimeUtil.getFormattedDate(lastModifiedAt))); - - changeLogLayout.addComponent(SPUIComponentProvider.createNameValueLabel(i18n.get("label.modified.by"), - lastModifiedBy == null ? "" : lastModifiedBy)); - } - - } - - /** - * GET Change LogLayout. - * - * @return VerticalLayout as UI - */ - public VerticalLayout getChangeLogLayout() { - return changeLogLayout; - } -} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/HtmlButtonRendererConnector.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/HtmlButtonRendererConnector.java index 8539b60ed..f1eee09eb 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/HtmlButtonRendererConnector.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/HtmlButtonRendererConnector.java @@ -14,7 +14,7 @@ import com.vaadin.client.connectors.ButtonRendererConnector; import com.vaadin.shared.ui.Connect; /** - * A connector for {@link HtmlButtonRenderer}. + * A connector for {@link HtmlButtonRenderer}. * */ @Connect(org.eclipse.hawkbit.ui.customrenderers.renderers.HtmlButtonRenderer.class) diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/RolloutRendererConnector.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/RolloutRendererConnector.java index ca58648ac..f500517f8 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/RolloutRendererConnector.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/RolloutRendererConnector.java @@ -35,4 +35,4 @@ public class RolloutRendererConnector extends ClickableRendererConnector handler) { return getRenderer().addClickHandler(handler); } -} \ No newline at end of file +} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/renderers/HtmlLabelRenderer.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/renderers/HtmlLabelRenderer.java index ec801ad2e..0acc05177 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/renderers/HtmlLabelRenderer.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/renderers/HtmlLabelRenderer.java @@ -15,9 +15,10 @@ import com.vaadin.ui.Grid.AbstractRenderer; * Renders label with provided value and style. * */ -public class HtmlLabelRenderer extends AbstractRenderer { +public class HtmlLabelRenderer extends AbstractRenderer { private static final long serialVersionUID = -7675588068526774915L; + /** * Creates a new text renderer */ diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/dd/criteria/DistributionsViewClientCriterion.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/dd/criteria/DistributionsViewClientCriterion.java index 9ca633dfd..f90e3e770 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/dd/criteria/DistributionsViewClientCriterion.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/dd/criteria/DistributionsViewClientCriterion.java @@ -49,14 +49,12 @@ public final class DistributionsViewClientCriterion extends ServerViewClientCrit criteria[0] = ServerViewComponentClientCriterion.createBuilder() .dragSourceIdPrefix(UIComponentIdProvider.DIST_TABLE_ID) .dropTargetIdPrefixes(UIComponentIdProvider.DELETE_BUTTON_WRAPPER_ID) - .dropAreaIds(UIComponentIdProvider.DELETE_BUTTON_WRAPPER_ID) - .build(); + .dropAreaIds(UIComponentIdProvider.DELETE_BUTTON_WRAPPER_ID).build(); // Distribution set type acceptable components. criteria[1] = ServerViewComponentClientCriterion.createBuilder() .dragSourceIdPrefix(SPUIDefinitions.DISTRIBUTION_SET_TYPE_ID_PREFIXS) .dropTargetIdPrefixes(UIComponentIdProvider.DELETE_BUTTON_WRAPPER_ID) - .dropAreaIds(UIComponentIdProvider.DELETE_BUTTON_WRAPPER_ID) - .build(); + .dropAreaIds(UIComponentIdProvider.DELETE_BUTTON_WRAPPER_ID).build(); // Upload software module table acceptable components. criteria[2] = ServerViewComponentClientCriterion.createBuilder() .dragSourceIdPrefix(UIComponentIdProvider.UPLOAD_SOFTWARE_MODULE_TABLE) @@ -68,8 +66,7 @@ public final class DistributionsViewClientCriterion extends ServerViewClientCrit criteria[3] = ServerViewComponentClientCriterion.createBuilder() .dragSourceIdPrefix(SPUIDefinitions.SOFTWARE_MODULE_TAG_ID_PREFIXS) .dropTargetIdPrefixes(UIComponentIdProvider.DELETE_BUTTON_WRAPPER_ID) - .dropAreaIds(UIComponentIdProvider.DELETE_BUTTON_WRAPPER_ID) - .build(); + .dropAreaIds(UIComponentIdProvider.DELETE_BUTTON_WRAPPER_ID).build(); return criteria; } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/decorators/SPUIButtonDecorator.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/decorators/SPUIButtonDecorator.java index 05d1f8a0a..234204cae 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/decorators/SPUIButtonDecorator.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/decorators/SPUIButtonDecorator.java @@ -13,9 +13,6 @@ import com.vaadin.ui.Button; /** * Interface to define method for button decoration. - * - * - * */ @FunctionalInterface public interface SPUIButtonDecorator { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/decorators/SPUIButtonStyleSmallNoBorder.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/decorators/SPUIButtonStyleSmallNoBorder.java index 50142e02d..83fd25ac7 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/decorators/SPUIButtonStyleSmallNoBorder.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/decorators/SPUIButtonStyleSmallNoBorder.java @@ -14,12 +14,6 @@ import com.vaadin.ui.themes.ValoTheme; /** * Style for button: Small NoBorder. - * - * - * - * - * - * */ public class SPUIButtonStyleSmallNoBorder implements SPUIButtonDecorator { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/decorators/SPUIButtonStyleSmallNoBorderUH.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/decorators/SPUIButtonStyleSmallNoBorderUH.java deleted file mode 100644 index 5b4dae0a3..000000000 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/decorators/SPUIButtonStyleSmallNoBorderUH.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (c) 2015 Bosch Software Innovations GmbH and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - */ -package org.eclipse.hawkbit.ui.decorators; - -import com.vaadin.server.Resource; -import com.vaadin.ui.Button; -import com.vaadin.ui.themes.ValoTheme; - -/** - * Style for button: Small NoBorder Height UnDefined. - * - */ -public class SPUIButtonStyleSmallNoBorderUH implements SPUIButtonDecorator { - - @Override - public Button decorate(final Button button, final String style, final boolean setStyle, final Resource icon) { - button.addStyleName(ValoTheme.BUTTON_SMALL); - button.addStyleName(ValoTheme.BUTTON_BORDERLESS_COLORED); - button.setHeightUndefined(); - // Set Style - if (null != style) { - if (setStyle) { - button.setStyleName(style); - } else { - button.addStyleName(style); - } - } - // Set icon - if (null != icon) { - button.addStyleName(ValoTheme.BUTTON_ICON_ONLY); - button.setIcon(icon); - } - return button; - } - -} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/decorators/SPUIEmbedValue.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/decorators/SPUIEmbedValue.java deleted file mode 100644 index 9694a687b..000000000 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/decorators/SPUIEmbedValue.java +++ /dev/null @@ -1,179 +0,0 @@ -/** - * Copyright (c) 2015 Bosch Software Innovations GmbH and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - */ -package org.eclipse.hawkbit.ui.decorators; - -/** - * DTO for Embeded UI decoration. - * - * - * - */ -public class SPUIEmbedValue { - private String id; - private String data; - private String styleName; - private boolean immediate; - private String source; - private int type; - private String mimeType; - private String description; - - /** - * GET - ID. - * - * @return id - */ - public String getId() { - return id; - } - - /** - * SET - ID. - * - * @param id - * as ID - */ - public void setId(String id) { - this.id = id; - } - - /** - * GET - DATA. - * - * @return data - */ - public String getData() { - return data; - } - - /** - * SET - DATA. - * - * @param data - * as data - */ - public void setData(String data) { - this.data = data; - } - - /** - * GET - STYLE NAME. - * - * @return style name - */ - public String getStyleName() { - return styleName; - } - - /** - * SET - STYLE NAME. - * - * @param styleName - * as Style - */ - public void setStyleName(String styleName) { - this.styleName = styleName; - } - - /** - * CHECK - IMM. - * - * @return flag - */ - public boolean isImmediate() { - return immediate; - } - - /** - * SET - IMM. - * - * @param immediate - * as flag - */ - public void setImmediate(boolean immediate) { - this.immediate = immediate; - } - - /** - * GET - SOURCE. - * - * @return source - */ - public String getSource() { - return source; - } - - /** - * SET - SOURCE. - * - * @param source - * as source - */ - public void setSource(String source) { - this.source = source; - } - - /** - * GET - TYPE. - * - * @return type - */ - public int getType() { - return type; - } - - /** - * SET - TYPE. - * - * @param type - * as type - */ - public void setType(int type) { - this.type = type; - } - - /** - * GET - MIME. - * - * @return mime - */ - public String getMimeType() { - return mimeType; - } - - /** - * SET - MIME. - * - * @param mimeType - * as mime - */ - public void setMimeType(String mimeType) { - this.mimeType = mimeType; - } - - /** - * GET - DESC. - * - * @return desc - */ - public String getDescription() { - return description; - } - - /** - * SET - DESC. - * - * @param description - * as desc - */ - public void setDescription(String description) { - this.description = description; - } - -} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/CreateUpdateDistSetTypeLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/CreateUpdateDistSetTypeLayout.java index 24fa2ac9a..61160d8d3 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/CreateUpdateDistSetTypeLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/CreateUpdateDistSetTypeLayout.java @@ -9,6 +9,7 @@ package org.eclipse.hawkbit.ui.distributions.disttype; import java.util.List; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -152,11 +153,11 @@ public class CreateUpdateDistSetTypeLayout extends CreateUpdateTypeLayout existedDistType = distributionSetManagement .findDistributionSetTypeByName(tagNameComboBox.getValue().toString()); - if (null != existedDistType) { - return existedDistType.getColour() != null - ? ColorPickerHelper.rgbToColorConverter(existedDistType.getColour()) + if (existedDistType.isPresent()) { + return existedDistType.get().getColour() != null + ? ColorPickerHelper.rgbToColorConverter(existedDistType.get().getColour()) : ColorPickerHelper.rgbToColorConverter(ColorPickerConstants.DEFAULT_COLOR); } return ColorPickerHelper.rgbToColorConverter(ColorPickerConstants.DEFAULT_COLOR); @@ -522,12 +523,10 @@ public class CreateUpdateDistSetTypeLayout extends CreateUpdateTypeLayout { tagDesc.setValue(selectedTypeTag.getDescription()); typeKey.setValue(selectedTypeTag.getKey()); if (distributionSetManagement.countDistributionSetsByType(selectedTypeTag.getId()) <= 0) { @@ -541,20 +540,12 @@ public class CreateUpdateDistSetTypeLayout extends CreateUpdateTypeLayout addTargetTableforUpdate(swModuleType, false)); + selectedTypeTag.getMandatoryModuleTypes() + .forEach(swModuleType -> addTargetTableforUpdate(swModuleType, true)); setColorPickerComponentsColor(selectedTypeTag.getColour()); - } - } - - private DistributionSetType fetchDistributionSetType(final String distTypeName) { - - return distributionSetManagement.findDistributionSetTypeByName(distTypeName); + }); } @SuppressWarnings("unchecked") @@ -590,12 +581,12 @@ public class CreateUpdateDistSetTypeLayout extends CreateUpdateTypeLayout findEntityByKey() { return distributionSetManagement.findDistributionSetTypeByKey(typeKey.getValue()); } @Override - protected DistributionSetType findEntityByName() { + protected Optional findEntityByName() { return distributionSetManagement.findDistributionSetTypeByName(tagName.getValue()); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/DSTypeFilterButtonClick.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/DSTypeFilterButtonClick.java index f13946d5f..32907eea2 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/DSTypeFilterButtonClick.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/DSTypeFilterButtonClick.java @@ -11,7 +11,6 @@ package org.eclipse.hawkbit.ui.distributions.disttype; import java.io.Serializable; import org.eclipse.hawkbit.repository.DistributionSetManagement; -import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.ui.common.filterlayout.AbstractFilterSingleButtonClick; import org.eclipse.hawkbit.ui.distributions.state.ManageDistUIState; import org.eclipse.hawkbit.ui.management.event.DistributionTableFilterEvent; @@ -49,9 +48,8 @@ public class DSTypeFilterButtonClick extends AbstractFilterSingleButtonClick imp @Override protected void filterClicked(final Button clickedButton) { - final DistributionSetType distSetType = distributionSetManagement - .findDistributionSetTypeByName(clickedButton.getData().toString()); - manageDistUIState.getManageDistFilters().setClickedDistSetType(distSetType); + distributionSetManagement.findDistributionSetTypeByName(clickedButton.getData().toString()) + .ifPresent(manageDistUIState.getManageDistFilters()::setClickedDistSetType); eventBus.publish(this, DistributionTableFilterEvent.FILTER_BY_TAG); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/DSTypeFilterButtons.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/DSTypeFilterButtons.java index bb5ca6fe6..7040393ae 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/DSTypeFilterButtons.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/DSTypeFilterButtons.java @@ -38,7 +38,7 @@ public class DSTypeFilterButtons extends AbstractFilterButtons { private final ManageDistUIState manageDistUIState; private final DistributionsViewClientCriterion distributionsViewClientCriterion; - + DSTypeFilterButtons(final UIEventBus eventBus, final ManageDistUIState manageDistUIState, final DistributionsViewClientCriterion distributionsViewClientCriterion, final DistributionSetManagement distributionSetManagement) { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetDetails.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetDetails.java index 01880565a..750e9e906 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetDetails.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetDetails.java @@ -159,7 +159,7 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet } for (final SoftwareModuleIdName swIdName : softwareModuleIdNameList) { - final SoftwareModule softwareModule = softwareManagement.findSoftwareModuleById(swIdName.getId()); + final SoftwareModule softwareModule = softwareManagement.findSoftwareModuleById(swIdName.getId()).get(); if (assignedSWModule.containsKey(softwareModule.getType().getName())) { assignedSWModule.get(softwareModule.getType().getName()).append("
").append("") .append(getUnsavedAssigedSwModule(softwareModule.getName(), softwareModule.getVersion())) @@ -374,7 +374,7 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet assignedSWModule.clear(); } setSelectedBaseEntity( - distributionSetManagement.findDistributionSetByIdWithDetails(getSelectedBaseEntityId())); + distributionSetManagement.findDistributionSetByIdWithDetails(getSelectedBaseEntityId()).get()); UI.getCurrent().access(this::populateModule); } } @@ -409,7 +409,7 @@ public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDet @Override protected void showMetadata(final ClickEvent event) { final DistributionSet ds = distributionSetManagement - .findDistributionSetByIdWithDetails(getSelectedBaseEntityId()); + .findDistributionSetByIdWithDetails(getSelectedBaseEntityId()).get(); UI.getCurrent().addWindow(dsMetadataPopupLayout.getWindow(ds, null)); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetTable.java index 75ffc4548..cc4673da8 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetTable.java @@ -13,6 +13,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.Optional; import java.util.Set; import org.eclipse.hawkbit.repository.DistributionSetManagement; @@ -121,7 +122,7 @@ public class DistributionSetTable extends AbstractNamedVersionTable events) { manageDistUIState.getLastSelectedDistribution() .ifPresent(lastSelectedDsIdName -> events.stream() - .filter(event -> event.getEntityId().equals(lastSelectedDsIdName)).findFirst() + .filter(event -> event.getEntityId().equals(lastSelectedDsIdName)).findAny() .ifPresent(event -> eventBus.publish(this, new DistributionTableEvent(BaseEntityEventType.SELECTED_ENTITY, event.getEntity())))); } @@ -184,7 +185,7 @@ public class DistributionSetTable extends AbstractNamedVersionTable findEntityByTableValue(final Long entityTableId) { return distributionSetManagement.findDistributionSetByIdWithDetails(entityTableId); } @@ -242,14 +243,15 @@ public class DistributionSetTable extends AbstractNamedVersionTable softwareModulesIdList, final Object distId) { - final DistributionSet distributionSet = distributionSetManagement.findDistributionSetById((Long) distId); + final Optional distributionSet = distributionSetManagement + .findDistributionSetById((Long) distId); - if (distributionSet == null) { + if (!distributionSet.isPresent()) { notification.displayWarning(i18n.get("distributionset.not.exists")); return; } - final DistributionSetIdName distributionSetIdName = new DistributionSetIdName(distributionSet); + final DistributionSetIdName distributionSetIdName = new DistributionSetIdName(distributionSet.get()); final HashMap> map; if (manageDistUIState.getConsolidatedDistSoftwarewList().containsKey(distributionSetIdName)) { @@ -264,7 +266,7 @@ public class DistributionSetTable extends AbstractNamedVersionTable getMetadataList() { - return Collections.unmodifiableList( - distributionSetManagement.findDistributionSetMetadataByDistributionSetId(getSelectedEntity().getId())); + return Collections.unmodifiableList(distributionSetManagement + .findDistributionSetMetadataByDistributionSetId(getSelectedEntity().getId(), new PageRequest(0, 500)) + .getContent()); } - /** - * Update metadata for DistributionSet. - */ - @Override protected void deleteMetadata(final DistributionSet entity, final String key, final String value) { distributionSetManagement.deleteDistributionSetMetadata(entity.getId(), key); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DistributionsConfirmationWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DistributionsConfirmationWindowLayout.java index 9135945e3..b9df7b862 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DistributionsConfirmationWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DistributionsConfirmationWindowLayout.java @@ -17,7 +17,6 @@ import java.util.stream.Collectors; import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.SoftwareManagement; -import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent; import org.eclipse.hawkbit.ui.common.confirmwindow.layout.AbstractConfirmationWindowLayout; import org.eclipse.hawkbit.ui.common.confirmwindow.layout.ConfirmationTab; @@ -278,7 +277,7 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW for (final String swModuleTypeName : manageDistUIState.getSelectedDeleteSWModuleTypes()) { softwareManagement.deleteSoftwareModuleType( - softwareManagement.findSoftwareModuleTypeByName(swModuleTypeName).getId()); + softwareManagement.findSoftwareModuleTypeByName(swModuleTypeName).get().getId()); } addToConsolitatedMsg(FontAwesome.TASKS.getHtml() + SPUILabelDefinitions.HTML_SPACE + i18n.get("message.sw.module.type.delete", new Object[] { deleteSWModuleTypeCount })); @@ -460,10 +459,10 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW private void deleteDistSetTypeAll(final ConfirmationTab tab) { final int deleteDistTypeCount = manageDistUIState.getSelectedDeleteDistSetTypes().size(); - for (final String deleteDistTypeName : manageDistUIState.getSelectedDeleteDistSetTypes()) { - dsManagement - .deleteDistributionSetType(dsManagement.findDistributionSetTypeByName(deleteDistTypeName).getId()); - } + manageDistUIState.getSelectedDeleteDistSetTypes().stream() + .map(deleteDistTypeName -> dsManagement.findDistributionSetTypeByName(deleteDistTypeName).get().getId()) + .forEach(dsManagement::deleteDistributionSetType); + addToConsolitatedMsg(FontAwesome.TASKS.getHtml() + SPUILabelDefinitions.HTML_SPACE + i18n.get("message.dist.type.delete", new Object[] { deleteDistTypeCount })); manageDistUIState.getSelectedDeleteDistSetTypes().clear(); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwMetadataPopupLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwMetadataPopupLayout.java index 0389811d9..0e1ba5342 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwMetadataPopupLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwMetadataPopupLayout.java @@ -44,8 +44,8 @@ public class SwMetadataPopupLayout extends AbstractMetadataPopupLayout events) { manageDistUIState.getSelectedBaseSwModuleId() .ifPresent(lastSelectedModuleId -> events.stream() - .filter(event -> lastSelectedModuleId.equals(event.getEntityId())).findFirst() + .filter(event -> lastSelectedModuleId.equals(event.getEntityId())).findAny() .ifPresent(lastEvent -> eventBus.publish(this, new SoftwareModuleEvent(BaseEntityEventType.SELECTED_ENTITY, lastEvent.getEntity())))); } @@ -257,7 +258,7 @@ public class SwModuleTable extends AbstractNamedVersionTable findEntityByTableValue(final Long lastSelectedId) { return softwareManagement.findSoftwareModuleById(lastSelectedId); } @@ -420,7 +421,7 @@ public class SwModuleTable extends AbstractNamedVersionTable new EntityNotFoundException(TargetFilterQuery.class, tfqId)); initLocal(); @@ -165,7 +164,8 @@ public class DistributionSetSelectWindow } private void updateTargetFilterQueryDS(final Long targetFilterQueryId, final Long dsId) { - final TargetFilterQuery tfq = targetFilterQueryManagement.findTargetFilterQueryById(targetFilterQueryId); + final TargetFilterQuery tfq = targetFilterQueryManagement.findTargetFilterQueryById(targetFilterQueryId) + .orElseThrow(() -> new EntityNotFoundException(TargetFilterQuery.class, targetFilterQueryId)); if (dsId != null) { confirmWithConsequencesDialog(tfq, dsId); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/TargetFilterTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/TargetFilterTable.java index 86402ed96..68c4fce6e 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/TargetFilterTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/TargetFilterTable.java @@ -181,7 +181,7 @@ public class TargetFilterTable extends Table { if (ok) { final Long rowId = (Long) ((Button) event.getComponent()).getData(); final String deletedFilterName = targetFilterQueryManagement.findTargetFilterQueryById(rowId) - .getName(); + .get().getName(); targetFilterQueryManagement.deleteTargetFilterQuery(rowId); /* @@ -254,7 +254,7 @@ public class TargetFilterTable extends Table { private void onClickOfDetailButton(final ClickEvent event) { final String targetFilterName = (String) ((Button) event.getComponent()).getData(); final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement - .findTargetFilterQueryByName(targetFilterName); + .findTargetFilterQueryByName(targetFilterName).get(); filterManagementUIState.setFilterQueryValue(targetFilterQuery.getQuery()); filterManagementUIState.setTfQuery(targetFilterQuery); filterManagementUIState.setEditViewDisplayed(true); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/client/AutoCompleteTextFieldConnector.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/client/AutoCompleteTextFieldConnector.java index 13d6d3707..450e2f904 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/client/AutoCompleteTextFieldConnector.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/client/AutoCompleteTextFieldConnector.java @@ -140,4 +140,3 @@ public class AutoCompleteTextFieldConnector extends AbstractExtensionConnector { rpc.suggest(textFieldWidget.getValue(), textFieldWidget.getCursorPos()); } } - diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/client/SuggestTokenDto.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/client/SuggestTokenDto.java index 9dbe07d36..c370a9917 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/client/SuggestTokenDto.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/client/SuggestTokenDto.java @@ -73,4 +73,4 @@ public class SuggestTokenDto implements Serializable { public String toString() { return "SuggestTokenDto [start=" + start + ", end=" + end + ", suggestion=" + suggestion + "]"; } -} \ No newline at end of file +} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/layouts/AbstractCreateUpdateTagLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/layouts/AbstractCreateUpdateTagLayout.java index 2bb45ae8d..798d893b8 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/layouts/AbstractCreateUpdateTagLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/layouts/AbstractCreateUpdateTagLayout.java @@ -8,6 +8,8 @@ */ package org.eclipse.hawkbit.ui.layouts; +import java.util.Optional; + import org.apache.commons.lang3.StringUtils; import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.TagManagement; @@ -147,7 +149,7 @@ public abstract class AbstractCreateUpdateTagLayout exten @Override public void saveOrUpdate() { if (isUpdateAction()) { - updateEntity(findEntityByName()); + updateEntity(findEntityByName().orElse(null)); return; } @@ -295,15 +297,16 @@ public abstract class AbstractCreateUpdateTagLayout exten * @return the color which should be selected in the color-picker component. */ protected Color getColorForColorPicker() { - final TargetTag targetTagSelected = tagManagement.findTargetTag(tagNameComboBox.getValue().toString()); - if (targetTagSelected == null) { + final Optional targetTagSelected = tagManagement + .findTargetTag(tagNameComboBox.getValue().toString()); + if (!targetTagSelected.isPresent()) { final DistributionSetTag distTag = tagManagement - .findDistributionSetTag(tagNameComboBox.getValue().toString()); + .findDistributionSetTag(tagNameComboBox.getValue().toString()).get(); return distTag.getColour() != null ? ColorPickerHelper.rgbToColorConverter(distTag.getColour()) : ColorPickerHelper.rgbToColorConverter(ColorPickerConstants.DEFAULT_COLOR); } - return targetTagSelected.getColour() != null - ? ColorPickerHelper.rgbToColorConverter(targetTagSelected.getColour()) + return targetTagSelected.get().getColour() != null + ? ColorPickerHelper.rgbToColorConverter(targetTagSelected.get().getColour()) : ColorPickerHelper.rgbToColorConverter(ColorPickerConstants.DEFAULT_COLOR); } @@ -604,14 +607,11 @@ public abstract class AbstractCreateUpdateTagLayout exten } private boolean isDuplicateByName() { - final E existingType = findEntityByName(); - if (existingType != null) { - uiNotification.displayValidationError( - i18n.get("message.tag.duplicate.check", new Object[] { existingType.getName() })); - return true; - } + final Optional existingType = findEntityByName(); + existingType.ifPresent(type -> uiNotification + .displayValidationError(i18n.get("message.tag.duplicate.check", new Object[] { type.getName() }))); - return false; + return existingType.isPresent(); } protected boolean isDuplicate() { @@ -658,7 +658,7 @@ public abstract class AbstractCreateUpdateTagLayout exten public void removeColorChangeListener(final ColorChangeListener listener) { } - protected abstract E findEntityByName(); + protected abstract Optional findEntityByName(); protected abstract String getWindowCaption(); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/layouts/CreateUpdateTypeLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/layouts/CreateUpdateTypeLayout.java index 9c65dc2d2..8590b7ea1 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/layouts/CreateUpdateTypeLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/layouts/CreateUpdateTypeLayout.java @@ -8,6 +8,8 @@ */ package org.eclipse.hawkbit.ui.layouts; +import java.util.Optional; + import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.TagManagement; import org.eclipse.hawkbit.repository.model.NamedEntity; @@ -229,15 +231,11 @@ public abstract class CreateUpdateTypeLayout extends Abst } private boolean isDuplicateByKey() { + final Optional existingType = findEntityByKey(); - final E existingType = findEntityByKey(); + existingType.ifPresent(type -> uiNotification.displayValidationError(getDuplicateKeyErrorMessage(type))); - if (existingType != null) { - uiNotification.displayValidationError(getDuplicateKeyErrorMessage(existingType)); - return true; - } - - return false; + return existingType.isPresent(); } @Override @@ -245,7 +243,7 @@ public abstract class CreateUpdateTypeLayout extends Abst return isDuplicateByKey() || super.isDuplicate(); } - protected abstract E findEntityByKey(); + protected abstract Optional findEntityByKey(); protected abstract String getDuplicateKeyErrorMessage(E existingType); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/actionhistory/ActionHistoryTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/actionhistory/ActionHistoryTable.java index 08e3e37f1..9c1fd3b8c 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/actionhistory/ActionHistoryTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/actionhistory/ActionHistoryTable.java @@ -432,7 +432,7 @@ public class ActionHistoryTable extends TreeTable { .getValue(); final org.eclipse.hawkbit.repository.model.Action action = deploymentManagement - .findActionWithDetails(actionId); + .findActionWithDetails(actionId).get(); final Pageable pageReq = new PageRequest(0, 1000, new Sort(Direction.DESC, ActionStatusFields.ID.getFieldName())); final Page actionStatusList; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionAddUpdateWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionAddUpdateWindowLayout.java index 341c8b114..a1d58e9c7 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionAddUpdateWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionAddUpdateWindowLayout.java @@ -9,6 +9,7 @@ package org.eclipse.hawkbit.ui.management.dstable; import java.util.Collections; +import java.util.Optional; import org.apache.commons.lang3.StringUtils; import org.eclipse.hawkbit.repository.DistributionSetManagement; @@ -213,7 +214,7 @@ public class DistributionAddUpdateWindowLayout extends CustomComponent { .updateDistributionSet(entityFactory.distributionSet().update(editDistId) .name(distNameTextField.getValue()).description(descTextArea.getValue()) .version(distVersionTextField.getValue()).requiredMigrationStep(isMigStepReq) - .type(distributionSetManagement.findDistributionSetTypeById(distSetTypeId))); + .type(distributionSetManagement.findDistributionSetTypeById(distSetTypeId).get())); notificationMessage.displaySuccess(i18n.get("message.new.dist.save.success", new Object[] { currentDS.getName(), currentDS.getVersion() })); // update table row+details layout @@ -233,9 +234,9 @@ public class DistributionAddUpdateWindowLayout extends CustomComponent { final String desc = HawkbitCommonUtil.trimAndNullIfEmpty(descTextArea.getValue()); final boolean isMigStepReq = reqMigStepCheckbox.getValue(); - final DistributionSet newDist = distributionSetManagement - .createDistributionSet(entityFactory.distributionSet().create().name(name).version(version) - .description(desc).type(distributionSetManagement.findDistributionSetTypeById(distSetTypeId)) + final DistributionSet newDist = distributionSetManagement.createDistributionSet( + entityFactory.distributionSet().create().name(name).version(version).description(desc) + .type(distributionSetManagement.findDistributionSetTypeById(distSetTypeId).get()) .requiredMigrationStep(isMigStepReq)); eventBus.publish(this, new DistributionTableEvent(BaseEntityEventType.ADD_ENTITY, newDist)); @@ -250,18 +251,19 @@ public class DistributionAddUpdateWindowLayout extends CustomComponent { final String name = distNameTextField.getValue(); final String version = distVersionTextField.getValue(); - final DistributionSet existingDs = distributionSetManagement.findDistributionSetByNameAndVersion(name, version); + final Optional existingDs = distributionSetManagement.findDistributionSetByNameAndVersion(name, + version); /* * Distribution should not exists with the same name & version. Display * error message, when the "existingDs" is not null and it is add window * (or) when the "existingDs" is not null and it is edit window and the * distribution Id of the edit window is different then the "existingDs" */ - if (existingDs != null && !existingDs.getId().equals(editDistId)) { + if (existingDs.isPresent() && !existingDs.get().getId().equals(editDistId)) { distNameTextField.addStyleName(SPUIStyleDefinitions.SP_TEXTFIELD_LAYOUT_ERROR_HIGHTLIGHT); distVersionTextField.addStyleName(SPUIStyleDefinitions.SP_TEXTFIELD_LAYOUT_ERROR_HIGHTLIGHT); - notificationMessage.displayValidationError( - i18n.get("message.duplicate.dist", new Object[] { existingDs.getName(), existingDs.getVersion() })); + notificationMessage.displayValidationError(i18n.get("message.duplicate.dist", + new Object[] { existingDs.get().getName(), existingDs.get().getVersion() })); return true; } @@ -291,21 +293,22 @@ public class DistributionAddUpdateWindowLayout extends CustomComponent { return; } - final DistributionSet distSet = distributionSetManagement.findDistributionSetByIdWithDetails(editDistId); - if (distSet == null) { + final Optional distSet = distributionSetManagement + .findDistributionSetByIdWithDetails(editDistId); + if (!distSet.isPresent()) { return; } editDistribution = Boolean.TRUE; - distNameTextField.setValue(distSet.getName()); - distVersionTextField.setValue(distSet.getVersion()); - if (distSet.getType().isDeleted()) { - distsetTypeNameComboBox.addItem(distSet.getType().getId()); + distNameTextField.setValue(distSet.get().getName()); + distVersionTextField.setValue(distSet.get().getVersion()); + if (distSet.get().getType().isDeleted()) { + distsetTypeNameComboBox.addItem(distSet.get().getType().getId()); } - distsetTypeNameComboBox.setValue(distSet.getType().getId()); + distsetTypeNameComboBox.setValue(distSet.get().getType().getId()); - reqMigStepCheckbox.setValue(distSet.isRequiredMigrationStep()); - descTextArea.setValue(distSet.getDescription()); + reqMigStepCheckbox.setValue(distSet.get().isRequiredMigrationStep()); + descTextArea.setValue(distSet.get().getDescription()); } /** diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionDetails.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionDetails.java index 1375f6219..240522d57 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionDetails.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionDetails.java @@ -8,6 +8,8 @@ */ package org.eclipse.hawkbit.ui.management.dstable; +import java.util.Optional; + import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.TagManagement; @@ -195,12 +197,13 @@ public class DistributionDetails extends AbstractNamedVersionedEntityTableDetail @Override protected void showMetadata(final ClickEvent event) { - final DistributionSet ds = distributionSetManagement.findDistributionSetById(getSelectedBaseEntityId()); - if (ds == null) { + final Optional ds = distributionSetManagement + .findDistributionSetById(getSelectedBaseEntityId()); + if (!ds.isPresent()) { notificationMessage.displayWarning(getI18n().get("distributionset.not.exists")); return; } - UI.getCurrent().addWindow(dsMetadataPopupLayout.getWindow(ds, null)); + UI.getCurrent().addWindow(dsMetadataPopupLayout.getWindow(ds.get(), null)); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionTable.java index 841c830e1..625f8b931 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionTable.java @@ -13,6 +13,7 @@ import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -117,8 +118,8 @@ public class DistributionTable extends AbstractNamedVersionTable event.getEntityId().equals(lastSelectedDsIdName)) - .findFirst().ifPresent(event -> eventBus.publish(this, + eventContainer.getEvents().stream().filter(event -> event.getEntityId().equals(lastSelectedDsIdName)).findAny() + .ifPresent(event -> eventBus.publish(this, new DistributionTableEvent(BaseEntityEventType.SELECTED_ENTITY, event.getEntity()))); } @@ -303,7 +304,7 @@ public class DistributionTable extends AbstractNamedVersionTable findEntityByTableValue(final Long lastSelectedId) { return distributionSetManagement.findDistributionSetByIdWithDetails(lastSelectedId); } @@ -425,13 +426,14 @@ public class DistributionTable extends AbstractNamedVersionTable findDistributionSetById = distributionSetManagement + .findDistributionSetById(distId); + if (!findDistributionSetById.isPresent()) { notification.displayWarning(i18n.get("distributionset.not.exists")); return; } - showOrHidePopupAndNotification(validate(targetDetailsList, findDistributionSetById)); + showOrHidePopupAndNotification(validate(targetDetailsList, findDistributionSetById.get())); } @Override @@ -526,12 +528,12 @@ public class DistributionTable extends AbstractNamedVersionTable targetObj = targetService.findTargetByControllerIDWithDetails( managementUIState.getDistributionTableFilters().getPinnedTarget().get().getControllerId()); - if (targetObj != null) { - final DistributionSet assignedDistribution = targetObj.getAssignedDistributionSet(); - final DistributionSet installedDistribution = targetObj.getTargetInfo().getInstalledDistributionSet(); + if (targetObj.isPresent()) { + final DistributionSet assignedDistribution = targetObj.get().getAssignedDistributionSet(); + final DistributionSet installedDistribution = targetObj.get().getTargetInfo().getInstalledDistributionSet(); Long installedDistId = null; Long assignedDistId = null; if (null != installedDistribution) { @@ -717,12 +719,12 @@ public class DistributionTable extends AbstractNamedVersionTable ds = distributionSetManagement.findDistributionSetById((Long) itemId); + if (!ds.isPresent()) { notification.displayWarning(i18n.get("distributionset.not.exists")); return; } - UI.getCurrent().addWindow(dsMetadataPopupLayout.getWindow(ds, null)); + UI.getCurrent().addWindow(dsMetadataPopupLayout.getWindow(ds.get(), null)); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/CreateUpdateDistributionTagLayoutWindow.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/CreateUpdateDistributionTagLayoutWindow.java index 14e015aa1..88c2ac700 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/CreateUpdateDistributionTagLayoutWindow.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/CreateUpdateDistributionTagLayoutWindow.java @@ -11,9 +11,11 @@ package org.eclipse.hawkbit.ui.management.dstag; import static org.apache.commons.lang3.StringUtils.isNotEmpty; import java.util.List; +import java.util.Optional; import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.TagManagement; +import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.ui.SpPermissionChecker; import org.eclipse.hawkbit.ui.colorpicker.ColorPickerConstants; @@ -69,12 +71,12 @@ public class CreateUpdateDistributionTagLayoutWindow extends AbstractCreateUpdat @Override protected void updateEntity(final DistributionSetTag entity) { - updateExistingTag(findEntityByName()); - + updateExistingTag(findEntityByName() + .orElseThrow(() -> new EntityNotFoundException(DistributionSetTag.class, tagName.getValue()))); } @Override - protected DistributionSetTag findEntityByName() { + protected Optional findEntityByName() { return tagManagement.findDistributionSetTag(tagName.getValue()); } @@ -136,14 +138,14 @@ public class CreateUpdateDistributionTagLayoutWindow extends AbstractCreateUpdat @Override public void setTagDetails(final String distTagSelected) { tagName.setValue(distTagSelected); - final DistributionSetTag selectedDistTag = tagManagement.findDistributionSetTag(distTagSelected); - if (null != selectedDistTag) { - tagDesc.setValue(selectedDistTag.getDescription()); - if (null == selectedDistTag.getColour()) { + final Optional selectedDistTag = tagManagement.findDistributionSetTag(distTagSelected); + if (selectedDistTag.isPresent()) { + tagDesc.setValue(selectedDistTag.get().getDescription()); + if (null == selectedDistTag.get().getColour()) { setTagColor(getColorPickerLayout().getDefaultColor(), ColorPickerConstants.DEFAULT_COLOR); } else { - setTagColor(ColorPickerHelper.rgbToColorConverter(selectedDistTag.getColour()), - selectedDistTag.getColour()); + setTagColor(ColorPickerHelper.rgbToColorConverter(selectedDistTag.get().getColour()), + selectedDistTag.get().getColour()); } } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/DeleteActionsLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/DeleteActionsLayout.java index 3448bd6b3..8a220bc68 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/DeleteActionsLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/DeleteActionsLayout.java @@ -11,6 +11,7 @@ package org.eclipse.hawkbit.ui.management.footer; import java.util.Arrays; import java.util.Collection; import java.util.List; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -330,13 +331,14 @@ public class DeleteActionsLayout extends AbstractDeleteActionsLayout { private boolean isDsInUseInBulkUpload(final Set distributionIdNameSet, final Long dsInBulkUpload) { if (distributionIdNameSet.contains(dsInBulkUpload)) { - final DistributionSet distributionSet = distributionSetManagement.findDistributionSetById(dsInBulkUpload); - if (distributionSet == null) { + final Optional distributionSet = distributionSetManagement + .findDistributionSetById(dsInBulkUpload); + if (!distributionSet.isPresent()) { notification.displayWarning(i18n.get("distributionset.not.exists")); return true; } notification.displayValidationError(i18n.get("message.tag.use.bulk.upload", HawkbitCommonUtil - .getFormattedNameVersion(distributionSet.getName(), distributionSet.getVersion()))); + .getFormattedNameVersion(distributionSet.get().getName(), distributionSet.get().getVersion()))); return true; } return false; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/BulkUploadHandler.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/BulkUploadHandler.java index 720c36445..bc4563113 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/BulkUploadHandler.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/BulkUploadHandler.java @@ -304,7 +304,7 @@ public class BulkUploadHandler extends CustomComponent final TargetBulkUpload targetBulkUpload = managementUIState.getTargetTableFilters().getBulkUpload(); final List targetsList = targetBulkUpload.getTargetsCreated(); final Long dsSelected = (Long) comboBox.getValue(); - if (distributionSetManagement.findDistributionSetById(dsSelected) == null) { + if (!distributionSetManagement.findDistributionSetById(dsSelected).isPresent()) { return i18n.get("message.bulk.upload.assignment.failed"); } deploymentManagement.assignDistributionSet(targetBulkUpload.getDsNameAndVersion(), actionType, @@ -316,7 +316,7 @@ public class BulkUploadHandler extends CustomComponent final Map tokensSelected = targetBulkTokenTags.getTokensAdded(); final List deletedTags = new ArrayList<>(); for (final TagData tagData : tokensSelected.values()) { - if (tagManagement.findTargetTagById(tagData.getId()) == null) { + if (!tagManagement.findTargetTagById(tagData.getId()).isPresent()) { deletedTags.add(tagData.getName()); } else { targetManagement.toggleTagAssignment( diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetAddUpdateWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetAddUpdateWindowLayout.java index 67b015c56..72ef34df7 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetAddUpdateWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetAddUpdateWindowLayout.java @@ -8,6 +8,8 @@ */ package org.eclipse.hawkbit.ui.management.targettable; +import java.util.Optional; + import org.apache.commons.lang3.StringUtils; import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.TargetManagement; @@ -162,12 +164,12 @@ public class TargetAddUpdateWindowLayout extends CustomComponent { * @return window or {@code null} if target is not exists. */ public Window getWindow(final String controllerId) { - final Target target = targetManagement.findTargetByControllerID(controllerId); - if (target == null) { + final Optional target = targetManagement.findTargetByControllerID(controllerId); + if (!target.isPresent()) { uINotification.displayWarning(i18n.get("target.not.exists", new Object[] { controllerId })); return null; } - populateValuesOfTarget(target); + populateValuesOfTarget(target.get()); createNewWindow(); window.addStyleName("target-update-window"); return window; @@ -188,8 +190,8 @@ public class TargetAddUpdateWindowLayout extends CustomComponent { private boolean isDuplicate() { final String newControlllerId = controllerIDTextField.getValue(); - final Target existingTarget = targetManagement.findTargetByControllerID(newControlllerId.trim()); - if (existingTarget != null) { + final Optional existingTarget = targetManagement.findTargetByControllerID(newControlllerId.trim()); + if (existingTarget.isPresent()) { uINotification.displayValidationError( i18n.get("message.target.duplicate.check", new Object[] { newControlllerId })); return true; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetBeanQuery.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetBeanQuery.java index 285362a5b..3203f803f 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetBeanQuery.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetBeanQuery.java @@ -150,7 +150,8 @@ public class TargetBeanQuery extends AbstractBeanQuery { prxyTarget.setInstalledDistributionSet(null); prxyTarget.setAssignedDistributionSet(null); } else { - final Target target = getTargetManagement().findTargetByControllerIDWithDetails(targ.getControllerId()); + final Target target = getTargetManagement().findTargetByControllerIDWithDetails(targ.getControllerId()) + .get(); final DistributionSet installedDistributionSet = target.getTargetInfo().getInstalledDistributionSet(); prxyTarget.setInstalledDistributionSet(installedDistributionSet); final DistributionSet assignedDistributionSet = target.getAssignedDistributionSet(); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetBulkTokenTags.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetBulkTokenTags.java index f229fc288..b8cbbc1a9 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetBulkTokenTags.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetBulkTokenTags.java @@ -17,6 +17,7 @@ import org.eclipse.hawkbit.ui.common.tagdetails.AbstractTargetTagToken; import org.eclipse.hawkbit.ui.management.state.ManagementUIState; import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.UINotification; +import org.springframework.data.domain.PageRequest; import org.vaadin.spring.events.EventBus.UIEventBus; /** @@ -26,6 +27,8 @@ import org.vaadin.spring.events.EventBus.UIEventBus; public class TargetBulkTokenTags extends AbstractTargetTagToken { private static final long serialVersionUID = 4159616629565523717L; + private static final int MAX_TAGS = 500; + TargetBulkTokenTags(final SpPermissionChecker checker, final I18N i18n, final UINotification uinotification, final UIEventBus eventBus, final ManagementUIState managementUIState, final TagManagement tagManagement) { super(checker, i18n, uinotification, eventBus, managementUIState, tagManagement); @@ -65,7 +68,7 @@ public class TargetBulkTokenTags extends AbstractTargetTagToken { protected void addAlreadySelectedTags() { for (final String tagName : managementUIState.getTargetTableFilters().getBulkUpload().getAssignedTagNames()) { - addNewToken(tagManagement.findTargetTag(tagName).getId()); + addNewToken(tagManagement.findTargetTag(tagName).get().getId()); } } @@ -73,7 +76,7 @@ public class TargetBulkTokenTags extends AbstractTargetTagToken { protected void populateContainer() { container.removeAllItems(); tagDetails.clear(); - for (final TargetTag tag : tagManagement.findAllTargetTags()) { + for (final TargetTag tag : tagManagement.findAllTargetTags(new PageRequest(0, MAX_TAGS))) { setContainerPropertValues(tag.getId(), tag.getName(), tag.getColour()); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTable.java index cfd9a4a4e..8abfb4044 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTable.java @@ -22,6 +22,7 @@ import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -295,7 +296,7 @@ public class TargetTable extends AbstractTable { } @Override - protected Target findEntityByTableValue(final Long lastSelectedId) { + protected Optional findEntityByTableValue(final Long lastSelectedId) { return targetManagement.findTargetById(lastSelectedId); } @@ -540,8 +541,8 @@ public class TargetTable extends AbstractTable { Lists.newArrayListWithCapacity(0), null); } - final TargetTag tag = tagManagement.findTargetTag(targTagName); - if (tag == null) { + final Optional tag = tagManagement.findTargetTag(targTagName); + if (!tag.isPresent()) { notification.displayWarning(i18n.get("targettag.not.exists", new Object[] { targTagName })); return new TargetTagAssignmentResult(0, 0, 0, Lists.newArrayListWithCapacity(0), Lists.newArrayListWithCapacity(0), null); @@ -594,12 +595,12 @@ public class TargetTable extends AbstractTable { return; } final Long targetId = (Long) targetItemId; - final Target target = targetManagement.findTargetById(targetId); - if (target == null) { + final Optional target = targetManagement.findTargetById(targetId); + if (!target.isPresent()) { getNotification().displayWarning(i18n.get("target.not.exists", new Object[] { "" })); return; } - final TargetIdName createTargetIdName = new TargetIdName(target); + final TargetIdName createTargetIdName = new TargetIdName(target.get()); final List findDistributionSetAllById = distributionSetManagement .findDistributionSetAllById(ids); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTableHeader.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTableHeader.java index eaf6f094c..c45183034 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTableHeader.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTableHeader.java @@ -8,6 +8,7 @@ */ package org.eclipse.hawkbit.ui.management.targettable; +import java.util.Optional; import java.util.Set; import java.util.concurrent.Executor; @@ -339,13 +340,13 @@ public class TargetTableHeader extends AbstractTableHeader { return; } final Long distributionSetId = distributionIdSet.iterator().next(); - final DistributionSet distributionSet = distributionSetManagement + final Optional distributionSet = distributionSetManagement .findDistributionSetById(distributionSetId); - if (distributionSet == null) { + if (!distributionSet.isPresent()) { notification.displayWarning(i18n.get("distributionset.not.exists")); return; } - final DistributionSetIdName distributionSetIdName = new DistributionSetIdName(distributionSet); + final DistributionSetIdName distributionSetIdName = new DistributionSetIdName(distributionSet.get()); managementUIState.getTargetTableFilters().setDistributionSet(distributionSetIdName); addFilterTextField(distributionSetIdName); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/CreateUpdateTargetTagLayoutWindow.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/CreateUpdateTargetTagLayoutWindow.java index cd3e5f24e..d2ae42aa6 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/CreateUpdateTargetTagLayoutWindow.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/CreateUpdateTargetTagLayoutWindow.java @@ -10,7 +10,7 @@ package org.eclipse.hawkbit.ui.management.targettag; import static org.apache.commons.lang3.StringUtils.isNotEmpty; -import java.util.List; +import java.util.Optional; import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.TagManagement; @@ -25,6 +25,7 @@ import org.eclipse.hawkbit.ui.management.event.TargetTagTableEvent; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.UINotification; +import org.springframework.data.domain.PageRequest; import org.vaadin.spring.events.EventBus.UIEventBus; /** @@ -35,6 +36,8 @@ public class CreateUpdateTargetTagLayoutWindow extends AbstractCreateUpdateTagLa private static final long serialVersionUID = 2446682350481560235L; + private static final int MAX_TAGS = 500; + /** * Constructor for CreateUpdateTargetTagLayoutWindow * @@ -69,8 +72,8 @@ public class CreateUpdateTargetTagLayoutWindow extends AbstractCreateUpdateTagLa @Override public void populateTagNameCombo() { tagNameComboBox.removeAllItems(); - final List trgTagNameList = tagManagement.findAllTargetTags(); - trgTagNameList.forEach(value -> tagNameComboBox.addItem(value.getName())); + tagManagement.findAllTargetTags(new PageRequest(0, MAX_TAGS)) + .forEach(value -> tagNameComboBox.addItem(value.getName())); } /** @@ -83,14 +86,14 @@ public class CreateUpdateTargetTagLayoutWindow extends AbstractCreateUpdateTagLa @Override public void setTagDetails(final String targetTagSelected) { tagName.setValue(targetTagSelected); - final TargetTag selectedTargetTag = tagManagement.findTargetTag(targetTagSelected); - if (selectedTargetTag != null) { - tagDesc.setValue(selectedTargetTag.getDescription()); - if (null == selectedTargetTag.getColour()) { + final Optional selectedTargetTag = tagManagement.findTargetTag(targetTagSelected); + if (selectedTargetTag.isPresent()) { + tagDesc.setValue(selectedTargetTag.get().getDescription()); + if (null == selectedTargetTag.get().getColour()) { setTagColor(getColorPickerLayout().getDefaultColor(), ColorPickerConstants.DEFAULT_COLOR); } else { - setTagColor(ColorPickerHelper.rgbToColorConverter(selectedTargetTag.getColour()), - selectedTargetTag.getColour()); + setTagColor(ColorPickerHelper.rgbToColorConverter(selectedTargetTag.get().getColour()), + selectedTargetTag.get().getColour()); } } } @@ -106,7 +109,7 @@ public class CreateUpdateTargetTagLayoutWindow extends AbstractCreateUpdateTagLa } @Override - protected TargetTag findEntityByName() { + protected Optional findEntityByName() { return tagManagement.findTargetTag(tagName.getValue()); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/CustomTargetTagFilterButtonClick.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/CustomTargetTagFilterButtonClick.java index 319b7fd2b..8cd112ce3 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/CustomTargetTagFilterButtonClick.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/CustomTargetTagFilterButtonClick.java @@ -52,7 +52,7 @@ public class CustomTargetTagFilterButtonClick extends AbstractFilterSingleButton @Override protected void filterClicked(final Button clickedButton) { final TargetFilterQuery targetFilterQuery = this.targetFilterQueryManagement - .findTargetFilterQueryById((Long) clickedButton.getData()); + .findTargetFilterQueryById((Long) clickedButton.getData()).get(); this.managementUIState.getTargetTableFilters().setTargetFilterQuery(targetFilterQuery.getId()); this.eventBus.publish(this, TargetFilterEvent.FILTER_BY_TARGET_FILTER_QUERY); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/menu/DashboardMenu.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/menu/DashboardMenu.java index de1fc1a80..61cd0c36c 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/menu/DashboardMenu.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/menu/DashboardMenu.java @@ -331,7 +331,7 @@ public final class DashboardMenu extends CustomComponent { */ public DashboardMenuItem getByViewName(final String viewName) { final Optional findFirst = dashboardVaadinViews.stream() - .filter(view -> view.getViewName().equals(viewName)).findFirst(); + .filter(view -> view.getViewName().equals(viewName)).findAny(); if (!findFirst.isPresent()) { return null; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/groupschart/GroupsPieChart.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/groupschart/GroupsPieChart.java index 9e86a1c49..5f14cda26 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/groupschart/GroupsPieChart.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/groupschart/GroupsPieChart.java @@ -8,11 +8,12 @@ */ package org.eclipse.hawkbit.ui.rollout.groupschart; -import org.eclipse.hawkbit.ui.rollout.groupschart.client.GroupsPieChartState; -import com.vaadin.ui.AbstractComponent; - import java.util.List; +import org.eclipse.hawkbit.ui.rollout.groupschart.client.GroupsPieChartState; + +import com.vaadin.ui.AbstractComponent; + /** * Draws a pie charts for the provided groups. */ diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/groupschart/client/GroupsPieChartConnector.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/groupschart/client/GroupsPieChartConnector.java index 9fd171327..e691fc7e1 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/groupschart/client/GroupsPieChartConnector.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/groupschart/client/GroupsPieChartConnector.java @@ -8,10 +8,11 @@ */ package org.eclipse.hawkbit.ui.rollout.groupschart.client; -import com.vaadin.client.communication.StateChangeEvent; import org.eclipse.hawkbit.ui.rollout.groupschart.GroupsPieChart; + import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.ui.Widget; +import com.vaadin.client.communication.StateChangeEvent; import com.vaadin.client.ui.AbstractComponentConnector; import com.vaadin.shared.ui.Connect; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/groupschart/client/GroupsPieChartState.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/groupschart/client/GroupsPieChartState.java index be8537fe6..a6ac99ce9 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/groupschart/client/GroupsPieChartState.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/groupschart/client/GroupsPieChartState.java @@ -8,10 +8,10 @@ */ package org.eclipse.hawkbit.ui.rollout.groupschart.client; -import com.vaadin.shared.AbstractComponentState; - import java.util.List; +import com.vaadin.shared.AbstractComponentState; + /** * State to transfer for the groups pie chart between server and client. */ diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/AddUpdateRolloutWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/AddUpdateRolloutWindowLayout.java index c8898a6aa..feef858fe 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/AddUpdateRolloutWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/AddUpdateRolloutWindowLayout.java @@ -620,7 +620,8 @@ public class AddUpdateRolloutWindowLayout extends GridLayout { private boolean duplicateCheckForEdit() { final String rolloutNameVal = getRolloutName(); - if (!rollout.getName().equals(rolloutNameVal) && rolloutManagement.findRolloutByName(rolloutNameVal) != null) { + if (!rollout.getName().equals(rolloutNameVal) + && rolloutManagement.findRolloutByName(rolloutNameVal).isPresent()) { uiNotification.displayValidationError(i18n.get("message.rollout.duplicate.check", rolloutNameVal)); return false; } @@ -707,7 +708,7 @@ public class AddUpdateRolloutWindowLayout extends GridLayout { } private boolean duplicateCheck() { - if (rolloutManagement.findRolloutByName(getRolloutName()) != null) { + if (rolloutManagement.findRolloutByName(getRolloutName()).isPresent()) { uiNotification.displayValidationError(i18n.get("message.rollout.duplicate.check", getRolloutName())); return false; } @@ -854,7 +855,7 @@ public class AddUpdateRolloutWindowLayout extends GridLayout { return; } - rollout = rolloutManagement.findRolloutById(rolloutId); + rollout = rolloutManagement.findRolloutById(rolloutId).get(); description.setValue(rollout.getDescription()); distributionSet.setValue(rollout.getDistributionSet().getId()); setActionType(rollout); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/DefineGroupsLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/DefineGroupsLayout.java index 0be334ee7..16d4f54c8 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/DefineGroupsLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/DefineGroupsLayout.java @@ -12,7 +12,6 @@ import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; -import com.vaadin.ui.UI; import org.apache.commons.lang3.StringUtils; import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.RolloutManagement; @@ -60,6 +59,7 @@ import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.TextArea; import com.vaadin.ui.TextField; +import com.vaadin.ui.UI; /** * Define groups for a Rollout @@ -278,8 +278,8 @@ public class DefineGroupsLayout extends GridLayout { final UI ui = UI.getCurrent(); - runningValidation = rolloutManagement - .validateTargetsInGroups(savedRolloutGroups, targetFilter, System.currentTimeMillis()); + runningValidation = rolloutManagement.validateTargetsInGroups(savedRolloutGroups, targetFilter, + System.currentTimeMillis()); runningValidation.addCallback(validation -> ui.access(() -> this.setGroupsValidation(validation)), throwable -> ui.access(() -> this.setGroupsValidation(null))); @@ -288,7 +288,7 @@ public class DefineGroupsLayout extends GridLayout { private void setGroupsValidation(RolloutGroupsValidation validation) { groupsValidation = validation; - if(validationRequested) { + if (validationRequested) { validateRemainingTargets(); return; } @@ -317,9 +317,7 @@ public class DefineGroupsLayout extends GridLayout { * Status of the groups validation */ public enum ValidationStatus { - VALID, - INVALID, - LOADING + VALID, INVALID, LOADING } /** @@ -337,7 +335,6 @@ public class DefineGroupsLayout extends GridLayout { void validation(ValidationStatus isValid); } - private class GroupRow { private TextField groupName; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/GroupsLegendLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/GroupsLegendLayout.java index 7bf1a3857..c2afb0759 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/GroupsLegendLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/GroupsLegendLayout.java @@ -8,17 +8,18 @@ */ package org.eclipse.hawkbit.ui.rollout.rollout; -import com.vaadin.ui.Component; -import com.vaadin.ui.Label; -import com.vaadin.ui.VerticalLayout; +import java.util.Collections; +import java.util.List; + import org.eclipse.hawkbit.repository.builder.RolloutGroupCreate; import org.eclipse.hawkbit.repository.model.RolloutGroup; import org.eclipse.hawkbit.repository.model.RolloutGroupsValidation; import org.eclipse.hawkbit.ui.common.builder.LabelBuilder; import org.eclipse.hawkbit.ui.utils.I18N; -import java.util.Collections; -import java.util.List; +import com.vaadin.ui.Component; +import com.vaadin.ui.Label; +import com.vaadin.ui.VerticalLayout; /** * Displays a legend for the Groups of a Rollout with the count of targets in @@ -112,8 +113,8 @@ public class GroupsLegendLayout extends VerticalLayout { } /** - * Display an indication that the legend is being calculated. - * When the loading process is done one of the populate methods should be called. + * Display an indication that the legend is being calculated. When the + * loading process is done one of the populate methods should be called. */ public void displayLoading() { populateGroupsLegendByTargetCounts(Collections.emptyList()); @@ -178,7 +179,8 @@ public class GroupsLegendLayout extends VerticalLayout { * @param groups * List of groups with their name */ - public void populateGroupsLegendByValidation(final RolloutGroupsValidation validation, final List groups) { + public void populateGroupsLegendByValidation(final RolloutGroupsValidation validation, + final List groups) { loadingLabel.setVisible(false); if (validation == null) { return; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutListGrid.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutListGrid.java index 7ca4ab692..3b9063133 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutListGrid.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutListGrid.java @@ -177,7 +177,8 @@ public class RolloutListGrid extends AbstractGrid { if (!rolloutUIState.isShowRollOuts()) { return; } - final Rollout rollout = rolloutManagement.findRolloutWithDetailedStatus(rolloutChangeEvent.getRolloutId()); + final Rollout rollout = rolloutManagement.findRolloutWithDetailedStatus(rolloutChangeEvent.getRolloutId()) + .get(); final TotalTargetCountStatus totalTargetCountStatus = rollout.getTotalTargetCountStatus(); final LazyQueryContainer rolloutContainer = (LazyQueryContainer) getContainerDataSource(); final Item item = rolloutContainer.getItem(rolloutChangeEvent.getRolloutId()); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupListGrid.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupListGrid.java index 1e1b29cc8..9670a77e5 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupListGrid.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupListGrid.java @@ -287,7 +287,7 @@ public class RolloutGroupListGrid extends AbstractGrid { @Override public void click(final RendererClickEvent event) { rolloutUIState.setRolloutGroup( - rolloutGroupManagement.findRolloutGroupWithDetailedStatus((Long) event.getItemId())); + rolloutGroupManagement.findRolloutGroupWithDetailedStatus((Long) event.getItemId()).get()); eventBus.publish(this, RolloutEvent.SHOW_ROLLOUT_GROUP_TARGETS); } } diff --git a/hawkbit-ui/src/test/java/org/eclipse/hawkbit/push/SpringSecurityAtmosphereInterceptorTest.java b/hawkbit-ui/src/test/java/org/eclipse/hawkbit/push/SpringSecurityAtmosphereInterceptorTest.java index 0aa4c7fae..a1cc4b343 100644 --- a/hawkbit-ui/src/test/java/org/eclipse/hawkbit/push/SpringSecurityAtmosphereInterceptorTest.java +++ b/hawkbit-ui/src/test/java/org/eclipse/hawkbit/push/SpringSecurityAtmosphereInterceptorTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.push; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; import javax.servlet.http.HttpSession; diff --git a/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/dd/client/criteria/ItemIdClientCriterionTest.java b/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/dd/client/criteria/ItemIdClientCriterionTest.java index 2f6bc9af9..f8f718aeb 100644 --- a/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/dd/client/criteria/ItemIdClientCriterionTest.java +++ b/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/dd/client/criteria/ItemIdClientCriterionTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.ui.dd.client.criteria; -import static org.fest.assertions.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; import org.junit.Test; diff --git a/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/dd/client/criteria/ViewClientCriterionTest.java b/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/dd/client/criteria/ViewClientCriterionTest.java index 19e8987a2..675d55bb1 100644 --- a/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/dd/client/criteria/ViewClientCriterionTest.java +++ b/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/dd/client/criteria/ViewClientCriterionTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.ui.dd.client.criteria; -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.Matchers.any; import static org.mockito.Mockito.doThrow; diff --git a/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/dd/client/criteria/ViewComponentClientCriterionTest.java b/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/dd/client/criteria/ViewComponentClientCriterionTest.java index f8a058352..ffbd4f50f 100644 --- a/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/dd/client/criteria/ViewComponentClientCriterionTest.java +++ b/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/dd/client/criteria/ViewComponentClientCriterionTest.java @@ -8,7 +8,7 @@ */ package org.eclipse.hawkbit.ui.dd.client.criteria; -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.doThrow; import static org.mockito.Mockito.verify; diff --git a/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/utils/SPUIComponentProviderTest.java b/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/utils/SPUIComponentProviderTest.java index 57426727d..59f09ae9f 100644 --- a/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/utils/SPUIComponentProviderTest.java +++ b/hawkbit-ui/src/test/java/org/eclipse/hawkbit/ui/utils/SPUIComponentProviderTest.java @@ -8,11 +8,11 @@ */ package org.eclipse.hawkbit.ui.utils; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import org.eclipse.hawkbit.ui.components.SPUIButton; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; -import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmallNoBorderUH; +import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmall; import org.junit.Test; import com.vaadin.ui.Button; @@ -33,12 +33,12 @@ public class SPUIComponentProviderTest { * @throws Exception */ @Test - public void checkButtonFactory() throws Exception { + public void checkButtonFactory() { // Checking Dyanmic Factory - Button placeHolderButton = null; - placeHolderButton = SPUIComponentProvider.getButton("", "Test", "Test", - SPUIDefinitions.SP_BUTTON_STATUS_STYLE, true, null, SPUIButtonStyleSmallNoBorderUH.class); + Button placeHolderButton; + placeHolderButton = SPUIComponentProvider.getButton("", "Test", "Test", SPUIDefinitions.SP_BUTTON_STATUS_STYLE, + true, null, SPUIButtonStyleSmall.class); assertThat(placeHolderButton).isInstanceOf(SPUIButton.class); assertThat(placeHolderButton.getCaption()).isEqualTo("Test"); assertThat(placeHolderButton.getStyleName()).isEqualTo(SPUIDefinitions.SP_BUTTON_STATUS_STYLE); diff --git a/pom.xml b/pom.xml index 847dc7a7c..9381ceadd 100644 --- a/pom.xml +++ b/pom.xml @@ -131,8 +131,6 @@ 1.1.0.Final - 1.4 - 2.0M10 1.4.22 2.6.4 1.6.5 @@ -685,18 +683,6 @@ json ${json.version}
- - org.easytesting - fest-assert - ${fest-assert.version} - test - - - org.easytesting - fest-assert-core - ${org.easytesting.version} - test - ru.yandex.qatools.allure allure-junit-adaptor