diff --git a/hawkbit-artifact/hawkbit-artifact-api/src/main/java/org/eclipse/hawkbit/repository/artifact/AbstractArtifactRepository.java b/hawkbit-artifact/hawkbit-artifact-api/src/main/java/org/eclipse/hawkbit/repository/artifact/AbstractArtifactRepository.java index 5f4ad8653..966b88df2 100644 --- a/hawkbit-artifact/hawkbit-artifact-api/src/main/java/org/eclipse/hawkbit/repository/artifact/AbstractArtifactRepository.java +++ b/hawkbit-artifact/hawkbit-artifact-api/src/main/java/org/eclipse/hawkbit/repository/artifact/AbstractArtifactRepository.java @@ -67,8 +67,9 @@ public abstract class AbstractArtifactRepository implements ArtifactRepository { checkHashes(providedHashes, sha1Hash16, md5Hash16, sha256Hash16); // Check if file with same sha1 hash exists and if so return it - if (existsByTenantAndSha1(tenant, sha1Hash16)) { - return addMissingHashes(getArtifactBySha1(tenant, sha1Hash16), sha1Hash16, md5Hash16, sha256Hash16); + if (existsBySha1(tenant, sha1Hash16)) { + // TODO - shall check if the file is really the same as bytes or just sha1 hash is the same + return addMissingHashes(getBySha1(tenant, sha1Hash16), sha1Hash16, md5Hash16, sha256Hash16); } return store(sanitizeTenant(tenant), new DbArtifactHash(sha1Hash16, md5Hash16, sha256Hash16), contentType, tempFile); diff --git a/hawkbit-artifact/hawkbit-artifact-api/src/main/java/org/eclipse/hawkbit/repository/artifact/ArtifactRepository.java b/hawkbit-artifact/hawkbit-artifact-api/src/main/java/org/eclipse/hawkbit/repository/artifact/ArtifactRepository.java index b7d829425..b322cb465 100644 --- a/hawkbit-artifact/hawkbit-artifact-api/src/main/java/org/eclipse/hawkbit/repository/artifact/ArtifactRepository.java +++ b/hawkbit-artifact/hawkbit-artifact-api/src/main/java/org/eclipse/hawkbit/repository/artifact/ArtifactRepository.java @@ -41,6 +41,26 @@ public interface ArtifactRepository { @NotEmpty String tenant, @NotNull InputStream content, @NotEmpty String filename, String contentType, DbArtifactHash hash); + /** + * Retrieves a {@link AbstractDbArtifact} from the store by its SHA1 hash. Throws {@link org.eclipse.hawkbit.repository.artifact.exception.ArtifactBinaryNotFoundException} if not found. + * + * @param tenant the tenant to store the artifact + * @param sha1Hash the sha1-hash of the file to lookup. + * @return The artifact file object or {@code null} if no file exists. + * @throws UnsupportedOperationException if implementation does not support the operation + */ + AbstractDbArtifact getBySha1(@NotEmpty String tenant, @NotEmpty String sha1Hash); + + + /** + * Checks if an artifact exists for a given tenant by its sha1 hash + * + * @param tenant the tenant + * @param sha1Hash the sha1-hash of the file to lookup. + * @return the boolean whether the artifact exists or not + */ + boolean existsBySha1(@NotEmpty String tenant, @NotEmpty String sha1Hash); + /** * Deletes an artifact by its SHA1 hash. * @@ -50,29 +70,10 @@ public interface ArtifactRepository { */ void deleteBySha1(@NotEmpty String tenant, @NotEmpty String sha1Hash); - /** - * Retrieves a {@link AbstractDbArtifact} from the store by its SHA1 hash. - * - * @param tenant the tenant to store the artifact - * @param sha1Hash the sha1-hash of the file to lookup. - * @return The artifact file object or {@code null} if no file exists. - * @throws UnsupportedOperationException if implementation does not support the operation - */ - AbstractDbArtifact getArtifactBySha1(@NotEmpty String tenant, @NotEmpty String sha1Hash); - /** * Deletes all artifacts of given tenant. * * @param tenant to erase */ void deleteByTenant(@NotEmpty String tenant); - - /** - * Checks if an artifact exists for a given tenant by its sha1 hash - * - * @param tenant the tenant - * @param sha1Hash the sha1-hash of the file to lookup. - * @return the boolean whether the artifact exists or not - */ - boolean existsByTenantAndSha1(@NotEmpty String tenant, @NotEmpty String sha1Hash); } \ No newline at end of file diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ArtifactBinaryNoLongerExistsException.java b/hawkbit-artifact/hawkbit-artifact-api/src/main/java/org/eclipse/hawkbit/repository/artifact/exception/ArtifactBinaryNoLongerExistsException.java similarity index 88% rename from hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ArtifactBinaryNoLongerExistsException.java rename to hawkbit-artifact/hawkbit-artifact-api/src/main/java/org/eclipse/hawkbit/repository/artifact/exception/ArtifactBinaryNoLongerExistsException.java index 6c88392a7..e85e6f577 100644 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ArtifactBinaryNoLongerExistsException.java +++ b/hawkbit-artifact/hawkbit-artifact-api/src/main/java/org/eclipse/hawkbit/repository/artifact/exception/ArtifactBinaryNoLongerExistsException.java @@ -7,7 +7,7 @@ * * SPDX-License-Identifier: EPL-2.0 */ -package org.eclipse.hawkbit.repository.exception; +package org.eclipse.hawkbit.repository.artifact.exception; import java.io.Serial; @@ -15,11 +15,9 @@ import lombok.EqualsAndHashCode; import lombok.ToString; import org.eclipse.hawkbit.exception.AbstractServerRtException; import org.eclipse.hawkbit.exception.SpServerError; -import org.eclipse.hawkbit.repository.model.SoftwareModule; /** - * Exception indicating that an artifact's binary does not exist anymore. This - * might be caused due to the soft deletion of a {@link SoftwareModule}. + * Exception indicating that an artifact's binary does not exist anymore. This might be caused due to the soft deletion of a software module. */ @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ArtifactBinaryNotFoundException.java b/hawkbit-artifact/hawkbit-artifact-api/src/main/java/org/eclipse/hawkbit/repository/artifact/exception/ArtifactBinaryNotFoundException.java similarity index 95% rename from hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ArtifactBinaryNotFoundException.java rename to hawkbit-artifact/hawkbit-artifact-api/src/main/java/org/eclipse/hawkbit/repository/artifact/exception/ArtifactBinaryNotFoundException.java index 1d267b2df..5179a8e54 100644 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ArtifactBinaryNotFoundException.java +++ b/hawkbit-artifact/hawkbit-artifact-api/src/main/java/org/eclipse/hawkbit/repository/artifact/exception/ArtifactBinaryNotFoundException.java @@ -7,7 +7,7 @@ * * SPDX-License-Identifier: EPL-2.0 */ -package org.eclipse.hawkbit.repository.exception; +package org.eclipse.hawkbit.repository.artifact.exception; import java.io.Serial; diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ArtifactDeleteFailedException.java b/hawkbit-artifact/hawkbit-artifact-api/src/main/java/org/eclipse/hawkbit/repository/artifact/exception/ArtifactDeleteFailedException.java similarity index 95% rename from hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ArtifactDeleteFailedException.java rename to hawkbit-artifact/hawkbit-artifact-api/src/main/java/org/eclipse/hawkbit/repository/artifact/exception/ArtifactDeleteFailedException.java index cc151d477..0f7e05418 100644 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ArtifactDeleteFailedException.java +++ b/hawkbit-artifact/hawkbit-artifact-api/src/main/java/org/eclipse/hawkbit/repository/artifact/exception/ArtifactDeleteFailedException.java @@ -7,7 +7,7 @@ * * SPDX-License-Identifier: EPL-2.0 */ -package org.eclipse.hawkbit.repository.exception; +package org.eclipse.hawkbit.repository.artifact.exception; import java.io.Serial; diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ArtifactUploadFailedException.java b/hawkbit-artifact/hawkbit-artifact-api/src/main/java/org/eclipse/hawkbit/repository/artifact/exception/ArtifactUploadFailedException.java similarity index 96% rename from hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ArtifactUploadFailedException.java rename to hawkbit-artifact/hawkbit-artifact-api/src/main/java/org/eclipse/hawkbit/repository/artifact/exception/ArtifactUploadFailedException.java index f9e310f7e..4647b210f 100644 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/exception/ArtifactUploadFailedException.java +++ b/hawkbit-artifact/hawkbit-artifact-api/src/main/java/org/eclipse/hawkbit/repository/artifact/exception/ArtifactUploadFailedException.java @@ -7,7 +7,7 @@ * * SPDX-License-Identifier: EPL-2.0 */ -package org.eclipse.hawkbit.repository.exception; +package org.eclipse.hawkbit.repository.artifact.exception; import java.io.Serial; diff --git a/hawkbit-artifact/hawkbit-artifact-repository-filesystem/src/main/java/org/eclipse/hawkbit/repository/artifact/ArtifactFilesystemRepository.java b/hawkbit-artifact/hawkbit-artifact-repository-filesystem/src/main/java/org/eclipse/hawkbit/repository/artifact/ArtifactFilesystemRepository.java index db015d004..175817791 100644 --- a/hawkbit-artifact/hawkbit-artifact-repository-filesystem/src/main/java/org/eclipse/hawkbit/repository/artifact/ArtifactFilesystemRepository.java +++ b/hawkbit-artifact/hawkbit-artifact-repository-filesystem/src/main/java/org/eclipse/hawkbit/repository/artifact/ArtifactFilesystemRepository.java @@ -14,8 +14,10 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.Optional; import org.apache.commons.io.FileUtils; +import org.eclipse.hawkbit.repository.artifact.exception.ArtifactBinaryNotFoundException; import org.eclipse.hawkbit.repository.artifact.model.AbstractDbArtifact; import org.eclipse.hawkbit.repository.artifact.model.DbArtifactHash; import org.springframework.validation.annotation.Validated; @@ -52,10 +54,10 @@ public class ArtifactFilesystemRepository extends AbstractArtifactRepository { } @Override - public ArtifactFilesystem getArtifactBySha1(final String tenant, final String sha1) { + public AbstractDbArtifact getBySha1(final String tenant, final String sha1) { final File file = getFile(tenant, sha1); if (!file.exists()) { - return null; + throw new ArtifactBinaryNotFoundException(sha1); } return new ArtifactFilesystem(file, sha1, new DbArtifactHash(sha1, null, null), file.length(), null); @@ -67,7 +69,7 @@ public class ArtifactFilesystemRepository extends AbstractArtifactRepository { } @Override - public boolean existsByTenantAndSha1(final String tenant, final String sha1) { + public boolean existsBySha1(final String tenant, final String sha1) { return getFile(tenant, sha1).exists(); } diff --git a/hawkbit-artifact/hawkbit-artifact-repository-filesystem/src/test/java/org/eclipse/hawkbit/repository/artifact/ArtifactFilesystemRepositoryTest.java b/hawkbit-artifact/hawkbit-artifact-repository-filesystem/src/test/java/org/eclipse/hawkbit/repository/artifact/ArtifactFilesystemRepositoryTest.java index a23894020..282d4cc79 100644 --- a/hawkbit-artifact/hawkbit-artifact-repository-filesystem/src/test/java/org/eclipse/hawkbit/repository/artifact/ArtifactFilesystemRepositoryTest.java +++ b/hawkbit-artifact/hawkbit-artifact-repository-filesystem/src/test/java/org/eclipse/hawkbit/repository/artifact/ArtifactFilesystemRepositoryTest.java @@ -10,6 +10,7 @@ package org.eclipse.hawkbit.repository.artifact; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.io.ByteArrayInputStream; import java.io.File; @@ -20,16 +21,17 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.assertj.core.api.Assertions; +import org.eclipse.hawkbit.repository.artifact.exception.ArtifactBinaryNotFoundException; import org.eclipse.hawkbit.repository.artifact.model.AbstractDbArtifact; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -@Slf4j /** * Feature: Unit Tests - Artifact File System Repository
* Story: Test storing artifact binaries in the file-system */ +@Slf4j class ArtifactFilesystemRepositoryTest { private static final String TENANT = "test_tenant"; @@ -77,7 +79,7 @@ class ArtifactFilesystemRepositoryTest { final byte[] fileContent = randomBytes(); final AbstractDbArtifact artifact = storeRandomArtifact(fileContent); - assertThat(artifactFilesystemRepository.getArtifactBySha1(TENANT, artifact.getHashes().getSha1())).isNotNull(); + assertThat(artifactFilesystemRepository.getBySha1(TENANT, artifact.getHashes().getSha1())).isNotNull(); } /** @@ -88,7 +90,9 @@ class ArtifactFilesystemRepositoryTest { final AbstractDbArtifact artifact = storeRandomArtifact(randomBytes()); artifactFilesystemRepository.deleteBySha1(TENANT, artifact.getHashes().getSha1()); - assertThat(artifactFilesystemRepository.getArtifactBySha1(TENANT, artifact.getHashes().getSha1())).isNull(); + final String sha1Hash = artifact.getHashes().getSha1(); + assertThatExceptionOfType(ArtifactBinaryNotFoundException.class) + .isThrownBy(() -> artifactFilesystemRepository.getBySha1(TENANT, sha1Hash)); } /** @@ -99,7 +103,9 @@ class ArtifactFilesystemRepositoryTest { final AbstractDbArtifact artifact = storeRandomArtifact(randomBytes()); artifactFilesystemRepository.deleteByTenant(TENANT); - assertThat(artifactFilesystemRepository.getArtifactBySha1(TENANT, artifact.getHashes().getSha1())).isNull(); + final String sha1Hash = artifact.getHashes().getSha1(); + assertThatExceptionOfType(ArtifactBinaryNotFoundException.class) + .isThrownBy(() -> artifactFilesystemRepository.getBySha1(TENANT, sha1Hash)); } /** diff --git a/hawkbit-ddi/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootController.java b/hawkbit-ddi/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootController.java index f1af927e7..45690f43d 100644 --- a/hawkbit-ddi/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootController.java +++ b/hawkbit-ddi/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootController.java @@ -53,7 +53,6 @@ import org.eclipse.hawkbit.repository.UpdateMode; import org.eclipse.hawkbit.repository.artifact.model.DbArtifact; import org.eclipse.hawkbit.repository.artifact.urlhandler.ArtifactUrlHandler; import org.eclipse.hawkbit.repository.event.remote.DownloadProgressEvent; -import org.eclipse.hawkbit.repository.exception.ArtifactBinaryNotFoundException; import org.eclipse.hawkbit.repository.exception.CancelActionNotAllowedException; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.exception.InvalidConfirmationFeedbackException; @@ -180,9 +179,7 @@ public class DdiRootController implements DdiRootControllerRestApi { } else { // Artifact presence is ensured in 'checkModule' final Artifact artifact = module.getArtifactByFilename(fileName).orElseThrow(NoSuchElementException::new); - final DbArtifact file = artifactManagement - .loadArtifactBinary(artifact.getSha1Hash(), module.getId(), module.isEncrypted()) - .orElseThrow(() -> new ArtifactBinaryNotFoundException(artifact.getSha1Hash())); + final DbArtifact file = artifactManagement.loadArtifactBinary(artifact.getSha1Hash(), module.getId(), module.isEncrypted()); final String ifMatch = RequestResponseContextHolder.getHttpServletRequest().getHeader(HttpHeaders.IF_MATCH); if (ifMatch != null && !HttpUtil.matchesHttpHeader(ifMatch, artifact.getSha1Hash())) { @@ -694,7 +691,7 @@ public class DdiRootController implements DdiRootControllerRestApi { } private Target findTarget(final String controllerId) { - return controllerManagement.getByControllerId(controllerId) + return controllerManagement.findByControllerId(controllerId) .orElseThrow(() -> new EntityNotFoundException(Target.class, controllerId)); } diff --git a/hawkbit-ddi/hawkbit-ddi-security/src/main/java/org/eclipse/hawkbit/security/controller/SecurityTokenAuthenticator.java b/hawkbit-ddi/hawkbit-ddi-security/src/main/java/org/eclipse/hawkbit/security/controller/SecurityTokenAuthenticator.java index 4791ffd0d..d4162f3d6 100644 --- a/hawkbit-ddi/hawkbit-ddi-security/src/main/java/org/eclipse/hawkbit/security/controller/SecurityTokenAuthenticator.java +++ b/hawkbit-ddi/hawkbit-ddi-security/src/main/java/org/eclipse/hawkbit/security/controller/SecurityTokenAuthenticator.java @@ -60,8 +60,8 @@ public class SecurityTokenAuthenticator extends Authenticator.AbstractAuthentica final String presentedToken = authHeader.substring(OFFSET_TARGET_TOKEN); return systemSecurityContext.runAsSystemAsTenant(() -> controllerSecurityToken.getTargetId() != null - ? controllerManagement.get(controllerSecurityToken.getTargetId()) - : controllerManagement.getByControllerId(controllerSecurityToken.getControllerId()), + ? controllerManagement.find(controllerSecurityToken.getTargetId()) + : controllerManagement.findByControllerId(controllerSecurityToken.getControllerId()), controllerSecurityToken.getTenant()) // validate if the presented token is the same as the one set for the target .filter(target -> presentedToken.equals( diff --git a/hawkbit-ddi/hawkbit-ddi-security/src/test/java/org/eclipse/hawkbit/security/controller/SecurityTokenAuthenticatorTest.java b/hawkbit-ddi/hawkbit-ddi-security/src/test/java/org/eclipse/hawkbit/security/controller/SecurityTokenAuthenticatorTest.java index f782f5963..008438c0d 100644 --- a/hawkbit-ddi/hawkbit-ddi-security/src/test/java/org/eclipse/hawkbit/security/controller/SecurityTokenAuthenticatorTest.java +++ b/hawkbit-ddi/hawkbit-ddi-security/src/test/java/org/eclipse/hawkbit/security/controller/SecurityTokenAuthenticatorTest.java @@ -78,7 +78,7 @@ class SecurityTokenAuthenticatorTest { final Target target = Mockito.mock(Target.class); when(target.getControllerId()).thenReturn(CONTROLLER_ID); when(target.getSecurityToken()).thenReturn(SECURITY_TOKEN); - when(controllerManagementMock.getByControllerId(CONTROLLER_ID)).thenReturn(Optional.of(target)); + when(controllerManagementMock.findByControllerId(CONTROLLER_ID)).thenReturn(Optional.of(target)); assertThat(authenticator.authenticate(securityToken)) .isNotNull() diff --git a/hawkbit-dmf/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherService.java b/hawkbit-dmf/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherService.java index 193bbff16..fd8657ee7 100644 --- a/hawkbit-dmf/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherService.java +++ b/hawkbit-dmf/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherService.java @@ -413,7 +413,7 @@ public class AmqpMessageDispatcherService extends BaseAmqpService { private void sendUpdateMessageToTargets( final Long dsId, final Map actionsPropsByTargetId, final List targets) { - distributionSetManagement.get(dsId).ifPresent(ds -> { + distributionSetManagement.find(dsId).ifPresent(ds -> { final Map> softwareModules = getSoftwareModulesWithMetadata(ds); sendUpdateMessageToTargets(actionsPropsByTargetId, targets, softwareModules); }); diff --git a/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherServiceTest.java b/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherServiceTest.java index e7bd50957..b4e0fe306 100644 --- a/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherServiceTest.java +++ b/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherServiceTest.java @@ -24,7 +24,6 @@ import java.util.Optional; import java.util.UUID; import org.eclipse.hawkbit.repository.RepositoryProperties; -import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.TargetManagement.Create; import org.eclipse.hawkbit.repository.artifact.ArtifactFilesystem; import org.eclipse.hawkbit.repository.artifact.model.AbstractDbArtifact; @@ -184,8 +183,8 @@ class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTest { receivedList.add(new ArtifactFilesystem(new File("./test"), artifact.getSha1Hash(), new DbArtifactHash(artifact.getSha1Hash(), null, null), artifact.getSize(), null)); } - module = softwareModuleManagement.get(module.getId()).get(); - dsA = distributionSetManagement.get(dsA.getId()).get(); + module = softwareModuleManagement.find(module.getId()).get(); + dsA = distributionSetManagement.find(dsA.getId()).get(); final Action action = createAction(dsA); diff --git a/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AbstractAmqpServiceIntegrationTest.java b/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AbstractAmqpServiceIntegrationTest.java index 0832b5dff..10f06a1e7 100644 --- a/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AbstractAmqpServiceIntegrationTest.java +++ b/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AbstractAmqpServiceIntegrationTest.java @@ -279,7 +279,7 @@ abstract class AbstractAmqpServiceIntegrationTest extends AbstractAmqpIntegratio protected void registerSameTargetAndAssertBasedOnVersion(final String controllerId, final String name, final int existingTargetsAfterCreation, final TargetUpdateStatus expectedTargetStatus, final Map attributes) { - final int version = controllerManagement.getByControllerId(controllerId).get().getOptLockRevision(); + final int version = controllerManagement.findByControllerId(controllerId).get().getOptLockRevision(); registerAndAssertTargetWithExistingTenant(controllerId, name, existingTargetsAfterCreation, expectedTargetStatus, CREATED_BY, attributes, () -> findTargetBasedOnNewVersion(controllerId, version)); } @@ -364,7 +364,7 @@ abstract class AbstractAmqpServiceIntegrationTest extends AbstractAmqpIntegratio } protected void assertUpdateAttributes(final String controllerId, final Map attributes) { - waitUntilIsPresent(() -> controllerManagement.getByControllerId(controllerId)); + waitUntilIsPresent(() -> controllerManagement.findByControllerId(controllerId)); await().untilAsserted(() -> { try { final Map controllerAttributes = SecurityContextSwitch.callAsPrivileged( @@ -443,7 +443,7 @@ abstract class AbstractAmqpServiceIntegrationTest extends AbstractAmqpIntegratio } private Optional findTargetBasedOnNewVersion(final String controllerId, final int version) { - final Optional target2 = controllerManagement.getByControllerId(controllerId); + final Optional target2 = controllerManagement.findByControllerId(controllerId); if (version < target2.get().getOptLockRevision()) { return target2; } diff --git a/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AmqpMessageDispatcherServiceIntegrationTest.java b/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AmqpMessageDispatcherServiceIntegrationTest.java index e3f25990b..af7873206 100644 --- a/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AmqpMessageDispatcherServiceIntegrationTest.java +++ b/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AmqpMessageDispatcherServiceIntegrationTest.java @@ -601,7 +601,7 @@ class AmqpMessageDispatcherServiceIntegrationTest extends AbstractAmqpServiceInt .containsEntry("type", EVENT.toString()) .containsEntry("topic", DOWNLOAD.toString()); - final Optional target = controllerManagement.getByControllerId(controllerId); + final Optional target = controllerManagement.findByControllerId(controllerId); assertThat(target).isPresent(); // verify the DS was assigned to the Target @@ -631,7 +631,7 @@ class AmqpMessageDispatcherServiceIntegrationTest extends AbstractAmqpServiceInt assertSoftwareModules(softwareModules, request.getSoftwareModules()); final List tokens = controllerIds.stream().map(controllerId -> { - final Optional target = controllerManagement.getByControllerId(controllerId); + final Optional target = controllerManagement.findByControllerId(controllerId); assertThat(target).isPresent(); return target.get().getSecurityToken(); }).toList(); diff --git a/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AmqpMessageHandlerServiceIntegrationTest.java b/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AmqpMessageHandlerServiceIntegrationTest.java index c2dc83c5e..2a727f2ec 100644 --- a/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AmqpMessageHandlerServiceIntegrationTest.java +++ b/hawkbit-dmf/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/integration/AmqpMessageHandlerServiceIntegrationTest.java @@ -1192,7 +1192,7 @@ class AmqpMessageHandlerServiceIntegrationTest extends AbstractAmqpServiceIntegr } private void verifyAssignedDsAndInstalledDs(final Long assignedDsId, final Long installedDsId) { - final Optional target = controllerManagement.getByControllerId(DMF_REGISTER_TEST_CONTROLLER_ID); + final Optional target = controllerManagement.findByControllerId(DMF_REGISTER_TEST_CONTROLLER_ID); assertThat(target).isPresent(); // verify the DS was assigned to the Target diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResource.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResource.java index 79c364c51..40fefefbf 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResource.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResource.java @@ -132,7 +132,7 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi { @Override public ResponseEntity getDistributionSet(final Long distributionSetId) { - final DistributionSet foundDs = distributionSetManagement.getOrElseThrowException(distributionSetId); + final DistributionSet foundDs = distributionSetManagement.get(distributionSetId); final MgmtDistributionSet response = MgmtDistributionSetMapper.toResponse(foundDs); MgmtDistributionSetMapper.addLinks(foundDs, response); @@ -211,7 +211,7 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi { final Long distributionSetId, final String rsqlParam, final int pagingOffsetParam, final int pagingLimitParam, final String sortParam) { // check if distribution set exists otherwise throw exception immediately - distributionSetManagement.getOrElseThrowException(distributionSetId); + distributionSetManagement.get(distributionSetId); final Pageable pageable = PagingUtility.toPageable(pagingOffsetParam, pagingLimitParam, sanitizeDistributionSetSortParam(sortParam)); final Page targetsInstalledDS; if (rsqlParam != null) { diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResource.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResource.java index 04c800aaf..5bb495b8f 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResource.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResource.java @@ -160,7 +160,7 @@ class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRestApi { } private DistributionSetTag findDistributionTagById(final Long distributionsetTagId) { - return distributionSetTagManagement.get(distributionsetTagId) + return distributionSetTagManagement.find(distributionsetTagId) .orElseThrow(() -> new EntityNotFoundException(DistributionSetTag.class, distributionsetTagId)); } } \ No newline at end of file diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResource.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResource.java index d263a243e..75922721c 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResource.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResource.java @@ -180,12 +180,12 @@ public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeR } private DistributionSetType findDistributionSetTypeWithExceptionIfNotFound(final Long distributionSetTypeId) { - return distributionSetTypeManagement.get(distributionSetTypeId) + return distributionSetTypeManagement.find(distributionSetTypeId) .orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, distributionSetTypeId)); } private SoftwareModuleType findSoftwareModuleTypeWithExceptionIfNotFound(final Long softwareModuleTypeId) { - return softwareModuleTypeManagement.get(softwareModuleTypeId) + return softwareModuleTypeManagement.find(softwareModuleTypeId) .orElseThrow(() -> new EntityNotFoundException(SoftwareModuleType.class, softwareModuleTypeId)); } } \ No newline at end of file diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadArtifactResource.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadArtifactResource.java index f89573f7e..177d76699 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadArtifactResource.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadArtifactResource.java @@ -13,12 +13,11 @@ import java.io.InputStream; import jakarta.servlet.http.HttpServletRequest; +import org.eclipse.hawkbit.repository.artifact.exception.ArtifactBinaryNoLongerExistsException; import org.eclipse.hawkbit.repository.artifact.model.DbArtifact; import org.eclipse.hawkbit.mgmt.rest.api.MgmtDownloadArtifactRestApi; import org.eclipse.hawkbit.repository.ArtifactManagement; import org.eclipse.hawkbit.repository.SoftwareModuleManagement; -import org.eclipse.hawkbit.repository.exception.ArtifactBinaryNoLongerExistsException; -import org.eclipse.hawkbit.repository.exception.ArtifactBinaryNotFoundException; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.SoftwareModule; @@ -53,7 +52,7 @@ public class MgmtDownloadArtifactResource implements MgmtDownloadArtifactRestApi */ @Override public ResponseEntity downloadArtifact(final Long softwareModuleId, final Long artifactId) { - final SoftwareModule module = softwareModuleManagement.get(softwareModuleId) + final SoftwareModule module = softwareModuleManagement.find(softwareModuleId) .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId)); if (module.isDeleted()) { throw new ArtifactBinaryNoLongerExistsException(); @@ -61,9 +60,7 @@ public class MgmtDownloadArtifactResource implements MgmtDownloadArtifactRestApi final Artifact artifact = module.getArtifact(artifactId) .orElseThrow(() -> new EntityNotFoundException(Artifact.class, artifactId)); - final DbArtifact file = artifactManagement - .loadArtifactBinary(artifact.getSha1Hash(), module.getId(), module.isEncrypted()) - .orElseThrow(() -> new ArtifactBinaryNotFoundException(artifact.getSha1Hash())); + final DbArtifact file = artifactManagement.loadArtifactBinary(artifact.getSha1Hash(), module.getId(), module.isEncrypted()); final HttpServletRequest request = RequestResponseContextHolder.getHttpServletRequest(); final String ifMatch = request.getHeader(HttpHeaders.IF_MATCH); if (ifMatch != null && !HttpUtil.matchesHttpHeader(ifMatch, artifact.getSha1Hash())) { diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResource.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResource.java index fe7329efe..073edd3f9 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResource.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResource.java @@ -273,7 +273,7 @@ public class MgmtRolloutResource implements MgmtRolloutRestApi { @Override public ResponseEntity retryRollout(final Long rolloutId) { - final Rollout rolloutForRetry = rolloutManagement.get(rolloutId) + final Rollout rolloutForRetry = rolloutManagement.find(rolloutId) .orElseThrow(() -> new EntityNotFoundException(Rollout.class, rolloutId)); if (rolloutForRetry.isDeleted()) { throw new EntityNotFoundException(Rollout.class, rolloutId); diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResource.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResource.java index 340b0ffa1..14446f206 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResource.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResource.java @@ -278,7 +278,7 @@ public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi { } private SoftwareModule findSoftwareModuleWithExceptionIfNotFound(final Long softwareModuleId, final Long artifactId) { - final SoftwareModule module = softwareModuleManagement.get(softwareModuleId) + final SoftwareModule module = softwareModuleManagement.find(softwareModuleId) .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId)); if (artifactId != null && module.getArtifact(artifactId).isEmpty()) { diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResource.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResource.java index dc4f28a94..7f2d953a4 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResource.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResource.java @@ -96,7 +96,7 @@ public class MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRes } private SoftwareModuleType findSoftwareModuleTypeWithExceptionIfNotFound(final Long softwareModuleTypeId) { - return softwareModuleTypeManagement.get(softwareModuleTypeId) + return softwareModuleTypeManagement.find(softwareModuleTypeId) .orElseThrow(() -> new EntityNotFoundException(SoftwareModuleType.class, softwareModuleTypeId)); } } \ No newline at end of file diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryResource.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryResource.java index ccca241cf..209b06ca9 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryResource.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryResource.java @@ -172,7 +172,7 @@ public class MgmtTargetFilterQueryResource implements MgmtTargetFilterQueryRestA } private TargetFilterQuery findFilterWithExceptionIfNotFound(final Long filterId) { - return filterManagement.get(filterId) + return filterManagement.find(filterId) .orElseThrow(() -> new EntityNotFoundException(TargetFilterQuery.class, filterId)); } } \ No newline at end of file diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResource.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResource.java index 09d061103..198e2e91a 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResource.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResource.java @@ -154,7 +154,7 @@ public class MgmtTargetResource implements MgmtTargetRestApi { targetManagement.unassignType(targetId); return null; } else { - return targetTypeManagement.get(targetRest.getTargetType()) + return targetTypeManagement.find(targetRest.getTargetType()) .orElseThrow(() -> new EntityNotFoundException(TargetType.class, targetRest.getTargetType())); } }) diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResource.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResource.java index 985e2783a..7c54f3cd6 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResource.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResource.java @@ -193,6 +193,6 @@ public class MgmtTargetTagResource implements MgmtTargetTagRestApi { } private TargetTag findTargetTagById(final Long targetTagId) { - return tagManagement.get(targetTagId).orElseThrow(() -> new EntityNotFoundException(TargetTag.class, targetTagId)); + return tagManagement.find(targetTagId).orElseThrow(() -> new EntityNotFoundException(TargetTag.class, targetTagId)); } } \ No newline at end of file diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTypeResource.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTypeResource.java index b1b010834..edb2c70e6 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTypeResource.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTypeResource.java @@ -122,7 +122,7 @@ public class MgmtTargetTypeResource implements MgmtTargetTypeRestApi { } private TargetType findTargetTypeWithExceptionIfNotFound(final Long targetTypeId) { - return targetTypeManagement.get(targetTypeId) + return targetTypeManagement.find(targetTypeId) .orElseThrow(() -> new EntityNotFoundException(TargetType.class, targetTypeId)); } } \ No newline at end of file diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/mapper/MgmtTargetMapper.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/mapper/MgmtTargetMapper.java index 52abef2aa..889417825 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/mapper/MgmtTargetMapper.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/mapper/MgmtTargetMapper.java @@ -345,7 +345,7 @@ public final class MgmtTargetMapper { .description(targetRest.getDescription()).securityToken(targetRest.getSecurityToken()) .address(targetRest.getAddress()) .targetType(Optional.ofNullable(targetRest.getTargetType()) - .map(targetTypeId -> targetTypeManagement.get(targetTypeId) + .map(targetTypeId -> targetTypeManagement.find(targetTypeId) .orElseThrow(() -> new EntityNotFoundException(TargetType.class, targetTypeId))) .map(TargetType.class::cast) .orElse(null)) diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResourceTest.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResourceTest.java index acb90b245..05a3162f3 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResourceTest.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResourceTest.java @@ -50,7 +50,6 @@ import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.exception.AssignmentQuotaExceededException; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.jpa.repository.ActionRepository; -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.DistributionSet; @@ -1067,7 +1066,7 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe .andExpect(jsonPath("$.locked", equalTo(false))) .andExpect(jsonPath("$.deleted", equalTo(false))); - final DistributionSet setupdated = distributionSetManagement.get(set.getId()).get(); + final DistributionSet setupdated = distributionSetManagement.find(set.getId()).get(); assertThat(setupdated.isRequiredMigrationStep()).isTrue(); assertThat(setupdated.getVersion()).isEqualTo("anotherVersion"); @@ -1079,8 +1078,7 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe * Ensures that DS property update on requiredMigrationStep fails if DS is assigned to a target. */ @Test - void updateRequiredMigrationStepFailsIfDistributionSetisInUse() throws Exception { - + void updateRequiredMigrationStepFailsIfDistributionSetIsInUse() throws Exception { // prepare test data assertThat(distributionSetManagement.findAll(PAGE)).isEmpty(); @@ -1095,7 +1093,7 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe .andDo(MockMvcResultPrinter.print()) .andExpect(status().isForbidden()); - final DistributionSet setupdated = distributionSetManagement.get(set.getId()).get(); + final DistributionSet setupdated = distributionSetManagement.find(set.getId()).get(); assertThat(setupdated.isRequiredMigrationStep()).isFalse(); assertThat(setupdated.getVersion()).isEqualTo(set.getVersion()); @@ -1702,16 +1700,16 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe .content(jsonObject.toString()).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); - assertThat(targetFilterQueryManagement.get(targetFilterQuery.getId()).get().getAutoAssignDistributionSet()) + assertThat(targetFilterQueryManagement.find(targetFilterQuery.getId()).get().getAutoAssignDistributionSet()) .isNull(); - assertThat(rolloutManagement.get(rollout.getId()).get().getStatus()).isIn(RolloutStatus.STOPPING, + assertThat(rolloutManagement.find(rollout.getId()).get().getStatus()).isIn(RolloutStatus.STOPPING, RolloutStatus.STOPPED); //then enforce executor to stop the rollout and check rolloutHandler.handleAll(); - assertThat(rolloutManagement.get(rollout.getId()).get().getStatus()).isIn(RolloutStatus.STOPPED); + assertThat(rolloutManagement.find(rollout.getId()).get().getStatus()).isIn(RolloutStatus.STOPPED); for (final Target target : targets) { - assertThat(targetManagement.get(target.getId()).get().getUpdateStatus()) + assertThat(targetManagement.find(target.getId()).get().getUpdateStatus()) .isEqualTo(TargetUpdateStatus.PENDING); assertThat(deploymentManagement.findActionsByTarget(target.getControllerId(), PageRequest.of(0, 100)) .getNumberOfElements()).isEqualTo(1); @@ -1737,17 +1735,17 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe .content(jsonObject.toString()).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); - assertThat(targetFilterQueryManagement.get(targetFilterQuery.getId()).get().getAutoAssignDistributionSet()) + assertThat(targetFilterQueryManagement.find(targetFilterQuery.getId()).get().getAutoAssignDistributionSet()) .isNull(); - assertThat(rolloutManagement.get(rollout.getId()).get().getStatus()).isIn(RolloutStatus.DELETING, + assertThat(rolloutManagement.find(rollout.getId()).get().getStatus()).isIn(RolloutStatus.DELETING, RolloutStatus.DELETED); //then enforce executor to stop the rollout and check rolloutHandler.handleAll(); // assert rollout is deleted - assertThat(rolloutManagement.get(rollout.getId())).isEmpty(); + assertThat(rolloutManagement.find(rollout.getId())).isEmpty(); for (final Target target : targets) { - assertThat(targetManagement.get(target.getId()).get().getUpdateStatus()) + assertThat(targetManagement.find(target.getId()).get().getUpdateStatus()) .isEqualTo(TargetUpdateStatus.IN_SYNC); assertThat(deploymentManagement.findActionsByTarget(target.getControllerId(), PageRequest.of(0, 100)) .getNumberOfElements()).isEqualTo(1); @@ -1771,10 +1769,10 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe .content(jsonObject.toString()).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); - assertThat(rolloutManagement.get(rollout.getId()).get().getStatus()).isIn(RolloutStatus.RUNNING); + assertThat(rolloutManagement.find(rollout.getId()).get().getStatus()).isIn(RolloutStatus.RUNNING); for (final Target target : targets) { - assertThat(targetManagement.get(target.getId()).get().getUpdateStatus()) + assertThat(targetManagement.find(target.getId()).get().getUpdateStatus()) .isEqualTo(TargetUpdateStatus.PENDING); assertThat(deploymentManagement.findActionsByTarget(target.getControllerId(), PageRequest.of(0, 100)) .getNumberOfElements()).isEqualTo(1); @@ -1803,7 +1801,7 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe .andExpect(status().isOk()) .andExpect(jsonPath("$.locked", equalTo(true))); - final DistributionSet updatedSet = distributionSetManagement.get(set.getId()).get(); + final DistributionSet updatedSet = distributionSetManagement.find(set.getId()).get(); assertThat(updatedSet.isLocked()).isTrue(); } @@ -1818,7 +1816,7 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe final DistributionSet set = testdataFactory.createDistributionSet("one"); assertThat(distributionSetManagement.count()).isEqualTo(1); distributionSetManagement.lock(set); - assertThat(distributionSetManagement.get(set.getId()) + assertThat(distributionSetManagement.find(set.getId()) .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, set.getId())).isLocked()) .as("Distribution set should be locked") .isTrue(); @@ -1831,7 +1829,7 @@ class MgmtDistributionSetResourceTest extends AbstractManagementApiIntegrationTe .andExpect(status().isOk()) .andExpect(jsonPath("$.locked", equalTo(false))); - final DistributionSet updatedSet = distributionSetManagement.get(set.getId()).get(); + final DistributionSet updatedSet = distributionSetManagement.find(set.getId()).get(); assertThat(updatedSet.isLocked()).isFalse(); } diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResourceTest.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResourceTest.java index 1a53acded..0bd9fe5d8 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResourceTest.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResourceTest.java @@ -261,7 +261,7 @@ class MgmtDistributionSetTagResourceTest extends AbstractManagementApiIntegratio .andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()); - assertThat(distributionSetTagManagement.get(original.getId())).isNotPresent(); + assertThat(distributionSetTagManagement.find(original.getId())).isNotPresent(); } /** diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java index 60627f5b2..9886be140 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java @@ -181,7 +181,7 @@ class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIntegrati .andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()); - testType = distributionSetTypeManagement.get(testType.getId()).get(); + testType = distributionSetTypeManagement.find(testType.getId()).get(); assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester"); assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType); assertThat(testType.getOptionalModuleTypes()).isEmpty(); @@ -207,7 +207,7 @@ class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIntegrati .andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()); - testType = distributionSetTypeManagement.get(testType.getId()).get(); + testType = distributionSetTypeManagement.find(testType.getId()).get(); assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester"); assertThat(testType.getOptionalModuleTypes()).containsExactly(osType); assertThat(testType.getMandatoryModuleTypes()).isEmpty(); @@ -366,7 +366,7 @@ class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIntegrati .andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()); - testType = distributionSetTypeManagement.get(testType.getId()).get(); + testType = distributionSetTypeManagement.find(testType.getId()).get(); assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester"); assertThat(testType.getOptionalModuleTypes()).containsExactly(appType); assertThat(testType.getMandatoryModuleTypes()).isEmpty(); @@ -385,7 +385,7 @@ class MgmtDistributionSetTypeResourceTest extends AbstractManagementApiIntegrati .andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()); - testType = distributionSetTypeManagement.get(testType.getId()).get(); + testType = distributionSetTypeManagement.find(testType.getId()).get(); assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester"); assertThat(testType.getOptionalModuleTypes()).isEmpty(); assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType); diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java index 782c07671..e487b05c4 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java @@ -1946,7 +1946,7 @@ class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTest { private void awaitRunningState(final Long rolloutId) { awaitRollout().until(() -> SecurityContextSwitch - .callAsPrivileged(() -> rolloutManagement.get(rolloutId).orElseThrow(NoSuchElementException::new)) + .callAsPrivileged(() -> rolloutManagement.find(rolloutId).orElseThrow(NoSuchElementException::new)) .getStatus().equals(RolloutStatus.RUNNING)); } @@ -1966,7 +1966,7 @@ class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTest { } private void assertStatusIs(final Rollout rollout, final RolloutStatus expected) { - final Optional updatedRollout = rolloutManagement.get(rollout.getId()); + final Optional updatedRollout = rolloutManagement.find(rollout.getId()); assertThat(updatedRollout).get().extracting(Rollout::getStatus).isEqualTo(expected); } @@ -2039,7 +2039,7 @@ class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTest { // Run here, because Scheduler is disabled during tests rolloutHandler.handleAll(); - return rolloutManagement.get(rollout.getId()).orElseThrow(NoSuchElementException::new); + return rolloutManagement.find(rollout.getId()).orElseThrow(NoSuchElementException::new); } private void triggerNextGroupAndExpect(final Rollout rollout, final ResultMatcher expect) throws Exception { diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java index 6b2c02ca0..272009329 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java @@ -47,6 +47,9 @@ import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.mgmt.rest.resource.util.ResourceUtility; import org.eclipse.hawkbit.repository.Constants; import org.eclipse.hawkbit.repository.SoftwareModuleManagement; +import org.eclipse.hawkbit.repository.artifact.exception.ArtifactBinaryNotFoundException; +import org.eclipse.hawkbit.repository.artifact.model.DbArtifact; +import org.eclipse.hawkbit.repository.artifact.model.DbArtifactHash; import org.eclipse.hawkbit.repository.exception.AssignmentQuotaExceededException; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.exception.FileSizeQuotaExceededException; @@ -258,7 +261,7 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes .andExpect(jsonPath("$.locked", equalTo(false))) .andReturn(); - final SoftwareModule updatedSm = softwareModuleManagement.get(sm.getId()).get(); + final SoftwareModule updatedSm = softwareModuleManagement.find(sm.getId()).get(); assertThat(updatedSm.getName()).isEqualTo(knownSWName); assertThat(updatedSm.getVendor()).isEqualTo(updateVendor); assertThat(updatedSm.getLastModifiedBy()).isEqualTo("smUpdateTester"); @@ -294,7 +297,7 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes .andExpect(jsonPath("$.lastModifiedAt", equalTo(sm.getLastModifiedAt()))) .andExpect(jsonPath("$.deleted", equalTo(false))); - softwareModuleManagement.get(sm.getId()); + softwareModuleManagement.find(sm.getId()); assertThat(sm.getLastModifiedBy()).isEqualTo("smUpdateTester"); assertThat(sm.getLastModifiedAt()).isEqualTo(sm.getLastModifiedAt()); assertThat(sm.isDeleted()).isFalse(); @@ -319,7 +322,7 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes mvc.perform(put("/rest/v1/softwaremodules/{smId}", sm.getId()).content(body) .contentType(MediaType.APPLICATION_JSON)); - final SoftwareModule updatedSm = softwareModuleManagement.get(sm.getId()).get(); + final SoftwareModule updatedSm = softwareModuleManagement.find(sm.getId()).get(); assertThat(updatedSm.getLastModifiedBy()).isEqualTo("smUpdateTester"); assertThat(updatedSm.isLocked()).isTrue(); @@ -341,7 +344,7 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes final SoftwareModule sm = softwareModuleManagement.create( SoftwareModuleManagement.Create.builder().type(osType).name("name1").version("version1").build()); softwareModuleManagement.lock(sm); - assertThat(softwareModuleManagement.get(sm.getId()) + assertThat(softwareModuleManagement.find(sm.getId()) .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, sm.getId())).isLocked()) .as("Software module is locked") .isTrue(); @@ -354,7 +357,7 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes mvc.perform(put("/rest/v1/softwaremodules/{smId}", sm.getId()).content(body) .contentType(MediaType.APPLICATION_JSON)); - final SoftwareModule updatedSm = softwareModuleManagement.get(sm.getId()).get(); + final SoftwareModule updatedSm = softwareModuleManagement.find(sm.getId()).get(); assertThat(updatedSm.getLastModifiedBy()).isEqualTo("smUpdateTester"); assertThat(updatedSm.isLocked()).isFalse(); // not unlocked @@ -397,7 +400,7 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes // check rest of response compared to DB final MgmtArtifact artResult = ResourceUtility.convertArtifactResponse( mvcResult.getResponse().getContentAsString()); - final Long artId = softwareModuleManagement.get(sm.getId()).get().getArtifacts().get(0).getId(); + final Long artId = softwareModuleManagement.find(sm.getId()).get().getArtifacts().get(0).getId(); assertThat(artResult.getId()).as("Wrong artifact id").isEqualTo(artId); assertThat((Object) JsonPath.compile("$._links.self.href").read(mvcResult.getResponse().getContentAsString())) .as("Link contains no self url") @@ -455,14 +458,10 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes @Test void emptyUploadArtifact() throws Exception { assertThat(softwareModuleManagement.findAll(PAGE)).isEmpty(); - assertThat(artifactManagement.count()).isZero(); final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); - final MockMultipartFile file = new MockMultipartFile("file", "orig", null, new byte[0]); - - mvc.perform(multipart("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file) - .accept(MediaType.APPLICATION_JSON)) + mvc.perform(multipart("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file).accept(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()) .andExpect(status().isBadRequest()); } @@ -502,7 +501,6 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes @Test void uploadArtifactWithCustomName() throws Exception { final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); - assertThat(artifactManagement.count()).isZero(); // create test file final byte[] random = randomBytes(5 * 1024); @@ -515,14 +513,11 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes .andExpect(status().isCreated()) .andExpect(content().contentType(MediaTypes.HAL_JSON)) .andExpect(jsonPath("$.providedFilename", equalTo("customFilename"))) - .andExpect(status().isCreated()); - - // check result in db... - // repo - assertThat(artifactManagement.count()).isEqualTo(1); - - // hashes - assertThat(artifactManagement.getByFilename("customFilename")).as("Local artifact is wrong").isPresent(); + .andExpect(status().isCreated()) + .andDo(result -> { + final MgmtArtifact mgmtArtifact = OBJECT_MAPPER.readerFor(MgmtArtifact.class).readValue(result.getResponse().getContentAsString()); + assertThat(artifactManagement.loadArtifactBinary(mgmtArtifact.getHashes().getSha1(), sm.getId(), sm.isEncrypted())).isNotNull(); + }); } /** @@ -531,7 +526,6 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes @Test void uploadArtifactWithHashCheck() throws Exception { final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); - assertThat(artifactManagement.count()).isZero(); // create test file final byte[] random = randomBytes(5 * 1024); @@ -586,7 +580,6 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes .andExpect(status().isCreated()); assertArtifact(sm, random); - } /** @@ -700,9 +693,6 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes downloadAndVerify(sm, random, artifact); downloadAndVerify(sm, random, artifact2); - - assertThat(softwareModuleManagement.findAll(PAGE)).as("Softwaremodule size is wrong").hasSize(1); - assertThat(artifactManagement.count()).isEqualTo(2); } /** @@ -783,7 +773,7 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes SoftwareModule sm = testdataFactory.createSoftwareModuleOs("softDeleted"); final Artifact artifact = testdataFactory.createArtifacts(sm.getId()).get(0); // the sm is changed by artifact creation, necessary to get the latest version for Hibernate - sm = softwareModuleManagement.get(sm.getId()).orElseThrow(); + sm = softwareModuleManagement.find(sm.getId()).orElseThrow(); testdataFactory.createDistributionSet(List.of(sm)); softwareModuleManagement.delete(sm.getId()); @@ -904,7 +894,7 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes SoftwareModule smSoftDeleted = testdataFactory.createSoftwareModuleOs("softDeleted"); final Artifact artifactSoftDeleted = testdataFactory.createArtifacts(smSoftDeleted.getId()).get(0); // the smSoftDeleted is changed by artifact creation, necessary to get the latest version for Hibernate - smSoftDeleted = softwareModuleManagement.get(smSoftDeleted.getId()).orElseThrow(); + smSoftDeleted = softwareModuleManagement.find(smSoftDeleted.getId()).orElseThrow(); testdataFactory.createDistributionSet(List.of(smSoftDeleted)); softwareModuleManagement.delete(smSoftDeleted.getId()); @@ -959,31 +949,34 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); final int artifactSize = 5 * 1024; - final byte[] random = randomBytes(artifactSize); // Create 2 artifacts + final long moduleId = sm.getId(); + final byte[] random = randomBytes(artifactSize); final Artifact artifact = artifactManagement.create( - new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file1", false, artifactSize)); + new ArtifactUpload(new ByteArrayInputStream(random), moduleId, "file1", false, artifactSize)); + final byte[] random2 = randomBytes(artifactSize); artifactManagement.create( - new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file2", false, artifactSize)); + new ArtifactUpload(new ByteArrayInputStream(random2), moduleId, "file2", false, artifactSize)); // check repo before delete assertThat(softwareModuleManagement.findAll(PAGE)).hasSize(1); - assertThat(softwareModuleManagement.get(sm.getId()).get().getArtifacts()).hasSize(2); - assertThat(artifactManagement.count()).isEqualTo(2); + assertThat(softwareModuleManagement.find(moduleId).get().getArtifacts()).hasSize(2); // delete - mvc.perform(delete("/rest/v1/softwaremodules/{smId}/artifacts/{artId}", sm.getId(), artifact.getId())) + mvc.perform(delete("/rest/v1/softwaremodules/{smId}/artifacts/{artId}", moduleId, artifact.getId())) .andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()); // check that only one artifact is still alive and still assigned assertThat(softwareModuleManagement.findAll(PAGE)).as("After the sm should be marked as deleted").hasSize(1); - assertThat(artifactManagement.count()).isEqualTo(1); - assertThat(softwareModuleManagement.get(sm.getId()).get().getArtifacts()) + final boolean encrypted = sm.isEncrypted(); + final String sha1Hash = artifact.getSha1Hash(); + assertThatExceptionOfType(ArtifactBinaryNotFoundException.class) + .isThrownBy(() -> artifactManagement.loadArtifactBinary(sha1Hash, moduleId, encrypted)); + assertThat(softwareModuleManagement.find(moduleId).get().getArtifacts()) .as("After delete artifact should available for marked as deleted sm's").hasSize(1); - } /** @@ -1332,8 +1325,8 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes .isEqualTo("http://localhost/rest/v1/softwaremodules/" + appCreatedId); assertThat(softwareModuleManagement.findAll(PAGE)).as("Wrong softwaremodule size").hasSize(2); - final SoftwareModule osCreated = softwareModuleManagement.get(osCreatedId).orElseThrow(); - final SoftwareModule appCreated = softwareModuleManagement.get(appCreatedId).orElseThrow(); + final SoftwareModule osCreated = softwareModuleManagement.find(osCreatedId).orElseThrow(); + final SoftwareModule appCreated = softwareModuleManagement.find(appCreatedId).orElseThrow(); assertThat(osCreated.getName()).as("Softwaremoudle name is wrong").isEqualTo(os.getName()); assertThat(osCreated.getCreatedBy()).as("Softwaremoudle created by is wrong").isEqualTo("uploadTester"); assertThat(osCreated.getCreatedAt()).as("Softwaremoudle created at is wrong").isGreaterThanOrEqualTo(current); @@ -1345,29 +1338,32 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes */ @Test void deleteUnassignedSoftwareModule() throws Exception { - final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); final int artifactSize = 5 * 1024; final byte[] random = randomBytes(artifactSize); - artifactManagement.create( + final Artifact artifact = artifactManagement.create( new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file1", false, artifactSize)); assertThat(softwareModuleManagement.findAll(PAGE)).as("Softwaremoudle size is wrong").hasSize(1); - assertThat(artifactManagement.count()).isEqualTo(1); + + final Long smId = sm.getId(); + final String sha1Hash = artifact.getSha1Hash(); + final boolean encrypted = sm.isEncrypted(); + assertThat(artifactManagement.loadArtifactBinary(sha1Hash, smId, encrypted)).isNotNull(); mvc.perform(delete("/rest/v1/softwaremodules/{smId}", sm.getId())) .andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()); - assertThat(softwareModuleManagement.findAll(PAGE)).as("After delete no softwarmodule should be available") - .isEmpty(); - assertThat(artifactManagement.count()).isZero(); + assertThat(softwareModuleManagement.findAll(PAGE)).as("After delete no softwarmodule should be available").isEmpty(); + assertThatExceptionOfType(EntityNotFoundException.class) // sm doesn't exists + .isThrownBy(() -> artifactManagement.loadArtifactBinary(sha1Hash, smId, encrypted)); } /** - * Verifies successfull deletion of a software module that is in use, i.e. assigned to a DS which should result in movinf the module to the archive. + * Verifies successful deletion of a software module that is in use, i.e. assigned to a DS which should result in movinf the module to the archive. */ @Test void deleteAssignedSoftwareModule() throws Exception { @@ -1376,13 +1372,16 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes final int artifactSize = 5 * 1024; final byte[] random = randomBytes(artifactSize); - final Long appTypeSmId = findFirstModuleByType(ds1, appType).get().getId(); + final SoftwareModule appTypeSm = findFirstModuleByType(ds1, appType).get(); + final Long appTypeSmId = appTypeSm.getId(); - artifactManagement.create( + final Artifact artifact = artifactManagement.create( new ArtifactUpload(new ByteArrayInputStream(random), appTypeSmId, "file1", false, artifactSize)); assertThat(softwareModuleManagement.count()).isEqualTo(3); - assertThat(artifactManagement.count()).isEqualTo(1); + final String sha1Hash = artifact.getSha1Hash(); + final boolean encrypted = appTypeSm.isEncrypted(); + assertThat(artifactManagement.loadArtifactBinary(sha1Hash, appTypeSmId, encrypted)).isNotNull(); mvc.perform(get("/rest/v1/softwaremodules/{smId}", appTypeSmId)) .andDo(MockMvcResultPrinter.print()) @@ -1399,7 +1398,8 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes .andExpect(jsonPath("$.deleted", equalTo(true))); assertThat(softwareModuleManagement.count()).isEqualTo(2); - assertThat(artifactManagement.count()).isEqualTo(1); + assertThatExceptionOfType(ArtifactBinaryNotFoundException.class) + .isThrownBy(() -> artifactManagement.loadArtifactBinary(sha1Hash, appTypeSmId, encrypted)); } /** @@ -1526,31 +1526,25 @@ class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTes } private void assertArtifact(final SoftwareModule sm, final byte[] random) throws IOException { - // check result in db... - // repo - assertThat(artifactManagement.count()).as("Wrong artifact size").isEqualTo(1); - + final DbArtifact artifact = artifactManagement + .loadArtifactBinary( + softwareModuleManagement.find( + sm.getId()).orElseThrow().getArtifacts().get(0).getSha1Hash(), sm.getId(), sm.isEncrypted()); // binary - try (final InputStream fileInputStream = artifactManagement - .loadArtifactBinary(softwareModuleManagement.get(sm.getId()).orElseThrow().getArtifacts().get(0).getSha1Hash(), - sm.getId(), sm.isEncrypted()) - .get().getFileInputStream()) { + try (final InputStream fileInputStream = artifact.getFileInputStream()) { assertTrue(IOUtils.contentEquals(new ByteArrayInputStream(random), fileInputStream), "Wrong artifact content"); } // hashes - assertThat(artifactManagement.getByFilename("origFilename").orElseThrow().getSha1Hash()).as("Wrong sha1 hash") - .isEqualTo(HashGeneratorUtils.generateSHA1(random)); - - assertThat(artifactManagement.getByFilename("origFilename").orElseThrow().getMd5Hash()).as("Wrong md5 hash") - .isEqualTo(HashGeneratorUtils.generateMD5(random)); - - assertThat(artifactManagement.getByFilename("origFilename").orElseThrow().getSha256Hash()).as("Wrong sha256 hash") - .isEqualTo(HashGeneratorUtils.generateSHA256(random)); + final DbArtifactHash hash = artifact.getHashes(); + assertThat(hash.getSha1()).as("Wrong sha1 hash").isEqualTo(HashGeneratorUtils.generateSHA1(random)); + // sha1 hashes are not used via loaded artifact +// assertThat(hash.getMd5()).as("Wrong md5 hash").isEqualTo(HashGeneratorUtils.generateMD5(random)); +// assertThat(hash.getSha256()).as("Wrong sha256 hash").isEqualTo(HashGeneratorUtils.generateSHA256(random)); // metadata - assertThat(softwareModuleManagement.get(sm.getId()).orElseThrow().getArtifacts().get(0).getFilename()) + assertThat(softwareModuleManagement.find(sm.getId()).orElseThrow().getArtifacts().get(0).getFilename()) .as("wrong metadata of the filename").isEqualTo("origFilename"); } diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java index c29326607..40ec0a3b0 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java @@ -349,7 +349,7 @@ public class MgmtSoftwareModuleTypeResourceTest extends AbstractManagementApiInt .andExpect(jsonPath("$.lastModifiedAt", equalTo(testType.getLastModifiedAt()))) .andExpect(jsonPath("$.deleted", equalTo(false))); - testType = softwareModuleTypeManagement.get(testType.getId()).get(); + testType = softwareModuleTypeManagement.find(testType.getId()).get(); assertThat(testType.getLastModifiedAt()).isEqualTo(testType.getLastModifiedAt()); assertThat(testType.isDeleted()).isFalse(); } diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryResourceTest.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryResourceTest.java index 9190d2daa..10d32efde 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryResourceTest.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetFilterQueryResourceTest.java @@ -144,7 +144,7 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte mvc.perform(delete(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + filterQuery.getId())) .andExpect(status().isOk()); - assertThat(targetFilterQueryManagement.get(filterQuery.getId())).isNotPresent(); + assertThat(targetFilterQueryManagement.find(filterQuery.getId())).isNotPresent(); } /** @@ -192,7 +192,7 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte .andExpect(jsonPath(JSON_PATH_NAME, equalTo(filterName))) .andExpect(jsonPath(JSON_PATH_CONFIRMATION_REQUIRED).doesNotExist()); - final TargetFilterQuery tfqCheck = targetFilterQueryManagement.get(tfq.getId()).get(); + final TargetFilterQuery tfqCheck = targetFilterQueryManagement.find(tfq.getId()).get(); assertThat(tfqCheck.getQuery()).isEqualTo(filterQuery2); assertThat(tfqCheck.getName()).isEqualTo(filterName); } @@ -219,7 +219,7 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte .andExpect(jsonPath(JSON_PATH_NAME, equalTo(filterName2))) .andExpect(jsonPath(JSON_PATH_CONFIRMATION_REQUIRED).doesNotExist()); - final TargetFilterQuery tfqCheck = targetFilterQueryManagement.get(tfq.getId()).get(); + final TargetFilterQuery tfqCheck = targetFilterQueryManagement.find(tfq.getId()).get(); assertThat(tfqCheck.getQuery()).isEqualTo(filterQuery); assertThat(tfqCheck.getName()).isEqualTo(filterName2); } @@ -493,7 +493,7 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte .andExpect(status().isOk()); implicitLock(set); - final TargetFilterQuery updatedFilterQuery = targetFilterQueryManagement.get(filterQuery.getId()).get(); + final TargetFilterQuery updatedFilterQuery = targetFilterQueryManagement.find(filterQuery.getId()).get(); assertThat(updatedFilterQuery.getAutoAssignDistributionSet()).isEqualTo(set); assertThat(updatedFilterQuery.getAutoAssignActionType()).isEqualTo(ActionType.FORCED); @@ -603,7 +603,7 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte targetFilterQueryManagement.updateAutoAssignDS(new AutoAssignDistributionSetUpdate(tfq.getId()).ds(set.getId())); implicitLock(set); - final TargetFilterQuery updatedFilterQuery = targetFilterQueryManagement.get(tfq.getId()).orElseThrow(); + final TargetFilterQuery updatedFilterQuery = targetFilterQueryManagement.find(tfq.getId()).orElseThrow(); assertThat(updatedFilterQuery.getAutoAssignDistributionSet()).isEqualTo(set); assertThat(updatedFilterQuery.getAutoAssignActionType()).isEqualTo(ActionType.FORCED); @@ -615,7 +615,7 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte mvc.perform(delete(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + tfq.getId() + "/autoAssignDS")) .andExpect(status().isNoContent()); - final TargetFilterQuery filterQueryWithDeletedDs = targetFilterQueryManagement.get(tfq.getId()).get(); + final TargetFilterQuery filterQueryWithDeletedDs = targetFilterQueryManagement.find(tfq.getId()).get(); assertThat(filterQueryWithDeletedDs.getAutoAssignDistributionSet()).isNull(); assertThat(filterQueryWithDeletedDs.getAutoAssignActionType()).isNull(); @@ -676,7 +676,7 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte // do not provide something about the confirmation verifyAutoAssignmentByActionType(tfq, set, null, null); - assertThat(targetFilterQueryManagement.get(tfq.getId())).hasValueSatisfying(filter -> + assertThat(targetFilterQueryManagement.find(tfq.getId())).hasValueSatisfying(filter -> assertThat(filter.isConfirmationRequired()).isEqualTo(confirmationFlowActive)); } @@ -720,7 +720,7 @@ public class MgmtTargetFilterQueryResourceTest extends AbstractManagementApiInte .andExpect(status().isOk()); implicitLock(set); - final TargetFilterQuery updatedFilterQuery = targetFilterQueryManagement.get(tfq.getId()).get(); + final TargetFilterQuery updatedFilterQuery = targetFilterQueryManagement.find(tfq.getId()).get(); final MgmtActionType expectedActionType = actionType != null ? actionType : MgmtActionType.FORCED; assertThat(updatedFilterQuery.getAutoAssignDistributionSet()).isEqualTo(set); diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResourceTest.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResourceTest.java index 75c84fb71..eae80ef15 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResourceTest.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResourceTest.java @@ -2576,7 +2576,7 @@ class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest { final long unknownTargetTypeId = 999; final String errorMsg = String.format("TargetType with given identifier {%s} does not exist.", unknownTargetTypeId); - final Optional targetType = targetTypeManagement.get(unknownTargetTypeId); + final Optional targetType = targetTypeManagement.find(unknownTargetTypeId); assertThat(targetType).isNotPresent(); final String controllerId = "targetcontroller"; diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResourceTest.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResourceTest.java index 3e5313cec..01ccb03f0 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResourceTest.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResourceTest.java @@ -227,7 +227,7 @@ public class MgmtTargetTagResourceTest extends AbstractManagementApiIntegrationT .andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()); - assertThat(targetTagManagement.get(original.getId())).isNotPresent(); + assertThat(targetTagManagement.find(original.getId())).isNotPresent(); } /** diff --git a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTypeResourceTest.java b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTypeResourceTest.java index 9d21f7265..af47fcafc 100644 --- a/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTypeResourceTest.java +++ b/hawkbit-mgmt/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTypeResourceTest.java @@ -349,7 +349,7 @@ class MgmtTargetTypeResourceTest extends AbstractManagementApiIntegrationTest { .andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()); - testType = targetTypeManagement.get(testType.getId()).get(); + testType = targetTypeManagement.find(testType.getId()).get(); assertThat(testType.getLastModifiedBy()).isEqualTo(TEST_USER); assertThat(testType.getOptLockRevision()).isEqualTo(2); assertThat(testType.getDistributionSetTypes()).containsExactly(standardDsType); @@ -405,7 +405,7 @@ class MgmtTargetTypeResourceTest extends AbstractManagementApiIntegrationTest { .andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()); - testType = targetTypeManagement.get(testType.getId()).get(); + testType = targetTypeManagement.find(testType.getId()).get(); assertThat(testType.getLastModifiedBy()).isEqualTo(TEST_USER); assertThat(testType.getOptLockRevision()).isEqualTo(2); assertThat(testType.getDistributionSetTypes()).isEmpty(); @@ -425,7 +425,7 @@ class MgmtTargetTypeResourceTest extends AbstractManagementApiIntegrationTest { .andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()); - testType = targetTypeManagement.get(testType.getId()).get(); + testType = targetTypeManagement.find(testType.getId()).get(); assertThat(testType.getLastModifiedBy()).isEqualTo(TEST_USER); assertThat(testType.getOptLockRevision()).isEqualTo(2); assertThat(testType.getDistributionSetTypes()).isEmpty(); 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 d06bbb24c..6069b91d1 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,8 +9,6 @@ */ package org.eclipse.hawkbit.repository; -import java.util.Optional; - import jakarta.validation.ConstraintViolationException; import jakarta.validation.Valid; import jakarta.validation.constraints.NotEmpty; @@ -19,8 +17,6 @@ import jakarta.validation.constraints.NotNull; import org.eclipse.hawkbit.im.authentication.SpPermission; import org.eclipse.hawkbit.repository.artifact.model.DbArtifact; import org.eclipse.hawkbit.im.authentication.SpringEvalExpressions; -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.InvalidMD5HashException; @@ -28,8 +24,6 @@ import org.eclipse.hawkbit.repository.exception.InvalidSHA1HashException; import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.ArtifactUpload; import org.eclipse.hawkbit.repository.model.SoftwareModule; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; import org.springframework.security.access.prepost.PreAuthorize; /** @@ -42,12 +36,6 @@ public interface ArtifactManagement extends PermissionSupport { return SpPermission.SOFTWARE_MODULE; } - /** - * @return the total amount of local artifacts stored in the artifact management - */ - @PreAuthorize(SpringEvalExpressions.HAS_READ_REPOSITORY) - long count(); - /** * Persists artifact binary as provided by given InputStream. assign the * artifact in addition to given {@link SoftwareModule}. @@ -56,7 +44,7 @@ public interface ArtifactManagement extends PermissionSupport { * @return uploaded {@link Artifact} * @throws EntityNotFoundException if given software module does not exist * @throws EntityAlreadyExistsException if File with that name already exists in the Software Module - * @throws ArtifactUploadFailedException if upload fails with internal server errors + * @throws org.eclipse.hawkbit.repository.artifact.exception.ArtifactUploadFailedException if upload fails with internal server errors * @throws InvalidMD5HashException if check against provided MD5 checksum failed * @throws InvalidSHA1HashException if check against provided SHA1 checksum failed * @throws ConstraintViolationException if {@link ArtifactUpload} contains invalid values @@ -64,75 +52,6 @@ public interface ArtifactManagement extends PermissionSupport { @PreAuthorize(SpringEvalExpressions.HAS_CREATE_REPOSITORY) Artifact create(@NotNull @Valid ArtifactUpload artifactUpload); - /** - * Deletes {@link Artifact} based on given id. - * - * @param id 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_DELETE_REPOSITORY) - void delete(long id); - - /** - * Searches for {@link Artifact} with given {@link Identifiable}. - * - * @param id to search for - * @return found {@link Artifact} - */ - @PreAuthorize(SpringEvalExpressions.HAS_READ_REPOSITORY + " or " + SpringEvalExpressions.IS_CONTROLLER) - Optional get(long id); - - /** - * Find by artifact by software module id and filename. - * - * @param filename file name - * @param softwareModuleId software module id. - * @return found {@link Artifact} - * @throws EntityNotFoundException if software module with given ID does not exist - */ - @PreAuthorize(SpringEvalExpressions.HAS_READ_REPOSITORY + " or " + SpringEvalExpressions.IS_CONTROLLER) - Optional getByFilenameAndSoftwareModule(@NotNull String filename, long softwareModuleId); - - /** - * Find all local artifact by sha1 and return the first artifact. - * - * @param sha1 the sha1 - * @return the first local artifact - */ - @PreAuthorize(SpringEvalExpressions.HAS_READ_REPOSITORY + " or " + SpringEvalExpressions.IS_CONTROLLER) - Optional findFirstBySHA1(@NotNull String sha1); - - /** - * Searches for {@link Artifact} with given file name. - * - * @param filename to search for - * @return found List of {@link Artifact}s. - */ - @PreAuthorize(SpringEvalExpressions.HAS_READ_REPOSITORY + " or " + SpringEvalExpressions.IS_CONTROLLER) - Optional getByFilename(@NotNull String filename); - - /** - * Get local artifact for a base software module. - * - * @param softwareModuleId software module id - * @param pageable Pageable parameter - * @return Page - * @throws EntityNotFoundException if software module with given ID does not exist - */ - @PreAuthorize(SpringEvalExpressions.HAS_READ_REPOSITORY) - Page findBySoftwareModule(long softwareModuleId, @NotNull Pageable pageable); - - /** - * Count local artifacts for a base software module. - * - * @param softwareModuleId software module id - * @return count by software module - * @throws EntityNotFoundException if software module with given ID does not exist - */ - @PreAuthorize(SpringEvalExpressions.HAS_READ_REPOSITORY) - long countBySoftwareModule(long softwareModuleId); - /** * Loads {@link DbArtifact} from store for given {@link Artifact}. * @@ -142,6 +61,14 @@ public interface ArtifactManagement extends PermissionSupport { * @return loaded {@link DbArtifact} */ @PreAuthorize("hasAuthority('" + SpPermission.DOWNLOAD_REPOSITORY_ARTIFACT + "')" + " or " + SpringEvalExpressions.IS_CONTROLLER) - Optional loadArtifactBinary(@NotEmpty String sha1Hash, long softwareModuleId, - final boolean isEncrypted); + DbArtifact loadArtifactBinary(@NotEmpty String sha1Hash, long softwareModuleId, final boolean isEncrypted); + + /** + * Deletes {@link Artifact} based on given id. + * + * @param id of the {@link Artifact} that has to be deleted. + * @throws EntityNotFoundException if artifact with given ID does not exist + */ + @PreAuthorize(SpringEvalExpressions.HAS_DELETE_REPOSITORY) + void delete(long id); } \ No newline at end of file diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java index a3770e42d..6cd574306 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 @@ -268,7 +268,7 @@ public interface ControllerManagement { * @see Target#getControllerId() */ @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER + " or " + SpringEvalExpressions.IS_SYSTEM_CODE) - Optional getByControllerId(@NotEmpty String controllerId); + Optional findByControllerId(@NotEmpty String controllerId); /** * Finds {@link Target} based on given ID returns found Target without details, i.e. @@ -280,7 +280,7 @@ public interface ControllerManagement { * @see Target#getId() */ @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER + " or " + SpringEvalExpressions.IS_SYSTEM_CODE) - Optional get(long targetId); + Optional find(long targetId); /** * Retrieves the specified number of messages from action history of the given {@link Action} based on messageCount. Regardless of the 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 838a00dbc..83aa21f05 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 @@ -37,7 +37,6 @@ import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException; import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException; import org.eclipse.hawkbit.repository.exception.UnsupportedSoftwareModuleForThisDistributionSetException; import org.eclipse.hawkbit.repository.model.DistributionSet; -import org.eclipse.hawkbit.repository.model.DistributionSetFilter; import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.NamedEntity; @@ -46,7 +45,6 @@ import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.Statistic; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Slice; import org.springframework.security.access.prepost.PreAuthorize; /** @@ -62,7 +60,7 @@ public interface DistributionSetManagement /** * Find {@link DistributionSet} based on given ID including (lazy loaded) details, e.g. {@link DistributionSet#getModules()}.
- * For performance reasons it is recommended to use {@link #get(long)} if the details are not required. + * For performance reasons it is recommended to use {@link #find(long)} if the details are not required. * * @param id to look for. * @return {@link DistributionSet} @@ -70,16 +68,6 @@ public interface DistributionSetManagement @PreAuthorize(HAS_READ_REPOSITORY) Optional getWithDetails(long id); - /** - * Find distribution set by id and throw an exception if it is (soft) deleted. - * - * @param id id of {@link DistributionSet} - * @return the found valid {@link DistributionSet} - * @throws EntityNotFoundException if distribution set with given ID does not exist - */ - @PreAuthorize(HAS_READ_REPOSITORY) - T getOrElseThrowException(long id); - @PreAuthorize(HAS_READ_REPOSITORY) boolean shouldLockImplicitly(final DistributionSet distributionSet); diff --git a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RepositoryManagement.java b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RepositoryManagement.java index cde60f010..0b2156ea3 100644 --- a/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RepositoryManagement.java +++ b/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/RepositoryManagement.java @@ -11,6 +11,7 @@ package org.eclipse.hawkbit.repository; import java.util.Collection; import java.util.List; +import java.util.Map; import java.util.Optional; import jakarta.validation.ConstraintViolationException; @@ -26,7 +27,6 @@ import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldExc import org.eclipse.hawkbit.repository.model.BaseEntity; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Slice; import org.springframework.security.access.prepost.PreAuthorize; /** @@ -58,6 +58,16 @@ public interface RepositoryManagement create(@NotNull @Valid Collection create); + /** + * Retrieve {@link BaseEntity} and throws exception if not found. + * + * @param id to search for + * @return {@link BaseEntity} in the repository with given {@link BaseEntity#getId()} + * @throws EntityNotFoundException if no entity with given ID exists + */ + @PreAuthorize(SpringEvalExpressions.HAS_READ_REPOSITORY) + T get(long id); + /** * Retrieve {@link BaseEntity} * @@ -65,16 +75,26 @@ public interface RepositoryManagement get(long id); + Optional find(long id); /** - * Retrieves all {@link BaseEntity}s without details. + * Retrieves {@link BaseEntity}s by id and throws exception if any of the requested entities are not found. + * + * @param ids the ids to for + * @return the found {@link BaseEntity}s + * @throws EntityNotFoundException if at least one of the given ids does not exist + */ + @PreAuthorize(SpringEvalExpressions.HAS_READ_REPOSITORY) + List get(@NotEmpty Collection ids); + + /** + * Retrieves {@link BaseEntity}s by id and skips not found. * * @param ids the ids to for * @return the found {@link BaseEntity}s */ @PreAuthorize(SpringEvalExpressions.HAS_READ_REPOSITORY) - List get(@NotEmpty Collection ids); + List find(@NotEmpty Collection ids); /** * Retrieves {@link Page} of all {@link BaseEntity} of given type. @@ -134,6 +154,18 @@ public interface RepositoryManagement key is the ID of the entity, value is the updated entity + * @throws EntityReadOnlyException if the {@link BaseEntity} cannot be updated (e.g. is already in use) + * @throws EntityNotFoundException in case the {@link BaseEntity} does not exist and cannot be updated + * @throws ConstraintViolationException if fields are not filled as specified. Check {@link BaseEntity} for field constraints. + */ + @PreAuthorize(SpringEvalExpressions.HAS_UPDATE_REPOSITORY) + Map update(@NotNull @Valid Collection update); + /** * Deletes or marks as delete in case the {@link BaseEntity} is in use. * 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 f60b62a29..739932af3 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 @@ -235,18 +235,16 @@ public interface RolloutManagement extends PermissionSupport { * Retrieves a specific rollout by its ID. * * @param rolloutId the ID of the rollout to retrieve - * @return the founded rollout or {@code null} if rollout with given ID does - * not exists + * @return the found rollout or empty if rollout with given ID does not exist */ @PreAuthorize(SpringEvalExpressions.HAS_READ_REPOSITORY) - Optional get(long rolloutId); + Optional find(long rolloutId); /** * Retrieves a specific rollout by its name. * * @param rolloutName the name of the rollout to retrieve - * @return the founded rollout or {@code null} if rollout with given name - * does not exists + * @return the found rollout or empty if rollout with given ID does not exist */ @PreAuthorize(SpringEvalExpressions.HAS_READ_REPOSITORY) Optional getByName(@NotEmpty String rolloutName); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutHandler.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutHandler.java index 4d378cc1e..6c19f11aa 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutHandler.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/JpaRolloutHandler.java @@ -16,7 +16,6 @@ import java.util.concurrent.locks.Lock; import io.micrometer.core.instrument.MeterRegistry; import lombok.extern.slf4j.Slf4j; -import org.eclipse.hawkbit.ContextAware; import org.eclipse.hawkbit.repository.RolloutExecutor; import org.eclipse.hawkbit.repository.RolloutHandler; import org.eclipse.hawkbit.repository.RolloutManagement; @@ -108,7 +107,7 @@ public class JpaRolloutHandler implements RolloutHandler { final long startNano = System.nanoTime(); DeploymentHelper.runInNewTransaction(txManager, handlerId + "-" + rolloutId, status -> { - rolloutManagement.get(rolloutId).ifPresentOrElse( + rolloutManagement.find(rolloutId).ifPresentOrElse( rolloutExecutor::execute, () -> log.error("Could not retrieve rollout with id {}. Will not continue with execution.", rolloutId)); return 0L; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/AbstractJpaRepositoryManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/AbstractJpaRepositoryManagement.java index a2dea5bf3..f3ab09819 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/AbstractJpaRepositoryManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/AbstractJpaRepositoryManagement.java @@ -15,12 +15,16 @@ import static org.eclipse.hawkbit.repository.jpa.configuration.Constants.TX_RT_M import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -31,11 +35,13 @@ import jakarta.persistence.criteria.CriteriaUpdate; import jakarta.persistence.criteria.Root; import jakarta.validation.constraints.NotNull; +import lombok.extern.slf4j.Slf4j; import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.Identifiable; import org.eclipse.hawkbit.repository.RepositoryManagement; import org.eclipse.hawkbit.repository.RsqlQueryField; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; +import org.eclipse.hawkbit.repository.exception.InvalidDistributionSetException; import org.eclipse.hawkbit.repository.jpa.Jpa; import org.eclipse.hawkbit.repository.jpa.JpaManagementHelper; import org.eclipse.hawkbit.repository.jpa.JpaRepositoryConfiguration; @@ -48,7 +54,6 @@ import org.eclipse.hawkbit.utils.ObjectCopyUtil; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Slice; import org.springframework.data.jpa.domain.Specification; import org.springframework.retry.annotation.Backoff; import org.springframework.retry.annotation.Retryable; @@ -73,6 +78,7 @@ import org.springframework.validation.annotation.Validated; @HandleAuthorizationDenied(handlerClass = JpaRepositoryConfiguration.ManagementExceptionThrowingMethodAuthorizationDeniedHandler.class) @Transactional(readOnly = true) @Validated +@Slf4j abstract class AbstractJpaRepositoryManagement, R extends BaseEntityRepository, A extends Enum & RsqlQueryField> implements RepositoryManagement { @@ -81,6 +87,7 @@ abstract class AbstractJpaRepositoryManagement jpaEntityCreator; + private final Function isValid; protected AbstractJpaRepositoryManagement(final R jpaRepository, final EntityManager entityManager) { this.jpaRepository = jpaRepository; @@ -100,6 +107,25 @@ abstract class AbstractJpaRepositoryManagement { + if (isValidMethodF == null) { + return true; // if there is no isValid method, then it is always valid + } else { + try { + return (Boolean) isValidMethodF.invoke(jpaEntity); + } catch (final IllegalAccessException | InvocationTargetException e) { + log.error(e.getMessage(), e); + return false; // if it fails, then it is not valid + } + } + }; } @Override @@ -117,13 +143,23 @@ abstract class AbstractJpaRepositoryManagement get(final long id) { + public T get(final long id) { + return jpaRepository.getById(id); + } + + @Override + public Optional find(final long id) { return jpaRepository.findById(id); } @Override public List get(final Collection ids) { - return findAllById(ids); + return findAllById(ids, true); + } + + @Override + public List find(final Collection ids) { + return findAllById(ids, false); } @Override @@ -157,13 +193,8 @@ abstract class AbstractJpaRepositoryManagement new EntityNotFoundException(managementClass(), update.getId())); - return update(update, entity); - } - - protected T update(final Identifiable update, final T entity) { + final T entity = getValid(update.getId()); + checkUpdate(update, entity); // update getId has no setter in target JPA entity but shall have getter and the value shall be the same // otherwise the Utils will throw an exception that there is no counterpart setter for getId if (ObjectCopyUtil.copy(update, entity, false, this::attach)) { @@ -173,6 +204,43 @@ abstract class AbstractJpaRepositoryManagement update(final Collection update) { + final Map toUpdate = findAllById(update.stream().map(Identifiable::getId).toList(), true) + .stream() + .filter(entity -> { + if (Boolean.FALSE.equals(isValid.apply(entity))) { + throw new InvalidDistributionSetException( + jpaRepository.getManagementClass().getSimpleName() + " " + entity.getId() + " is invalid"); + } + return true; + }) + .collect(Collectors.toMap(Identifiable::getId, Function.identity())); + final List toSave = new ArrayList<>(toUpdate.values()); + for (final U u : update) { + final T entity = toUpdate.get(u.getId()); + checkUpdate(u, entity); + // update getId has no setter in target JPA entity but shall have getter and the value shall be the same + // otherwise the Utils will throw an exception that there is no counterpart setter for getId + if (ObjectCopyUtil.copy(u, entity, false, this::attach)) { + toSave.add(entity); + } + } + if (toSave.isEmpty()) { + return toUpdate; + } else { + final List savedEntities = jpaRepository.saveAll(toSave); + final Map result = new HashMap<>(toUpdate); + for (final T savedEntity : savedEntities) { + result.put(savedEntity.getId(), savedEntity); + } + return result; + } + } + @Override @Transactional @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = TX_RT_MAX, backoff = @Backoff(delay = TX_RT_DELAY)) @@ -194,18 +262,28 @@ abstract class AbstractJpaRepositoryManagement List.of(RsqlUtility.getInstance().buildRsqlSpecification(rsql, fieldsClass()))); } + protected void checkUpdate(final U update, final T distributionSet) {} + // return which are for soft deletion @SuppressWarnings("java:S1172") // java:S1172 - it is intended to be used by subclasses protected Collection softDelete(final Collection toDelete) { return Collections.emptyList(); } + protected T getValid(final Long id) { + final T jpaEntity = jpaRepository.getById(id); + if (Boolean.FALSE.equals(isValid.apply(jpaEntity))) { + throw new InvalidDistributionSetException(jpaRepository.getManagementClass().getSimpleName() + " " + id + " is invalid"); + } + return jpaEntity; + } + protected void delete0(final Collection ids) { if (ObjectUtils.isEmpty(ids)) { return; } - final List toDelete = findAllById(ids); // throws EntityNotFoundException if any of these does not exist + final List toDelete = findAllById(ids, true); // throws EntityNotFoundException if any of these does not exist jpaRepository.getAccessController().ifPresent(ac -> { for (final T entity : toDelete) { ac.assertOperationAllowed(AccessController.Operation.DELETE, entity); @@ -240,9 +318,9 @@ abstract class AbstractJpaRepositoryManagement findAllById(final Collection ids) { + private List findAllById(final Collection ids, final boolean throwIfNotFound) { final List foundDs = jpaRepository.findAllById(ids); - if (foundDs.size() != ids.size()) { + if (throwIfNotFound && foundDs.size() != ids.size()) { throw new EntityNotFoundException(managementClass(), ids, foundDs.stream().map(T::getId).toList()); } return foundDs; diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/AbstractJpaRepositoryWithMetadataManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/AbstractJpaRepositoryWithMetadataManagement.java index 97ac16f18..752b84364 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/AbstractJpaRepositoryWithMetadataManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/AbstractJpaRepositoryWithMetadataManagement.java @@ -121,14 +121,8 @@ abstract class AbstractJpaRepositoryWithMetadataManagement getMetadata(final Long id) { - return jpaRepository - .findById(id) - .map(T::getMetadata) - .map(metadata -> metadata.entrySet().stream() - .collect(Collectors.toMap( - Map.Entry::getKey, - e -> (MV) e.getValue()))) - .orElseThrow(() -> new EntityNotFoundException(jpaRepository.getManagementClass(), id)); + final T entity = jpaRepository.getById(id); + return entity.getMetadata().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } @Override @@ -146,16 +140,6 @@ abstract class AbstractJpaRepositoryWithMetadataManagement new EntityNotFoundException(jpaRepository.getManagementClass(), id)); - if (!jpaEntity.isValid()) { - throw new InvalidDistributionSetException(jpaRepository.getManagementClass().getSimpleName() + " " + id + " is invalid"); - } - return jpaEntity; - } - @SuppressWarnings("unchecked") private boolean setMetadataValue(final String key, final MV newValue, final MVI existingValue, final Map metadataValueMap) { if (useCopy) { diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaActionManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaActionManagement.java index e04be2053..ff35ef061 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaActionManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaActionManagement.java @@ -21,7 +21,6 @@ import java.util.stream.Stream; import lombok.extern.slf4j.Slf4j; import org.eclipse.hawkbit.repository.QuotaManagement; import org.eclipse.hawkbit.repository.RepositoryProperties; -import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.jpa.model.AbstractJpaBaseEntity_; import org.eclipse.hawkbit.repository.jpa.model.JpaAction; import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus; @@ -80,7 +79,7 @@ public class JpaActionManagement { protected Action addActionStatus(final ActionStatusCreate create) { final Long actionId = create.getActionId(); - final JpaAction action = getActionAndThrowExceptionIfNotFound(actionId); + final JpaAction action = actionRepository.getById(actionId); if (isUpdatingActionStatusAllowed(action, create)) { return handleAddUpdateActionStatus(create, action); @@ -92,10 +91,6 @@ public class JpaActionManagement { return action; } - protected JpaAction getActionAndThrowExceptionIfNotFound(final Long actionId) { - return actionRepository.findById(actionId).orElseThrow(() -> new EntityNotFoundException(Action.class, actionId)); - } - protected void onActionStatusUpdate(final JpaActionStatus newActionStatus, final JpaAction action) { // can be overwritten to intercept the persistence of the action status } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaArtifactManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaArtifactManagement.java index 24e72ea09..32a09c705 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaArtifactManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaArtifactManagement.java @@ -13,24 +13,22 @@ import java.io.IOException; import java.io.InputStream; import java.util.Optional; -import jakarta.annotation.Nullable; import jakarta.persistence.EntityManager; import lombok.extern.slf4j.Slf4j; +import org.eclipse.hawkbit.repository.ArtifactManagement; +import org.eclipse.hawkbit.repository.QuotaManagement; import org.eclipse.hawkbit.repository.artifact.ArtifactRepository; +import org.eclipse.hawkbit.repository.artifact.encryption.ArtifactEncryptionService; +import org.eclipse.hawkbit.repository.artifact.exception.ArtifactBinaryNotFoundException; +import org.eclipse.hawkbit.repository.artifact.exception.ArtifactDeleteFailedException; import org.eclipse.hawkbit.repository.artifact.exception.ArtifactStoreException; +import org.eclipse.hawkbit.repository.artifact.exception.ArtifactUploadFailedException; import org.eclipse.hawkbit.repository.artifact.exception.HashNotMatchException; import org.eclipse.hawkbit.repository.artifact.model.AbstractDbArtifact; import org.eclipse.hawkbit.repository.artifact.model.DbArtifact; import org.eclipse.hawkbit.repository.artifact.model.DbArtifactHash; -import org.eclipse.hawkbit.repository.artifact.encryption.ArtifactEncryptionService; -import org.eclipse.hawkbit.repository.ArtifactManagement; -import org.eclipse.hawkbit.repository.QuotaManagement; -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.InsufficientPermissionException; import org.eclipse.hawkbit.repository.exception.InvalidMD5HashException; import org.eclipse.hawkbit.repository.exception.InvalidSHA1HashException; import org.eclipse.hawkbit.repository.exception.InvalidSHA256HashException; @@ -53,8 +51,6 @@ import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.tenancy.TenantAware; import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty; import org.springframework.dao.ConcurrencyFailureException; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; import org.springframework.retry.annotation.Backoff; import org.springframework.retry.annotation.Retryable; import org.springframework.stereotype.Service; @@ -72,49 +68,49 @@ import org.springframework.validation.annotation.Validated; @ConditionalOnBooleanProperty(prefix = "hawkbit.jpa", name = { "enabled", "artifact-management" }, matchIfMissing = true) public class JpaArtifactManagement implements ArtifactManagement { + private final LocalArtifactRepository localArtifactRepository; + private final ArtifactRepository artifactRepository; + private final SoftwareModuleRepository softwareModuleRepository; private final EntityManager entityManager; private final PlatformTransactionManager txManager; - private final LocalArtifactRepository localArtifactRepository; - private final SoftwareModuleRepository softwareModuleRepository; - @Nullable - private final ArtifactRepository artifactRepository; private final TenantAware tenantAware; private final QuotaManagement quotaManagement; protected JpaArtifactManagement( + final LocalArtifactRepository localArtifactRepository, + final Optional artifactRepository, + final SoftwareModuleRepository softwareModuleRepository, final EntityManager entityManager, final PlatformTransactionManager txManager, - final LocalArtifactRepository localArtifactRepository, - final SoftwareModuleRepository softwareModuleRepository, @Nullable final ArtifactRepository artifactRepository, final QuotaManagement quotaManagement, final TenantAware tenantAware) { + this.localArtifactRepository = localArtifactRepository; + this.artifactRepository = artifactRepository.orElse(null); + this.softwareModuleRepository = softwareModuleRepository; this.entityManager = entityManager; this.txManager = txManager; - this.localArtifactRepository = localArtifactRepository; - this.softwareModuleRepository = softwareModuleRepository; - this.artifactRepository = artifactRepository; this.quotaManagement = quotaManagement; this.tenantAware = tenantAware; } - @Override - public long count() { - return localArtifactRepository.count(); - } - @Override @Transactional @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY)) public Artifact create(final ArtifactUpload artifactUpload) { - assertArtifactRepositoryAvailable(); + if (artifactRepository == null) { + throw new UnsupportedOperationException(); + } final long moduleId = artifactUpload.getModuleId(); - assertArtifactQuota(moduleId, 1); - final JpaSoftwareModule softwareModule = - softwareModuleRepository - .findById(moduleId) - .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, moduleId)); + QuotaHelper.assertAssignmentQuota( + moduleId, 1, quotaManagement.getMaxArtifactsPerSoftwareModule(), + Artifact.class, SoftwareModule.class, + // get all artifacts without user context + softwareModuleId -> localArtifactRepository + .count(null, ArtifactSpecifications.bySoftwareModuleId(softwareModuleId))); + + final JpaSoftwareModule softwareModule = softwareModuleRepository.getById(moduleId); final String filename = artifactUpload.getFilename(); final Artifact existing = softwareModule.getArtifactByFilename(filename).orElse(null); @@ -139,12 +135,34 @@ public class JpaArtifactManagement implements ArtifactManagement { } } + @SuppressWarnings("java:S2201") // java:S2201 - the idea is to just check if the artifact exists + @Override + public DbArtifact loadArtifactBinary(final String sha1Hash, final long softwareModuleId, final boolean isEncrypted) { + if (artifactRepository == null) { + throw new UnsupportedOperationException(); + } + + final String tenant = tenantAware.getCurrentTenant(); + // check access to the software module and if artifact belongs to it + for (final Artifact artifact : softwareModuleRepository.getById(softwareModuleId).getArtifacts()) { + if (artifact.getSha1Hash().equals(sha1Hash)) { + final DbArtifact dbArtifact = artifactRepository.getBySha1(tenant, sha1Hash); + return isEncrypted ? wrapInEncryptionAwareDbArtifact(softwareModuleId, dbArtifact) : dbArtifact; + } + } + throw new ArtifactBinaryNotFoundException(sha1Hash); + } + @Override @Transactional @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY)) public void delete(final long id) { - final JpaArtifact toDelete = (JpaArtifact) get(id).orElseThrow(() -> new EntityNotFoundException(Artifact.class, id)); + if (artifactRepository == null) { + throw new UnsupportedOperationException(); + } + + final JpaArtifact toDelete = localArtifactRepository.getById(id); final JpaSoftwareModule softwareModule = toDelete.getSoftwareModule(); // clearArtifactBinary checks (unconditionally) software module UPDATE access @@ -159,66 +177,6 @@ public class JpaArtifactManagement implements ArtifactManagement { AfterTransactionCommitExecutorHolder.getInstance().getAfterCommit().afterCommit(() -> clearArtifactBinary(sha1Hash)); } - @Override - public Optional get(final long id) { - return localArtifactRepository.findById(id).map(Artifact.class::cast); - } - - @Override - public Optional getByFilenameAndSoftwareModule(final String filename, final long softwareModuleId) { - assertSoftwareModuleExists(softwareModuleId); - - return localArtifactRepository.findFirstByFilenameAndSoftwareModuleId(filename, softwareModuleId); - } - - @Override - public Optional findFirstBySHA1(final String sha1Hash) { - return localArtifactRepository.findFirstBySha1Hash(sha1Hash); - } - - @Override - public Optional getByFilename(final String filename) { - return localArtifactRepository.findFirstByFilename(filename); - } - - @Override - public Page findBySoftwareModule(final long softwareModuleId, final Pageable pageable) { - assertSoftwareModuleExists(softwareModuleId); - - return localArtifactRepository - .findAll(ArtifactSpecifications.bySoftwareModuleId(softwareModuleId), pageable) - .map(Artifact.class::cast); - } - - @Override - public long countBySoftwareModule(final long softwareModuleId) { - assertSoftwareModuleExists(softwareModuleId); - - return localArtifactRepository.count(ArtifactSpecifications.bySoftwareModuleId(softwareModuleId)); - } - - @SuppressWarnings("java:S2201") // java:S2201 - the idea is to just check if the artifact exists - @Override - public Optional loadArtifactBinary(final String sha1Hash, final long softwareModuleId, final boolean isEncrypted) { - assertArtifactRepositoryAvailable(); - - assertSoftwareModuleExists(softwareModuleId); - - final String tenant = tenantAware.getCurrentTenant(); - if (artifactRepository.existsByTenantAndSha1(tenant, sha1Hash)) { - // assert artifact exists and belongs to the software module - findFirstBySHA1(sha1Hash) - // if not found no assertOperationAllowed shall fail - .orElseThrow(InsufficientPermissionException::new); - - final DbArtifact dbArtifact = artifactRepository.getArtifactBySha1(tenant, sha1Hash); - return Optional.ofNullable( - isEncrypted ? wrapInEncryptionAwareDbArtifact(softwareModuleId, dbArtifact) : dbArtifact); - } - - return Optional.empty(); - } - /** * Garbage collects artifact binaries if only referenced by given {@link SoftwareModule#getId()} or {@link SoftwareModule}'s that are * marked as deleted. @@ -231,11 +189,10 @@ public class JpaArtifactManagement implements ArtifactManagement { * @param sha1Hash no longer needed */ void clearArtifactBinary(final String sha1Hash) { - assertArtifactRepositoryAvailable(); - DeploymentHelper.runInNewTransaction(txManager, "clearArtifactBinary", status -> { // countBySha1HashAndTenantAndSoftwareModuleDeletedIsFalse will skip ACM checks and will return total count as it should be - if (localArtifactRepository.countBySha1HashAndTenantAndSoftwareModuleDeletedIsFalse(sha1Hash, tenantAware.getCurrentTenant()) <= 0) { // 1 artifact is the one being deleted! + if (localArtifactRepository.countBySha1HashAndTenantAndSoftwareModuleDeletedIsFalse(sha1Hash, + tenantAware.getCurrentTenant()) <= 0) { // 1 artifact is the one being deleted! // removes the real artifact ONLY AFTER the delete of artifact or software module // in local history has passed successfully (caller has permission and no errors) AfterTransactionCommitExecutorHolder.getInstance().getAfterCommit().afterCommit(() -> { @@ -252,19 +209,17 @@ public class JpaArtifactManagement implements ArtifactManagement { } private AbstractDbArtifact storeArtifact(final ArtifactUpload artifactUpload, final boolean isSmEncrypted) { - final String tenant = tenantAware.getCurrentTenant(); - final long smId = artifactUpload.getModuleId(); final InputStream stream = artifactUpload.getInputStream(); - final String fileName = artifactUpload.getFilename(); - final String contentType = artifactUpload.getContentType(); - final String providedSha1 = artifactUpload.getProvidedSha1Sum(); - final String providedMd5 = artifactUpload.getProvidedMd5Sum(); - final String providedSha256 = artifactUpload.getProvidedSha256Sum(); - try (final InputStream wrappedStream = wrapInQuotaStream( - isSmEncrypted ? wrapInEncryptionStream(smId, stream) : stream)) { - return artifactRepository.store(tenant, wrappedStream, fileName, contentType, - new DbArtifactHash(providedSha1, providedMd5, providedSha256)); + isSmEncrypted + ? wrapInEncryptionStream(artifactUpload.getModuleId(), stream) + : stream)) { + return artifactRepository.store( + tenantAware.getCurrentTenant(), wrappedStream, artifactUpload.getFilename(), artifactUpload.getContentType(), + new DbArtifactHash( + artifactUpload.getProvidedSha1Sum(), + artifactUpload.getProvidedMd5Sum(), + artifactUpload.getProvidedSha256Sum())); } catch (final ArtifactStoreException | IOException e) { throw new ArtifactUploadFailedException(e); } catch (final HashNotMatchException e) { @@ -282,15 +237,6 @@ public class JpaArtifactManagement implements ArtifactManagement { return ArtifactEncryptionService.getInstance().encryptArtifact(smId, stream); } - private void assertArtifactQuota(final long moduleId, final int requested) { - QuotaHelper.assertAssignmentQuota( - moduleId, requested, quotaManagement.getMaxArtifactsPerSoftwareModule(), - Artifact.class, SoftwareModule.class, - // get all artifacts without user context - softwareModuleId -> localArtifactRepository - .count(null, ArtifactSpecifications.bySoftwareModuleId(softwareModuleId))); - } - private InputStream wrapInQuotaStream(final InputStream in) { final long maxArtifactSize = quotaManagement.getMaxArtifactSize(); @@ -311,8 +257,9 @@ public class JpaArtifactManagement implements ArtifactManagement { encryptionService.encryptionSizeOverhead()); } - private Artifact storeArtifactMetadata(final SoftwareModule softwareModule, final String providedFilename, - final AbstractDbArtifact result, final Artifact existing) { + private Artifact storeArtifactMetadata( + final SoftwareModule softwareModule, final String providedFilename, final AbstractDbArtifact result, + final Artifact existing) { final JpaArtifact artifact; if (existing == null) { artifact = new JpaArtifact(result.getHashes().getSha1(), providedFilename, softwareModule); @@ -327,16 +274,4 @@ public class JpaArtifactManagement implements ArtifactManagement { log.debug("storing new artifact into repository {}", artifact); return localArtifactRepository.save(AccessController.Operation.CREATE, artifact); } - - private void assertSoftwareModuleExists(final long softwareModuleId) { - if (!softwareModuleRepository.existsById(softwareModuleId)) { - throw new EntityNotFoundException(SoftwareModule.class, softwareModuleId); - } - } - - private void assertArtifactRepositoryAvailable() { - if (artifactRepository == null) { - throw new UnsupportedOperationException("ArtifactRepository is unavailable"); - } - } } \ No newline at end of file diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaConfirmationManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaConfirmationManagement.java index 3141774a0..8c6ce33ab 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaConfirmationManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaConfirmationManagement.java @@ -108,7 +108,7 @@ public class JpaConfirmationManagement extends JpaActionManagement implements Co backoff = @Backoff(delay = Constants.TX_RT_DELAY)) public Action confirmAction(final long actionId, final Integer code, final Collection deviceMessages) { log.trace("Action with id {} confirm request is triggered.", actionId); - final Action action = getActionAndThrowExceptionIfNotFound(actionId); + final Action action = actionRepository.getById(actionId); assertActionCanAcceptFeedback(action); final List messages = new ArrayList<>(); if (deviceMessages != null) { @@ -124,7 +124,7 @@ public class JpaConfirmationManagement extends JpaActionManagement implements Co backoff = @Backoff(delay = Constants.TX_RT_DELAY)) public Action denyAction(final long actionId, final Integer code, final Collection deviceMessages) { log.trace("Action with id {} deny request is triggered.", actionId); - final Action action = getActionAndThrowExceptionIfNotFound(actionId); + final Action action = actionRepository.getById(actionId); assertActionCanAcceptFeedback(action); final List messages = new ArrayList<>(); if (deviceMessages != null) { diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaControllerManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaControllerManagement.java index 38e8c06f8..713044d97 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaControllerManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaControllerManagement.java @@ -223,7 +223,7 @@ public class JpaControllerManagement extends JpaActionManagement implements Cont } case DOWNLOADED: { handleDownloadedActionStatus(action).ifPresent(controllerId -> - requestControllerAttributes(getByControllerId(controllerId) + requestControllerAttributes(findByControllerId(controllerId) .map(JpaTarget.class::cast) .orElseThrow(() -> new EntityNotFoundException(Target.class, controllerId)))); break; @@ -239,7 +239,7 @@ public class JpaControllerManagement extends JpaActionManagement implements Cont @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY)) public Action addCancelActionStatus(final ActionStatusCreate create) { - final JpaAction action = getActionAndThrowExceptionIfNotFound(create.getActionId()); + final JpaAction action = actionRepository.getById(create.getActionId()); if (!action.isCancelingOrCanceled()) { throw new CancelActionNotAllowedException("The action is not in canceling state."); } @@ -284,7 +284,7 @@ public class JpaControllerManagement extends JpaActionManagement implements Cont @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY)) public ActionStatus addInformationalActionStatus(final ActionStatusCreate create) { - final JpaAction action = getActionAndThrowExceptionIfNotFound(create.getActionId()); + final JpaAction action = actionRepository.getById(create.getActionId()); assertActionStatusQuota(create, action); final JpaActionStatus actionStatus = buildJpaActionStatus(create); @@ -476,13 +476,13 @@ public class JpaControllerManagement extends JpaActionManagement implements Cont } @Override - public Optional getByControllerId(final String controllerId) { - return targetRepository.findByControllerId(controllerId).map(Target.class::cast); + public Optional find(final long targetId) { + return targetRepository.findById(targetId).map(Target.class::cast); } @Override - public Optional get(final long targetId) { - return targetRepository.findById(targetId).map(Target.class::cast); + public Optional findByControllerId(final String controllerId) { + return targetRepository.findByControllerId(controllerId).map(Target.class::cast); } @Override @@ -538,10 +538,7 @@ public class JpaControllerManagement extends JpaActionManagement implements Cont targetRepository.getAccessController().ifPresent( accessController -> accessController.assertOperationAllowed( AccessController.Operation.UPDATE, - actionRepository - .findById(actionId) - .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId)) - .getTarget())); + actionRepository.getById(actionId).getTarget())); actionRepository.updateExternalRef(actionId, externalRef); } @@ -579,13 +576,14 @@ public class JpaControllerManagement extends JpaActionManagement implements Cont public boolean updateOfflineAssignedVersion(@NotEmpty final String controllerId, final String distributionName, final String version) { List distributionSetAssignmentResults = systemSecurityContext.runAsSystem(() -> - distributionSetManagement.findByNameAndVersion(distributionName, version).map( - distributionSet -> deploymentManagement.offlineAssignedDistributionSets( - controllerId, List.of(Map.entry(controllerId, distributionSet.getId())))) + distributionSetManagement.findByNameAndVersion(distributionName, version) + .map(distributionSet -> deploymentManagement.offlineAssignedDistributionSets( + controllerId, List.of(Map.entry(controllerId, distributionSet.getId())))) .orElseThrow(() -> new EntityNotFoundException(DistributionSet.class, Map.entry(distributionName, version)))); - return distributionSetAssignmentResults.stream().findFirst() + return distributionSetAssignmentResults.stream() + .findFirst() .map(result -> result.getAlreadyAssigned() == 0) .orElseThrow(); } @@ -901,7 +899,7 @@ public class JpaControllerManagement extends JpaActionManagement implements Cont * {@link Status#RETRIEVED} */ private Action handleRegisterRetrieved(final Long actionId, final String message) { - final JpaAction action = getActionAndThrowExceptionIfNotFound(actionId); + final JpaAction action = actionRepository.getById(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 don't need an extra count // query, we just want to check if the last action status is a retrieved or not. diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaDeploymentManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaDeploymentManagement.java index 6a23e18c7..deb943197 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaDeploymentManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaDeploymentManagement.java @@ -222,7 +222,7 @@ public class JpaDeploymentManagement extends JpaActionManagement implements Depl private Action cancelAction0(final long actionId) { log.debug("cancelAction({})", actionId); - final JpaAction action = actionRepository.findById(actionId).orElseThrow(() -> new EntityNotFoundException(Action.class, actionId)); + final JpaAction action = actionRepository.getById(actionId); if (action.isCancelingOrCanceled()) { throw new CancelActionNotAllowedException("Actions in canceling or canceled state cannot be canceled"); @@ -378,7 +378,7 @@ public class JpaDeploymentManagement extends JpaActionManagement implements Depl } private Action forceQuitAction0(final long actionId) { - final JpaAction action = actionRepository.findById(actionId).orElseThrow(() -> new EntityNotFoundException(Action.class, actionId)); + final JpaAction action = actionRepository.getById(actionId); if (!action.isCancelingOrCanceled()) { throw new ForceQuitActionNotAllowedException(action.getId() + " is not canceled yet and cannot be force quit"); @@ -406,7 +406,8 @@ public class JpaDeploymentManagement extends JpaActionManagement implements Depl @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY)) public Action forceTargetAction(final long actionId) { - final JpaAction action = actionRepository.findById(actionId).map(this::assertTargetUpdateAllowed) + final JpaAction action = actionRepository.findById(actionId) + .map(this::assertTargetUpdateAllowed) .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId)); if (!action.isForcedOrTimeForced()) { @@ -997,9 +998,4 @@ public class JpaDeploymentManagement extends JpaActionManagement implements Depl throw new EntityNotFoundException(Action.class, actionId); } } - - private Page findActiveActionsForRollout(long rolloutId, Pageable pageable) { - return actionRepository - .findAll(ActionSpecifications.byRolloutIdAndActive(rolloutId), pageable); - } } \ No newline at end of file diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaDistributionSetInvalidationManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaDistributionSetInvalidationManagement.java index 45a95fa38..18cb80f1b 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaDistributionSetInvalidationManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaDistributionSetInvalidationManagement.java @@ -9,7 +9,6 @@ */ package org.eclipse.hawkbit.repository.jpa.management; -import java.util.Collection; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; @@ -22,13 +21,10 @@ import org.eclipse.hawkbit.repository.RolloutManagement; import org.eclipse.hawkbit.repository.TargetFilterQueryManagement; import org.eclipse.hawkbit.repository.exception.IncompleteDistributionSetException; import org.eclipse.hawkbit.repository.exception.StopRolloutException; -import org.eclipse.hawkbit.repository.jpa.repository.ActionRepository; import org.eclipse.hawkbit.repository.jpa.utils.DeploymentHelper; -import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.ActionCancellationType; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetInvalidation; -import org.eclipse.hawkbit.repository.model.DistributionSetInvalidationCount; import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.eclipse.hawkbit.security.SystemSecurityContext; import org.eclipse.hawkbit.tenancy.TenantAware; @@ -115,7 +111,7 @@ public class JpaDistributionSetInvalidationManagement implements DistributionSet } private void invalidateDistributionSet(final long setId, final ActionCancellationType cancelationType) { - final DistributionSet distributionSet = distributionSetManagement.getOrElseThrowException(setId); + final DistributionSet distributionSet = distributionSetManagement.get(setId); if (!distributionSet.isComplete()) { throw new IncompleteDistributionSetException( "Distribution set of type " + distributionSet.getType().getKey() + " is incomplete: " + distributionSet.getId()); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaDistributionSetManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaDistributionSetManagement.java index e37f60d56..b7b7813f0 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaDistributionSetManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaDistributionSetManagement.java @@ -105,28 +105,32 @@ public class JpaDistributionSetManagement this.repositoryProperties = repositoryProperties; } - @SuppressWarnings("java:S1066") // java:S1066 better readable without merging the if statements @Override public JpaDistributionSet update(final Update update) { - final JpaDistributionSet distributionSet = getValid0(update.getId()); - - // lock/unlock ONLY if locked flag is present! + final JpaDistributionSet updated = super.update(update); if (Boolean.TRUE.equals(update.getLocked())) { - if (!distributionSet.isLocked()) { - lockSoftwareModules(distributionSet); - distributionSet.setLocked(true); - } - } else if (Boolean.FALSE.equals(update.getLocked())) { - if (distributionSet.isLocked()) { - distributionSet.setLocked(false); + lockSoftwareModules(updated); + } + return updated; + } + + @Override + public Map update(final Collection updates) { + final Map updated = super.update(updates); + for (final Update update : updates) { + final JpaDistributionSet updatedSet = updated.get(update.getId()); + if (Boolean.TRUE.equals(update.getLocked())) { + lockSoftwareModules(updatedSet); } } + return updated; + } + @Override + protected void checkUpdate(final Update update, final JpaDistributionSet distributionSet) { if (update.getRequiredMigrationStep() != null && !update.getRequiredMigrationStep().equals(distributionSet.isRequiredMigrationStep())) { assertDistributionSetIsNotAssignedToTargets(update.getId()); } - - return super.update(update, distributionSet); } @Override @@ -154,11 +158,6 @@ public class JpaDistributionSetManagement return jpaRepository.findOne(jpaRepository.byIdSpec(id), JpaDistributionSet_.GRAPH_DISTRIBUTION_SET_DETAIL); } - @Override - public JpaDistributionSet getOrElseThrowException(final long id) { - return getById(id); - } - // implicitly lock a distribution set if not already locked and implicit lock is enabled and not to skip @Override @Transactional @@ -256,7 +255,7 @@ public class JpaDistributionSetManagement final JpaDistributionSet set = getValid0(id); assertDistributionSetIsNotAssignedToTargets(id); - final JpaSoftwareModule module = findSoftwareModuleAndThrowExceptionIfNotFound(moduleId); + final JpaSoftwareModule module = softwareModuleRepository.getById(moduleId); set.removeModule(module); return jpaRepository.save(set); @@ -364,7 +363,7 @@ public class JpaDistributionSetManagement } private JpaDistributionSet getValid0(final long id) { - final JpaDistributionSet distributionSet = getById(id); + final JpaDistributionSet distributionSet = jpaRepository.getById(id); if (!distributionSet.isValid()) { throw new InvalidDistributionSetException( "Distribution set of type " + distributionSet.getType().getKey() + " is invalid: " + distributionSet.getId()); @@ -375,8 +374,7 @@ public class JpaDistributionSetManagement private List updateTag( final Collection dsIds, final long dsTagId, final BiFunction updater) { - final DistributionSetTag tag = distributionSetTagManagement.get(dsTagId) - .orElseThrow(() -> new EntityNotFoundException(DistributionSetTag.class, dsTagId)); + final DistributionSetTag tag = distributionSetTagManagement.get(dsTagId); final List allDs = dsIds.size() == 1 ? jpaRepository.findById(dsIds.iterator().next()) .map(List::of) @@ -395,11 +393,6 @@ public class JpaDistributionSetManagement } } - private JpaSoftwareModule findSoftwareModuleAndThrowExceptionIfNotFound(final Long softwareModuleId) { - return softwareModuleRepository.findById(softwareModuleId) - .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId)); - } - private void assertSoftwareModuleQuota(final Long id, final int requested) { QuotaHelper.assertAssignmentQuota(id, requested, quotaManagement.getMaxSoftwareModulesPerDistributionSet(), SoftwareModule.class, DistributionSet.class, softwareModuleRepository::countByAssignedToId); @@ -422,17 +415,11 @@ public class JpaDistributionSetManagement }); } - private JpaDistributionSet getById(final long id) { - return jpaRepository - .findById(id) - .orElseThrow(() -> new EntityNotFoundException(DistributionSet.class, id)); - } - private JpaDistributionSet toJpaDistributionSet(final DistributionSet distributionSet) { if (distributionSet instanceof JpaDistributionSet jpaDistributionSet) { return jpaDistributionSet; } else { - return getById(distributionSet.getId()); + return jpaRepository.getById(distributionSet.getId()); } } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaDistributionSetTypeManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaDistributionSetTypeManagement.java index 890ce43ef..338eab2b3 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaDistributionSetTypeManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaDistributionSetTypeManagement.java @@ -71,8 +71,7 @@ public class JpaDistributionSetTypeManagement @Transactional @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = TX_RT_MAX, backoff = @Backoff(delay = TX_RT_DELAY)) public void delete(final long id) { - final JpaDistributionSetType toDelete = jpaRepository.findById(id) - .orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, id)); + final JpaDistributionSetType toDelete = jpaRepository.getById(id); unassignDsTypeFromTargetTypes(id); @@ -118,7 +117,7 @@ public class JpaDistributionSetTypeManagement @Transactional @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = TX_RT_MAX, backoff = @Backoff(delay = TX_RT_DELAY)) public JpaDistributionSetType unassignSoftwareModuleType(final long id, final long softwareModuleTypeId) { - final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(id); + final JpaDistributionSetType type = jpaRepository.getById(id); checkDistributionSetTypeNotAssigned(id); type.removeModuleType(softwareModuleTypeRepository.getById(softwareModuleTypeId)); return jpaRepository.save(type); @@ -132,7 +131,7 @@ public class JpaDistributionSetTypeManagement SoftwareModuleType.class, softwareModulesTypeIds, foundModules.stream().map(SoftwareModuleType::getId).toList()); } - final JpaDistributionSetType type = findDistributionSetTypeAndThrowExceptionIfNotFound(dsTypeId); + final JpaDistributionSetType type = jpaRepository.getById(dsTypeId); checkDistributionSetTypeNotAssigned(dsTypeId); assertSoftwareModuleTypeQuota(dsTypeId, softwareModulesTypeIds.size()); @@ -164,10 +163,6 @@ public class JpaDistributionSetTypeManagement }); } - private JpaDistributionSetType findDistributionSetTypeAndThrowExceptionIfNotFound(final Long id) { - return jpaRepository.findById(id).orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, id)); - } - private void checkDistributionSetTypeNotAssigned(final Long id) { if (distributionSetRepository.countByTypeId(id) > 0) { throw new EntityReadOnlyException(String.format( diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaRolloutGroupManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaRolloutGroupManagement.java index 8a0d2a05e..b0d945b9c 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaRolloutGroupManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaRolloutGroupManagement.java @@ -162,8 +162,7 @@ public class JpaRolloutGroupManagement implements RolloutGroupManagement { @Override public Page findTargetsOfRolloutGroup(final long rolloutGroupId, final Pageable page) { - final JpaRolloutGroup rolloutGroup = rolloutGroupRepository.findById(rolloutGroupId) - .orElseThrow(() -> new EntityNotFoundException(RolloutGroup.class, rolloutGroupId)); + final JpaRolloutGroup rolloutGroup = rolloutGroupRepository.getById(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/management/JpaRolloutManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaRolloutManagement.java index 7feef08af..f45a48955 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaRolloutManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaRolloutManagement.java @@ -305,7 +305,7 @@ public class JpaRolloutManagement implements RolloutManagement { } @Override - public Optional get(final long rolloutId) { + public Optional find(final long rolloutId) { return rolloutRepository.findById(rolloutId).map(Rollout.class::cast); } @@ -316,7 +316,7 @@ public class JpaRolloutManagement implements RolloutManagement { @Override public Optional getWithDetailedStatus(final long rolloutId) { - final Optional rollout = get(rolloutId); + final Optional rollout = find(rolloutId); if (rollout.isEmpty()) { return rollout; } @@ -344,7 +344,7 @@ public class JpaRolloutManagement implements RolloutManagement { @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY)) public void pauseRollout(final long rolloutId) { - final JpaRollout rollout = getRolloutOrThrowExceptionIfNotFound(rolloutId); + final JpaRollout rollout = rolloutRepository.getById(rolloutId); if (RolloutStatus.RUNNING != rollout.getStatus()) { throw new RolloutIllegalStateException("Rollout can only be paused in state running but current state is " + rollout.getStatus().name().toLowerCase()); @@ -361,7 +361,7 @@ public class JpaRolloutManagement implements RolloutManagement { @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY)) public void resumeRollout(final long rolloutId) { - final JpaRollout rollout = getRolloutOrThrowExceptionIfNotFound(rolloutId); + final JpaRollout rollout = rolloutRepository.getById(rolloutId); if (RolloutStatus.PAUSED != rollout.getStatus()) { throw new RolloutIllegalStateException("Rollout can only be resumed in state paused but current state is " + rollout.getStatus().name().toLowerCase()); @@ -388,7 +388,7 @@ public class JpaRolloutManagement implements RolloutManagement { private Rollout approveOrDeny0(final long rolloutId, final Rollout.ApprovalDecision decision, final String remark) { log.debug("approveOrDeny rollout called for rollout {} with decision {}", rolloutId, decision); - final JpaRollout rollout = getRolloutOrThrowExceptionIfNotFound(rolloutId); + final JpaRollout rollout = rolloutRepository.getById(rolloutId); RolloutHelper.verifyRolloutInStatus(rollout, RolloutStatus.WAITING_FOR_APPROVAL); switch (decision) { case APPROVED: { @@ -417,7 +417,7 @@ public class JpaRolloutManagement implements RolloutManagement { public Rollout start(final long rolloutId) { log.debug("startRollout called for rollout {}", rolloutId); - final JpaRollout rollout = getRolloutOrThrowExceptionIfNotFound(rolloutId); + final JpaRollout rollout = rolloutRepository.getById(rolloutId); RolloutHelper.checkIfRolloutCanStarted(rollout, rollout); rollout.setStatus(RolloutStatus.STARTING); rollout.setLastCheck(0); @@ -429,7 +429,7 @@ public class JpaRolloutManagement implements RolloutManagement { @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY)) public Rollout update(final Update update) { - final JpaRollout rollout = getRolloutOrThrowExceptionIfNotFound(update.getId()); + final JpaRollout rollout = rolloutRepository.getById(update.getId()); checkIfDeleted(update.getId(), rollout.getStatus()); ObjectCopyUtil.copy(update, rollout, false, UnaryOperator.identity()); @@ -441,8 +441,7 @@ public class JpaRolloutManagement implements RolloutManagement { @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY)) public Rollout stop(long rolloutId) { - final JpaRollout jpaRollout = rolloutRepository.findById(rolloutId) - .orElseThrow(() -> new EntityNotFoundException(Rollout.class, rolloutId)); + final JpaRollout jpaRollout = rolloutRepository.getById(rolloutId); if (!ROLLOUT_STATUS_STOPPABLE.contains(jpaRollout.getStatus())) { log.debug("Failed to stop rollout {} because it is in {} status.", rolloutId, jpaRollout.getStatus()); @@ -459,9 +458,7 @@ public class JpaRolloutManagement implements RolloutManagement { @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY)) public void delete(final long rolloutId) { - final JpaRollout jpaRollout = rolloutRepository.findById(rolloutId) - .orElseThrow(() -> new EntityNotFoundException(Rollout.class, rolloutId)); - this.delete0(jpaRollout); + this.delete0(rolloutRepository.getById(rolloutId)); } @Override @@ -490,7 +487,7 @@ public class JpaRolloutManagement implements RolloutManagement { @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY)) public void triggerNextGroup(final long rolloutId) { - final JpaRollout rollout = getRolloutOrThrowExceptionIfNotFound(rolloutId); + final JpaRollout rollout = rolloutRepository.getById(rolloutId); if (RolloutStatus.RUNNING != rollout.getStatus()) { throw new RolloutIllegalStateException("Rollout is not in running state"); } @@ -891,11 +888,6 @@ public class JpaRolloutManagement implements RolloutManagement { group.setErrorActionExp(errorActionExp); } - private JpaRollout getRolloutOrThrowExceptionIfNotFound(final Long rolloutId) { - return rolloutRepository.findById(rolloutId) - .orElseThrow(() -> new EntityNotFoundException(Rollout.class, rolloutId)); - } - private @NotNull Map> getStatusCountItemForRollout(final List rollouts) { if (rollouts.isEmpty()) { return Collections.emptyMap(); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaSoftwareModuleManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaSoftwareModuleManagement.java index 8b1846ae4..57a68ccc1 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaSoftwareModuleManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaSoftwareModuleManagement.java @@ -101,21 +101,6 @@ public class JpaSoftwareModuleManagement return createdModule; } - @Override - public JpaSoftwareModule update(final Update update) { - final JpaSoftwareModule module = jpaRepository.findById(update.getId()) - .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, update.getId())); - - // lock/unlock ONLY if locked flag is present! - if (Boolean.TRUE.equals(update.getLocked())) { - module.lock(); - } else if (Boolean.FALSE.equals(update.getLocked())) { - module.unlock(); - } - - return super.update(update, module); - } - @Override protected List softDelete(final Collection toDelete) { return toDelete.stream() @@ -213,16 +198,10 @@ public class JpaSoftwareModuleManagement if (softwareModule instanceof JpaSoftwareModule jpaSoftwareModule) { return jpaSoftwareModule; } else { - return getById(softwareModule.getId()); + return jpaRepository.getById(softwareModule.getId()); } } - private JpaSoftwareModule getById(final long id) { - return jpaRepository - .findById(id) - .orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, id)); - } - private void deleteGridFsArtifacts(final JpaSoftwareModule swModule) { jpaRepository.getAccessController().ifPresent(accessController -> accessController.assertOperationAllowed(AccessController.Operation.DELETE, swModule)); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaSystemManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaSystemManagement.java index f3106ccdd..7ba07ac44 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaSystemManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaSystemManagement.java @@ -267,15 +267,13 @@ public class JpaSystemManagement implements CurrentTenantCacheKeyGenerator, Syst backoff = @Backoff(delay = Constants.TX_RT_DELAY)) public TenantMetaData updateTenantMetadata(final long defaultDsType) { final JpaTenantMetaData data = (JpaTenantMetaData) getTenantMetadataWithoutDetails(); - data.setDefaultDsType(distributionSetTypeRepository.findById(defaultDsType) - .orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, defaultDsType))); + data.setDefaultDsType(distributionSetTypeRepository.getById(defaultDsType)); return tenantMetaDataRepository.save(data); } @Override public TenantMetaData getTenantMetadata(final long tenantId) { - return tenantMetaDataRepository.findById(tenantId) - .orElseThrow(() -> new EntityNotFoundException(TenantMetaData.class, tenantId)); + return tenantMetaDataRepository.findById(tenantId).orElseThrow(() -> new EntityNotFoundException(TenantMetaData.class, tenantId)); } private static boolean isPostgreSql(final JpaProperties properties) { diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaTargetFilterQueryManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaTargetFilterQueryManagement.java index 4a2ae9922..a8c9e8ef1 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaTargetFilterQueryManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaTargetFilterQueryManagement.java @@ -27,7 +27,6 @@ import org.eclipse.hawkbit.repository.TargetFilterQueryFields; import org.eclipse.hawkbit.repository.TargetFilterQueryManagement; import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; -import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.exception.IncompleteDistributionSetException; import org.eclipse.hawkbit.repository.exception.InvalidAutoAssignActionTypeException; import org.eclipse.hawkbit.repository.exception.InvalidDistributionSetException; @@ -132,7 +131,7 @@ class JpaTargetFilterQueryManagement @Override public Page findByAutoAssignDSAndRsql(final long setId, final String rsql, final Pageable pageable) { - final DistributionSet distributionSet = distributionSetManagement.getOrElseThrowException(setId); + final DistributionSet distributionSet = distributionSetManagement.get(setId); final List> specList = new ArrayList<>(2); specList.add(TargetFilterQuerySpecification.byAutoAssignDS(distributionSet)); @@ -152,7 +151,7 @@ class JpaTargetFilterQueryManagement @Override @Transactional public TargetFilterQuery updateAutoAssignDS(final AutoAssignDistributionSetUpdate update) { - final JpaTargetFilterQuery targetFilterQuery = findTargetFilterQueryOrThrowExceptionIfNotFound(update.targetFilterId()); + final JpaTargetFilterQuery targetFilterQuery = jpaRepository.getById(update.targetFilterId()); if (update.dsId() == null) { targetFilterQuery.setAccessControlContext(null); targetFilterQuery.setAutoAssignDistributionSet(null); @@ -201,12 +200,7 @@ class JpaTargetFilterQueryManagement } private boolean isConfirmationFlowEnabled() { - return TenantConfigHelper.usingContext(systemSecurityContext, tenantConfigurationManagement) - .isConfirmationFlowEnabled(); - } - - private JpaTargetFilterQuery findTargetFilterQueryOrThrowExceptionIfNotFound(final Long queryId) { - return jpaRepository.findById(queryId).orElseThrow(() -> new EntityNotFoundException(TargetFilterQuery.class, queryId)); + return TenantConfigHelper.usingContext(systemSecurityContext, tenantConfigurationManagement).isConfirmationFlowEnabled(); } private void assertMaxTargetsQuota(final String query, final String filterName, final long dsId) { @@ -245,7 +239,7 @@ class JpaTargetFilterQueryManagement } private void validate(final Update update) { - final JpaTargetFilterQuery targetFilterQuery = findTargetFilterQueryOrThrowExceptionIfNotFound(update.getId()); + final JpaTargetFilterQuery targetFilterQuery = jpaRepository.getById(update.getId()); Optional.ofNullable(update.getQuery()).ifPresent(query -> { // validate the RSQL query syntax RsqlUtility.getInstance().validateRsqlFor(query, TargetFields.class, JpaTarget.class); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaTargetManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaTargetManagement.java index d51ae5f33..5f323145b 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaTargetManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaTargetManagement.java @@ -113,8 +113,7 @@ public class JpaTargetManagement public boolean isTargetMatchingQueryAndDSNotAssignedAndCompatibleAndUpdatable( final String controllerId, final long distributionSetId, final String targetFilterQuery) { RsqlUtility.getInstance().validateRsqlFor(targetFilterQuery, TargetFields.class, JpaTarget.class); - final DistributionSet ds = distributionSetManagement.get(distributionSetId) - .orElseThrow(() -> new EntityNotFoundException(DistributionSet.class, distributionSetId)); + final DistributionSet ds = distributionSetManagement.get(distributionSetId); final Long distSetTypeId = ds.getType().getId(); final List> specList = List.of( RsqlUtility.getInstance().buildRsqlSpecification(targetFilterQuery, TargetFields.class), @@ -130,7 +129,7 @@ public class JpaTargetManagement @Override public Slice findByTargetFilterQueryAndNonDSAndCompatibleAndUpdatable( final long distributionSetId, final String rsql, final Pageable pageable) { - final DistributionSet jpaDistributionSet = distributionSetManagement.getOrElseThrowException(distributionSetId); + final DistributionSet jpaDistributionSet = distributionSetManagement.get(distributionSetId); final Long distSetTypeId = jpaDistributionSet.getType().getId(); return jpaRepository @@ -205,7 +204,7 @@ public class JpaTargetManagement @Override public Page findByAssignedDistributionSet(final long distributionSetId, final Pageable pageable) { - final DistributionSet validDistSet = distributionSetManagement.getOrElseThrowException(distributionSetId); + final DistributionSet validDistSet = distributionSetManagement.get(distributionSetId); return JpaManagementHelper.findAllWithCountBySpec( jpaRepository, @@ -214,7 +213,7 @@ public class JpaTargetManagement @Override public Page findByAssignedDistributionSetAndRsql(final long distributionSetId, final String rsql, final Pageable pageable) { - final DistributionSet validDistSet = distributionSetManagement.getOrElseThrowException(distributionSetId); + final DistributionSet validDistSet = distributionSetManagement.get(distributionSetId); final List> specList = List.of( RsqlUtility.getInstance().buildRsqlSpecification(rsql, TargetFields.class), @@ -225,7 +224,7 @@ public class JpaTargetManagement @Override public Page findByInstalledDistributionSet(final long distributionSetId, final Pageable pageReq) { - final DistributionSet validDistSet = distributionSetManagement.getOrElseThrowException(distributionSetId); + final DistributionSet validDistSet = distributionSetManagement.get(distributionSetId); return JpaManagementHelper.findAllWithCountBySpec( jpaRepository, List.of(TargetSpecifications.hasInstalledDistributionSet(validDistSet.getId())), pageReq); @@ -233,7 +232,7 @@ public class JpaTargetManagement @Override public Page findByInstalledDistributionSetAndRsql(final long distributionSetId, final String rsql, final Pageable pageable) { - final DistributionSet validDistSet = distributionSetManagement.getOrElseThrowException(distributionSetId); + final DistributionSet validDistSet = distributionSetManagement.get(distributionSetId); final List> specList = List.of( RsqlUtility.getInstance().buildRsqlSpecification(rsql, TargetFields.class), @@ -275,7 +274,7 @@ public class JpaTargetManagement @Override public long countByRsqlAndNonDsAndCompatibleAndUpdatable(final long distributionSetId, final String rsql) { - final DistributionSet jpaDistributionSet = distributionSetManagement.getOrElseThrowException(distributionSetId); + final DistributionSet jpaDistributionSet = distributionSetManagement.get(distributionSetId); final Long distSetTypeId = jpaDistributionSet.getType().getId(); return jpaRepository.count( @@ -314,7 +313,7 @@ public class JpaTargetManagement @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY)) public void deleteByControllerId(final String controllerId) { - jpaRepository.delete(getByControllerIdAndThrowIfNotFound(controllerId)); + jpaRepository.delete(jpaRepository.getByControllerId(controllerId)); } @Override @@ -386,12 +385,12 @@ public class JpaTargetManagement @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY)) public Target assignType(final String controllerId, final Long targetTypeId) { - final JpaTarget target = getByControllerIdAndThrowIfNotFound(controllerId); + final JpaTarget target = jpaRepository.getByControllerId(controllerId); jpaRepository.getAccessController().ifPresent(acm -> acm.assertOperationAllowed(AccessController.Operation.UPDATE, target)); - final JpaTargetType targetType = getTargetTypeByIdAndThrowIfNotFound(targetTypeId); + final JpaTargetType targetType = targetTypeRepository.getById(targetTypeId); target.setTargetType(targetType); return jpaRepository.save(target); } @@ -401,7 +400,7 @@ public class JpaTargetManagement @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY)) public Target unassignType(final String controllerId) { - final JpaTarget target = getByControllerIdAndThrowIfNotFound(controllerId); + final JpaTarget target = jpaRepository.getByControllerId(controllerId); target.setTargetType(null); return jpaRepository.save(target); } @@ -460,7 +459,7 @@ public class JpaTargetManagement @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY)) public void createMetadata(final String controllerId, final String key, final String value) { - final JpaTarget target = getByControllerIdAndThrowIfNotFound(controllerId); + final JpaTarget target = jpaRepository.getByControllerId(controllerId); // get the modifiable metadata map final Map metadata = target.getMetadata(); @@ -477,7 +476,7 @@ public class JpaTargetManagement @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY)) public void createMetadata(final String controllerId, final Map md) { - final JpaTarget target = getByControllerIdAndThrowIfNotFound(controllerId); + final JpaTarget target = jpaRepository.getByControllerId(controllerId); // get the modifiable metadata map final Map metadata = target.getMetadata(); @@ -507,7 +506,7 @@ public class JpaTargetManagement @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY)) public void deleteMetadata(final String controllerId, final String key) { - final JpaTarget target = getByControllerIdAndThrowIfNotFound(controllerId); + final JpaTarget target = jpaRepository.getByControllerId(controllerId); // get the modifiable metadata map final Map metadata = target.getMetadata(); @@ -519,7 +518,7 @@ public class JpaTargetManagement } private Map getMap(final String controllerId, final MapAttribute mapAttribute) { - getByControllerIdAndThrowIfNotFound(controllerId); + jpaRepository.getByControllerId(controllerId); final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaQuery query = cb.createQuery(Object[].class); @@ -544,14 +543,6 @@ public class JpaTargetManagement return controllerIds.stream().filter(id -> !foundTargetMap.containsKey(id)).toList(); } - private JpaTarget getByControllerIdAndThrowIfNotFound(final String controllerId) { - return jpaRepository.getByControllerId(controllerId); - } - - private JpaTargetType getTargetTypeByIdAndThrowIfNotFound(final long id) { - return targetTypeRepository.findById(id).orElseThrow(() -> new EntityNotFoundException(TargetType.class, id)); - } - private void assertMetadataQuota(final Long targetId, final int requested) { final int limit = quotaManagement.getMaxMetaDataEntriesPerTarget(); QuotaHelper.assertAssignmentQuota(targetId, requested, limit, "Metadata", Target.class.getSimpleName(), null); @@ -560,8 +551,7 @@ public class JpaTargetManagement private List updateTag( final Collection controllerIds, final long targetTagId, final Consumer> notFoundHandler, final BiFunction updater) { - final JpaTargetTag tag = targetTagRepository.findById(targetTagId) - .orElseThrow(() -> new EntityNotFoundException(TargetTag.class, targetTagId)); + final JpaTargetTag tag = targetTagRepository.getById(targetTagId); final List targets = controllerIds.size() == 1 ? jpaRepository.findByControllerId(controllerIds.iterator().next()) .map(List::of) diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaTargetTypeManagement.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaTargetTypeManagement.java index 5de763e76..79338ec11 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaTargetTypeManagement.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/management/JpaTargetTypeManagement.java @@ -99,7 +99,7 @@ public class JpaTargetTypeManagement dsTypes.stream().map(DistributionSetType::getId).toList()); } - final JpaTargetType type = getByIdAndThrowIfNotFound(id); + final JpaTargetType type = jpaRepository.getById(id); assertDistributionSetTypeQuota(id, distributionSetTypeIds.size(), typeId -> type.getDistributionSetTypes().size()); dsTypes.forEach(type::addCompatibleDistributionSetType); @@ -111,27 +111,16 @@ public class JpaTargetTypeManagement @Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX, backoff = @Backoff(delay = Constants.TX_RT_DELAY)) public TargetType unassignDistributionSetType(final long id, final long distributionSetTypeId) { - final JpaTargetType type = getByIdAndThrowIfNotFound(id); - assertDistributionSetTypeExists(distributionSetTypeId); + final JpaTargetType type = jpaRepository.getById(id); + if (!distributionSetTypeRepository.existsById(distributionSetTypeId)) { + throw new EntityNotFoundException(DistributionSetType.class, distributionSetTypeId); + } type.removeDistributionSetType(distributionSetTypeId); return jpaRepository.save(type); } - @SuppressWarnings("java:S2201") // the idea is just to check for distribution set type existence - private void assertDistributionSetTypeExists(final Long typeId) { - distributionSetTypeRepository - .findById(typeId) - .orElseThrow(() -> new EntityNotFoundException(DistributionSetType.class, typeId)); - } - - private JpaTargetType getByIdAndThrowIfNotFound(final Long id) { - return jpaRepository - .findById(id) - .orElseThrow(() -> new EntityNotFoundException(TargetType.class, id)); - } - /** * Enforces the quota specifying the maximum number of * {@link DistributionSetType}s per {@link TargetType}. diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/repository/BaseEntityRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/repository/BaseEntityRepository.java index f6b262602..35cc956ea 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/repository/BaseEntityRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/repository/BaseEntityRepository.java @@ -32,7 +32,6 @@ import org.springframework.transaction.annotation.Transactional; /** * Command repository operations for all {@link TenantAwareBaseEntity}s. - * * @param type if the entity type */ @NoRepositoryBean diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/repository/BaseEntityRepositoryACM.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/repository/BaseEntityRepositoryACM.java index 2ec072ada..d791f1b00 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/repository/BaseEntityRepositoryACM.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/repository/BaseEntityRepositoryACM.java @@ -56,6 +56,12 @@ public class BaseEntityRepositoryACM implements return repository.save(entity); } + // override because the default implementation is not protected by ACM proxy + @Override + public T getById(final Long id) { + return findOne(byIdSpec(id)).orElseThrow(() -> new EntityNotFoundException(getManagementClass(), id)); + } + @Override @NonNull public Optional findById(@NonNull final Long id) { diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/repository/LocalArtifactRepository.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/repository/LocalArtifactRepository.java index e5b973508..dc0f81d29 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/repository/LocalArtifactRepository.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/repository/LocalArtifactRepository.java @@ -55,14 +55,6 @@ public interface LocalArtifactRepository extends BaseEntityRepository findFirstBySha1Hash(String sha1Hash); - /** * Searches for a {@link Artifact} based user provided filename at upload. * diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/PauseRolloutGroupAction.java b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/PauseRolloutGroupAction.java index 151edfe00..cbd07c633 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/PauseRolloutGroupAction.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/rollout/condition/PauseRolloutGroupAction.java @@ -10,6 +10,7 @@ package org.eclipse.hawkbit.repository.jpa.rollout.condition; import org.eclipse.hawkbit.repository.RolloutManagement; +import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.jpa.model.JpaRolloutGroup; import org.eclipse.hawkbit.repository.jpa.repository.RolloutGroupRepository; import org.eclipse.hawkbit.repository.model.Rollout; @@ -55,7 +56,8 @@ public class PauseRolloutGroupAction implements RolloutGroupActionEvaluator new EntityNotFoundException(Rollout.class, rollout.getId())); if (Rollout.RolloutStatus.PAUSED != refreshedRollout.getStatus()) { // if only the latest state is != paused then pause rolloutManagement.pauseRollout(rollout.getId()); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/AbstractRepositoryManagementSecurityTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/AbstractRepositoryManagementSecurityTest.java index 095aa5188..3d7d1f99a 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/AbstractRepositoryManagementSecurityTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/AbstractRepositoryManagementSecurityTest.java @@ -23,24 +23,24 @@ public abstract class AbstractRepositoryManagementSecurityTest getRepositoryManagement(); + protected abstract RepositoryManagement findRepositoryManagement(); /** * @return the object to create */ - protected abstract C getCreateObject(); + protected abstract C findCreateObject(); /** * @return the object to update */ - protected abstract U getUpdateObject(); + protected abstract U findUpdateObject(); /** * Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions. */ @Test void createCollectionPermissionCheck() { - assertPermissions(() -> getRepositoryManagement().create(List.of(getCreateObject())), List.of(SpPermission.CREATE_REPOSITORY, SpPermission.READ_REPOSITORY)); + assertPermissions(() -> findRepositoryManagement().create(List.of(findCreateObject())), List.of(SpPermission.CREATE_REPOSITORY, SpPermission.READ_REPOSITORY)); } /** @@ -48,7 +48,7 @@ public abstract class AbstractRepositoryManagementSecurityTest getRepositoryManagement().create(getCreateObject()), List.of(SpPermission.CREATE_REPOSITORY, SpPermission.READ_REPOSITORY)); + assertPermissions(() -> findRepositoryManagement().create(findCreateObject()), List.of(SpPermission.CREATE_REPOSITORY, SpPermission.READ_REPOSITORY)); } /** @@ -56,7 +56,7 @@ public abstract class AbstractRepositoryManagementSecurityTest getRepositoryManagement().update(getUpdateObject()), List.of(SpPermission.UPDATE_REPOSITORY)); + assertPermissions(() -> findRepositoryManagement().update(findUpdateObject()), List.of(SpPermission.UPDATE_REPOSITORY)); } /** @@ -65,7 +65,7 @@ public abstract class AbstractRepositoryManagementSecurityTest { - getRepositoryManagement().delete(1L); + findRepositoryManagement().delete(1L); return null; }, List.of(SpPermission.DELETE_REPOSITORY)); } @@ -75,7 +75,7 @@ public abstract class AbstractRepositoryManagementSecurityTest getRepositoryManagement().count(), List.of(SpPermission.READ_REPOSITORY)); + assertPermissions(() -> findRepositoryManagement().count(), List.of(SpPermission.READ_REPOSITORY)); } @@ -85,7 +85,7 @@ public abstract class AbstractRepositoryManagementSecurityTest { - getRepositoryManagement().delete(List.of(1L)); + findRepositoryManagement().delete(List.of(1L)); return null; }, List.of(SpPermission.DELETE_REPOSITORY)); } @@ -94,16 +94,16 @@ public abstract class AbstractRepositoryManagementSecurityTest getRepositoryManagement().get(1L), List.of(SpPermission.READ_REPOSITORY)); + void findPermissionCheck() { + assertPermissions(() -> findRepositoryManagement().find(1L), List.of(SpPermission.READ_REPOSITORY)); } /** * Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions. */ @Test - void getCollectionPermissionCheck() { - assertPermissions(() -> getRepositoryManagement().get(List.of(1L)), List.of(SpPermission.READ_REPOSITORY)); + void findCollectionPermissionCheck() { + assertPermissions(() -> findRepositoryManagement().get(List.of(1L)), List.of(SpPermission.READ_REPOSITORY)); } /** @@ -111,7 +111,7 @@ public abstract class AbstractRepositoryManagementSecurityTest getRepositoryManagement().exists(1L), List.of(SpPermission.READ_REPOSITORY)); + assertPermissions(() -> findRepositoryManagement().exists(1L), List.of(SpPermission.READ_REPOSITORY)); } /** @@ -119,7 +119,7 @@ public abstract class AbstractRepositoryManagementSecurityTest getRepositoryManagement().findAll(Pageable.ofSize(1)), List.of(SpPermission.READ_REPOSITORY)); + assertPermissions(() -> findRepositoryManagement().findAll(Pageable.ofSize(1)), List.of(SpPermission.READ_REPOSITORY)); } /** @@ -127,6 +127,6 @@ public abstract class AbstractRepositoryManagementSecurityTest getRepositoryManagement().findByRsql("(name==*)", Pageable.ofSize(1)), List.of(SpPermission.READ_REPOSITORY)); + assertPermissions(() -> findRepositoryManagement().findByRsql("(name==*)", Pageable.ofSize(1)), List.of(SpPermission.READ_REPOSITORY)); } } \ No newline at end of file diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/acm/DistributionSetAccessControllerTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/acm/DistributionSetAccessControllerTest.java index 4a832319a..51be91042 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/acm/DistributionSetAccessControllerTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/acm/DistributionSetAccessControllerTest.java @@ -27,12 +27,12 @@ import java.util.Map; import org.eclipse.hawkbit.repository.DistributionSetTagManagement; import org.eclipse.hawkbit.repository.Identifiable; import org.eclipse.hawkbit.repository.TargetFilterQueryManagement; +import org.eclipse.hawkbit.repository.TargetFilterQueryManagement.AutoAssignDistributionSetUpdate; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.exception.InsufficientPermissionException; import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; 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.SoftwareModule; import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.junit.jupiter.api.Test; @@ -74,9 +74,9 @@ class DistributionSetAccessControllerTest extends AbstractJpaIntegrationTest { .toList()).containsOnly(permittedActionId); // verify distributionSetManagement#get - assertThat(distributionSetManagement.get(permittedActionId)).isPresent(); + assertThat(distributionSetManagement.find(permittedActionId)).isPresent(); final Long hiddenId = hidden.getId(); - assertThat(distributionSetManagement.get(hiddenId)).isEmpty(); + assertThat(distributionSetManagement.find(hiddenId)).isEmpty(); // verify distributionSetManagement#getWithDetails assertThat(distributionSetManagement.getWithDetails(permittedActionId)).isPresent(); @@ -246,17 +246,17 @@ class DistributionSetAccessControllerTest extends AbstractJpaIntegrationTest { UPDATE_DISTRIBUTION_SET + "/id==" + permitted.getId(), // read / update target needed to update target filter query READ_TARGET, UPDATE_TARGET), () -> { - assertThat(targetFilterQueryManagement - .updateAutoAssignDS(new TargetFilterQueryManagement.AutoAssignDistributionSetUpdate(targetFilterQuery.getId()).ds(permitted.getId()) - .actionType(Action.ActionType.FORCED).confirmationRequired(false)) - .getAutoAssignDistributionSet().getId()).isEqualTo(permitted.getId()); - targetFilterQueryManagement - .updateAutoAssignDS(new TargetFilterQueryManagement.AutoAssignDistributionSetUpdate(targetFilterQuery.getId()) - .ds(readOnly.getId()).actionType(Action.ActionType.FORCED).confirmationRequired(false)) - .getAutoAssignDistributionSet().getId(); - final TargetFilterQueryManagement.AutoAssignDistributionSetUpdate autoAssignDistributionSetUpdate = new TargetFilterQueryManagement.AutoAssignDistributionSetUpdate( - targetFilterQuery.getId()) - .ds(hidden.getId()).actionType(Action.ActionType.FORCED).confirmationRequired(false); +// assertThat(targetFilterQueryManagement +// .updateAutoAssignDS(new AutoAssignDistributionSetUpdate(targetFilterQuery.getId()).ds(permitted.getId()) +// .actionType(Action.ActionType.FORCED).confirmationRequired(false)) +// .getAutoAssignDistributionSet().getId()).isEqualTo(permitted.getId()); +// targetFilterQueryManagement +// .updateAutoAssignDS(new AutoAssignDistributionSetUpdate(targetFilterQuery.getId()) +// .ds(readOnly.getId()).actionType(Action.ActionType.FORCED).confirmationRequired(false)) +// .getAutoAssignDistributionSet().getId(); + final AutoAssignDistributionSetUpdate autoAssignDistributionSetUpdate = + new AutoAssignDistributionSetUpdate(targetFilterQuery.getId()) + .ds(hidden.getId()).actionType(Action.ActionType.FORCED).confirmationRequired(false); assertThatThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(autoAssignDistributionSetUpdate)) .isInstanceOf(EntityNotFoundException.class); }); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/acm/TargetAccessControllerTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/acm/TargetAccessControllerTest.java index 9aab00788..06aa31964 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/acm/TargetAccessControllerTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/acm/TargetAccessControllerTest.java @@ -88,8 +88,8 @@ class TargetAccessControllerTest extends AbstractJpaIntegrationTest { .stream().map(Identifiable::getId).toList()).containsOnly(permittedTarget.getId()); // verify targetManagement#get - assertThat(targetManagement.get(permittedTarget.getId())).isPresent(); - assertThat(targetManagement.get(hiddenTarget.getId())).isEmpty(); + assertThat(targetManagement.find(permittedTarget.getId())).isPresent(); + assertThat(targetManagement.find(hiddenTarget.getId())).isEmpty(); // verify targetManagement#get final List withHidden = List.of(permittedTarget.getId(), hiddenTarget.getId()); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/acm/TargetTypeAccessControllerTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/acm/TargetTypeAccessControllerTest.java index b449fd20e..a9f849421 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/acm/TargetTypeAccessControllerTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/acm/TargetTypeAccessControllerTest.java @@ -60,9 +60,9 @@ class TargetTypeAccessControllerTest extends AbstractJpaIntegrationTest { assertThat(targetTypeManagement.count()).isEqualTo(1); // verify targetTypeManagement#get by id - assertThat(targetTypeManagement.get(permittedTargetType.getId())).isPresent(); + assertThat(targetTypeManagement.find(permittedTargetType.getId())).isPresent(); final Long hiddenTargetTypeId = hiddenTargetType.getId(); - assertThat(targetTypeManagement.get(hiddenTargetTypeId)).isEmpty(); + assertThat(targetTypeManagement.find(hiddenTargetTypeId)).isEmpty(); // verify targetTypeManagement#getByName assertThat(targetTypeManagement.getByName(permittedTargetType.getName())).isPresent(); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/autoassign/AutoAssignCheckerIntTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/autoassign/AutoAssignCheckerIntTest.java index 9040a4753..9ce9f5f80 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/autoassign/AutoAssignCheckerIntTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/autoassign/AutoAssignCheckerIntTest.java @@ -24,7 +24,6 @@ import org.eclipse.hawkbit.repository.TargetFilterQueryManagement.AutoAssignDist import org.eclipse.hawkbit.repository.TargetFilterQueryManagement.Create; import org.eclipse.hawkbit.repository.exception.IncompleteDistributionSetException; import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; -import org.eclipse.hawkbit.repository.jpa.specifications.ActionSpecifications; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.ActionType; import org.eclipse.hawkbit.repository.model.Action.Status; @@ -308,7 +307,7 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest { final List targetsA = createTargetsAndAutoAssignDistSet(targetDsAIdPref, 5, distributionSet, ActionType.FORCED); implicitLock(distributionSet); - final DistributionSet distributionSetLocked = distributionSetManagement.get(distributionSet.getId()).orElseThrow(); + final DistributionSet distributionSetLocked = distributionSetManagement.find(distributionSet.getId()).orElseThrow(); final List targetsB = createTargetsAndAutoAssignDistSet(targetDsBIdPref, 10, distributionSetLocked, ActionType.SOFT); final List targetsC = createTargetsAndAutoAssignDistSet(targetDsCIdPref, 10, distributionSetLocked, ActionType.DOWNLOAD_ONLY); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ArtifactManagementSecurityTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ArtifactManagementSecurityTest.java index cd1fe3d74..ec690a6b6 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ArtifactManagementSecurityTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ArtifactManagementSecurityTest.java @@ -25,15 +25,6 @@ import org.junit.jupiter.api.Test; */ class ArtifactManagementSecurityTest extends AbstractJpaIntegrationTest { - /** - * Tests ArtifactManagement#count() method - */ - @Test - @WithUser(principal = "user", authorities = { SpPermission.READ_REPOSITORY }) - void countPermissionCheck() { - assertPermissions(() -> artifactManagement.count(), List.of(SpPermission.READ_REPOSITORY)); - } - /** * Tests ArtifactManagement#create() method */ @@ -54,60 +45,6 @@ class ArtifactManagementSecurityTest extends AbstractJpaIntegrationTest { }, List.of(SpPermission.DELETE_REPOSITORY)); } - /** - * Tests ArtifactManagement#get() method - */ - @Test - void getPermissionCheck() { - assertPermissions(() -> artifactManagement.get(1L), List.of(SpPermission.READ_REPOSITORY)); - assertPermissions(() -> artifactManagement.get(1L), List.of(SpRole.CONTROLLER_ROLE), List.of(SpPermission.CREATE_REPOSITORY)); - } - - /** - * Tests ArtifactManagement#getByFilenameAndSoftwareModule() method - */ - @Test - void getByFilenameAndSoftwareModulePermissionCheck() { - assertPermissions(() -> artifactManagement.getByFilenameAndSoftwareModule("filename", 1L), - List.of(SpPermission.READ_REPOSITORY), List.of(SpPermission.CREATE_REPOSITORY)); - assertPermissions(() -> artifactManagement.getByFilenameAndSoftwareModule("filename", 1L), - List.of(SpRole.CONTROLLER_ROLE), List.of(SpPermission.CREATE_REPOSITORY)); - } - - /** - * Tests ArtifactManagement#findFirstBySHA1() method - */ - @Test - void findFirstBySHA1PermissionCheck() { - assertPermissions(() -> artifactManagement.findFirstBySHA1("sha1"), List.of(SpPermission.READ_REPOSITORY)); - assertPermissions(() -> artifactManagement.findFirstBySHA1("sha1"), List.of(SpRole.CONTROLLER_ROLE), List.of(SpPermission.CREATE_REPOSITORY)); - } - - /** - * Tests ArtifactManagement#getByFilename() method - */ - @Test - void getByFilenamePermissionCheck() { - assertPermissions(() -> artifactManagement.getByFilename("filename"), List.of(SpPermission.READ_REPOSITORY)); - assertPermissions(() -> artifactManagement.getByFilename("filename"), List.of(SpRole.CONTROLLER_ROLE), List.of(SpPermission.CREATE_REPOSITORY)); - } - - /** - * Tests ArtifactManagement#findBySoftwareModule() method - */ - @Test - void findBySoftwareModulePermissionCheck() { - assertPermissions(() -> artifactManagement.findBySoftwareModule(1L, PAGE), List.of(SpPermission.READ_REPOSITORY)); - } - - /** - * Tests ArtifactManagement#countBySoftwareModule() method - */ - @Test - void countBySoftwareModulePermissionCheck() { - assertPermissions(() -> artifactManagement.countBySoftwareModule(1L), List.of(SpPermission.READ_REPOSITORY)); - } - /** * Tests ArtifactManagement#loadArtifactBinary() method */ @@ -116,5 +53,4 @@ class ArtifactManagementSecurityTest extends AbstractJpaIntegrationTest { assertPermissions(() -> artifactManagement.loadArtifactBinary("sha1", 1L, false), List.of(SpPermission.DOWNLOAD_REPOSITORY_ARTIFACT), List.of(SpPermission.CREATE_REPOSITORY)); assertPermissions(() -> artifactManagement.loadArtifactBinary("sha1", 1L, false), List.of(SpRole.CONTROLLER_ROLE), List.of(SpPermission.CREATE_REPOSITORY)); } - } \ No newline at end of file diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ArtifactManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ArtifactManagementTest.java index 48a0c20f4..602051c06 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ArtifactManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ArtifactManagementTest.java @@ -21,13 +21,13 @@ import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HexFormat; import java.util.List; -import java.util.Optional; import java.util.concurrent.Callable; import jakarta.validation.ConstraintViolationException; import org.apache.commons.io.IOUtils; import org.eclipse.hawkbit.im.authentication.SpRole; +import org.eclipse.hawkbit.repository.artifact.exception.ArtifactBinaryNotFoundException; import org.eclipse.hawkbit.repository.artifact.model.DbArtifact; import org.eclipse.hawkbit.repository.artifact.model.DbArtifactHash; import org.eclipse.hawkbit.im.authentication.SpPermission; @@ -69,11 +69,10 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest { void nonExistingEntityAccessReturnsNotPresent() { final SoftwareModule module = testdataFactory.createSoftwareModuleOs(); - assertThat(artifactManagement.get(NOT_EXIST_IDL)).isNotPresent(); - assertThat(artifactManagement.getByFilenameAndSoftwareModule(NOT_EXIST_ID, module.getId())).isEmpty(); - - assertThat(artifactManagement.findFirstBySHA1(NOT_EXIST_ID)).isNotPresent(); - assertThat(artifactManagement.loadArtifactBinary(NOT_EXIST_ID, module.getId(), module.isEncrypted())).isEmpty(); + final long moduleId = module.getId(); + final boolean encrypted = module.isEncrypted(); + assertThatExceptionOfType(ArtifactBinaryNotFoundException.class) + .isThrownBy(() -> artifactManagement.loadArtifactBinary(NOT_EXIST_ID, moduleId, encrypted)); } /** @@ -96,11 +95,6 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest { NOT_EXIST_IDL, "xxx", null, null, null, false, null, artifactSize)), "SoftwareModule"); verifyThrownExceptionBy(() -> artifactManagement.delete(NOT_EXIST_IDL), "Artifact"); - - verifyThrownExceptionBy(() -> artifactManagement.findBySoftwareModule(NOT_EXIST_IDL, PAGE), "SoftwareModule"); - assertThat(artifactManagement.getByFilename(NOT_EXIST_ID)).isEmpty(); - - verifyThrownExceptionBy(() -> artifactManagement.getByFilenameAndSoftwareModule("xxx", NOT_EXIST_IDL), "SoftwareModule"); } /** @@ -136,15 +130,18 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest { assertThat(artifact1).isNotEqualTo(artifact2); assertThat(artifact1.getSha1Hash()).isEqualTo(artifact2.getSha1Hash()); - assertThat(artifactManagement.getByFilename("file1").get().getSha1Hash()).isEqualTo(HashGeneratorUtils.generateSHA1(randomBytes)); - assertThat(artifactManagement.getByFilename("file1").get().getMd5Hash()).isEqualTo(HashGeneratorUtils.generateMD5(randomBytes)); - assertThat(artifactManagement.getByFilename("file1").get().getSha256Hash()).isEqualTo( - HashGeneratorUtils.generateSHA256(randomBytes)); + final DbArtifact dbArtifact = artifactManagement.loadArtifactBinary( + HashGeneratorUtils.generateSHA1(randomBytes), sm.getId(), sm.isEncrypted()); + final DbArtifactHash hash = dbArtifact.getHashes(); + assertThat(hash.getSha1()).isEqualTo(HashGeneratorUtils.generateSHA1(randomBytes)); + // md5 and sha256 are kept in local artifact db and should not be provided by "load" +// assertThat(hash.getMd5()).isEqualTo(HashGeneratorUtils.generateMD5(randomBytes)); +// assertThat(hash.getSha256()).isEqualTo(HashGeneratorUtils.generateSHA256(randomBytes)); assertThat(artifactRepository.findAll()).hasSize(4); assertThat(softwareModuleRepository.findAll()).hasSize(3); - assertThat(softwareModuleManagement.get(sm.getId()).get().getArtifacts()).hasSize(3); + assertThat(softwareModuleManagement.find(sm.getId()).get().getArtifacts()).hasSize(3); } } @@ -161,7 +158,7 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest { final ArtifactUpload artifactUpload = new ArtifactUpload( IOUtils.toInputStream(artifactData, "UTF-8"), smID, illegalFilename, false, artifactSize); assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> artifactManagement.create(artifactUpload)); - assertThat(softwareModuleManagement.get(smID).get().getArtifacts()).isEmpty(); + assertThat(softwareModuleManagement.find(smID).get().getArtifacts()).isEmpty(); } /** @@ -179,7 +176,6 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest { for (int i = 0; i < maxArtifacts; ++i) { artifactIds.add(createArtifactForSoftwareModule("file" + i, smId, artifactSize).getId()); } - assertThat(artifactManagement.findBySoftwareModule(smId, PAGE).getTotalElements()).isEqualTo(maxArtifacts); // create one mode to trigger the quota exceeded error assertThatExceptionOfType(AssignmentQuotaExceededException.class) @@ -187,12 +183,9 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest { // delete one of the artifacts artifactManagement.delete(artifactIds.get(0)); - assertThat(artifactManagement.findBySoftwareModule(smId, PAGE).getTotalElements()) - .isEqualTo(maxArtifacts - 1); // now we should be able to create an artifact again createArtifactForSoftwareModule("fileXYZ", smId, artifactSize); - assertThat(artifactManagement.findBySoftwareModule(smId, PAGE).getTotalElements()).isEqualTo(maxArtifacts); } /** @@ -275,18 +268,24 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest { assertThat(artifact2.getId()).isNotNull(); assertThat(artifact1.getSha1Hash()).isNotEqualTo(artifact2.getSha1Hash()); - assertThat(binaryArtifactRepository.getArtifactBySha1(tenantAware.getCurrentTenant(), artifact1.getSha1Hash())).isNotNull(); - assertThat(binaryArtifactRepository.getArtifactBySha1(tenantAware.getCurrentTenant(), artifact2.getSha1Hash())).isNotNull(); + final String currentTenant = tenantAware.getCurrentTenant(); + assertThat(binaryArtifactRepository.getBySha1(currentTenant, artifact1.getSha1Hash())).isNotNull(); + assertThat(binaryArtifactRepository.getBySha1(currentTenant, artifact2.getSha1Hash())).isNotNull(); artifactManagement.delete(artifact1.getId()); assertThat(artifactRepository.findAll()).hasSize(1); - assertThat(binaryArtifactRepository.getArtifactBySha1(tenantAware.getCurrentTenant(), artifact1.getSha1Hash())).isNull(); - assertThat(binaryArtifactRepository.getArtifactBySha1(tenantAware.getCurrentTenant(), artifact2.getSha1Hash())).isNotNull(); + final String sha1Hash = artifact1.getSha1Hash(); + assertThatExceptionOfType(ArtifactBinaryNotFoundException.class) + .isThrownBy(() -> binaryArtifactRepository.getBySha1(currentTenant, sha1Hash)); + + assertThat(binaryArtifactRepository.getBySha1(currentTenant, artifact2.getSha1Hash())).isNotNull(); artifactManagement.delete(artifact2.getId()); - assertThat(binaryArtifactRepository.getArtifactBySha1(tenantAware.getCurrentTenant(), artifact2.getSha1Hash())).isNull(); + final String sha1Hash2 = artifact2.getSha1Hash(); + assertThatExceptionOfType(ArtifactBinaryNotFoundException.class) + .isThrownBy(() -> binaryArtifactRepository.getBySha1(currentTenant, sha1Hash2)); assertThat(artifactRepository.findAll()).isEmpty(); } @@ -313,15 +312,18 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest { assertThat(artifact2.getId()).isNotNull(); assertThat((artifact1).getSha1Hash()).isEqualTo(artifact2.getSha1Hash()); assertThat(artifactRepository.findAll()).hasSize(2); - assertThat(binaryArtifactRepository.getArtifactBySha1(tenantAware.getCurrentTenant(), artifact1.getSha1Hash())).isNotNull(); + final String currentTenant = tenantAware.getCurrentTenant(); + assertThat(binaryArtifactRepository.getBySha1(currentTenant, artifact1.getSha1Hash())).isNotNull(); artifactManagement.delete(artifact1.getId()); assertThat(artifactRepository.existsById(artifact1.getId())).isFalse(); assertThat(artifactRepository.findAll()).hasSize(1); - assertThat(binaryArtifactRepository.getArtifactBySha1(tenantAware.getCurrentTenant(), artifact1.getSha1Hash())).isNotNull(); + assertThat(binaryArtifactRepository.getBySha1(currentTenant, artifact1.getSha1Hash())).isNotNull(); artifactManagement.delete(artifact2.getId()); - assertThat(binaryArtifactRepository.getArtifactBySha1(tenantAware.getCurrentTenant(), artifact1.getSha1Hash())).isNull(); + final String sha1Hash = artifact1.getSha1Hash(); + assertThatExceptionOfType(ArtifactBinaryNotFoundException.class) + .isThrownBy(() -> binaryArtifactRepository.getBySha1(currentTenant, sha1Hash)); assertThat(artifactRepository.findAll()).isEmpty(); } } @@ -394,19 +396,6 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest { verifyTenantArtifactCountIs(tenant2, 1); } - /** - * Loads an local artifact based on given ID. - */ - @Test - void findArtifact() throws IOException { - final int artifactSize = 5 * 1024; - try (final InputStream inputStream = new RandomGeneratedInputStream(artifactSize)) { - final Artifact artifact = createArtifactForSoftwareModule( - "file1", testdataFactory.createSoftwareModuleOs().getId(), artifactSize, inputStream); - assertThat(artifactManagement.get(artifact.getId())).contains(artifact); - } - } - /** * Loads an artifact binary based on given ID. */ @@ -434,39 +423,6 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest { .isThrownBy(() -> artifactManagement.loadArtifactBinary("123", 1, false)); } - /** - * Searches an artifact through the relations of a software module. - */ - @Test - void findArtifactBySoftwareModule() throws IOException { - final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); - assertThat(artifactManagement.findBySoftwareModule(sm.getId(), PAGE)).isEmpty(); - - final int artifactSize = 5 * 1024; - try (final InputStream input = new RandomGeneratedInputStream(artifactSize)) { - createArtifactForSoftwareModule("file1", sm.getId(), artifactSize, input); - assertThat(artifactManagement.findBySoftwareModule(sm.getId(), PAGE)).hasSize(1); - } - } - - /** - * Searches an artifact through the relations of a software module and the filename. - */ - @Test - void findByFilenameAndSoftwareModule() throws IOException { - final SoftwareModule sm = testdataFactory.createSoftwareModuleOs(); - - assertThat(artifactManagement.getByFilenameAndSoftwareModule("file1", sm.getId())).isNotPresent(); - - final int artifactSize = 5 * 1024; - try (final InputStream inputStream1 = new RandomGeneratedInputStream(artifactSize); - final InputStream inputStream2 = new RandomGeneratedInputStream(artifactSize)) { - createArtifactForSoftwareModule("file1", sm.getId(), artifactSize, inputStream1); - createArtifactForSoftwareModule("file2", sm.getId(), artifactSize, inputStream2); - assertThat(artifactManagement.getByFilenameAndSoftwareModule("file1", sm.getId())).isPresent(); - } - } - /** * Verifies that creation of an artifact with none matching hashes fails. */ @@ -522,8 +478,8 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest { assertThat(createdArtifact.getSha256Hash()).isEqualTo(artifactHashes.getSha256()); } - final Optional dbArtifact = artifactManagement.loadArtifactBinary(artifactHashes.getSha1(), sm.getId(), sm.isEncrypted()); - assertThat(dbArtifact).isPresent(); + final DbArtifact dbArtifact = artifactManagement.loadArtifactBinary(artifactHashes.getSha1(), sm.getId(), sm.isEncrypted()); + assertThat(dbArtifact).isNotNull(); } /** @@ -544,9 +500,8 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest { final Artifact artifact = artifactManagement.create(artifactUpload); assertThat(artifact).isNotNull(); } - final Optional dbArtifact = artifactManagement.loadArtifactBinary( - artifactHashes.getSha1(), smOs.getId(), smOs.isEncrypted()); - assertThat(dbArtifact).isPresent(); + final DbArtifact dbArtifact = artifactManagement.loadArtifactBinary(artifactHashes.getSha1(), smOs.getId(), smOs.isEncrypted()); + assertThat(dbArtifact).isNotNull(); try (final InputStream inputStream = new ByteArrayInputStream(testData)) { final ArtifactUpload existingArtifactUpload = new ArtifactUpload( @@ -601,8 +556,8 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest { assertThat(runAsTenant(tenant, () -> artifactRepository.findAll())).hasSize(count); } - private void assertEqualFileContents(final Optional artifact, final byte[] randomBytes) throws IOException { - try (final InputStream inputStream = artifact.get().getFileInputStream()) { + private void assertEqualFileContents(final DbArtifact artifact, final byte[] randomBytes) throws IOException { + try (final InputStream inputStream = artifact.getFileInputStream()) { assertTrue( IOUtils.contentEquals(new ByteArrayInputStream(randomBytes), inputStream), "The stored binary matches the given binary"); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ControllerManagementSecurityTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ControllerManagementSecurityTest.java index 41574b85c..b7f42ff53 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ControllerManagementSecurityTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ControllerManagementSecurityTest.java @@ -195,10 +195,10 @@ class ControllerManagementSecurityTest extends AbstractJpaIntegrationTest { * Tests ControllerManagement#getByControllerId() method */ @Test - void getByControllerIdPermissionsCheck() { - assertPermissions(() -> controllerManagement.getByControllerId("controllerId"), + void findByControllerIdPermissionsCheck() { + assertPermissions(() -> controllerManagement.findByControllerId("controllerId"), List.of(SpRole.CONTROLLER_ROLE)); - assertPermissions(() -> controllerManagement.getByControllerId("controllerId"), + assertPermissions(() -> controllerManagement.findByControllerId("controllerId"), List.of(SpRole.SYSTEM_ROLE)); } @@ -207,8 +207,8 @@ class ControllerManagementSecurityTest extends AbstractJpaIntegrationTest { */ @Test void getPermissionsCheck() { - assertPermissions(() -> controllerManagement.get(1L), List.of(SpRole.CONTROLLER_ROLE)); - assertPermissions(() -> controllerManagement.get(1L), List.of(SpRole.SYSTEM_ROLE)); + assertPermissions(() -> controllerManagement.find(1L), List.of(SpRole.CONTROLLER_ROLE)); + assertPermissions(() -> controllerManagement.find(1L), List.of(SpRole.SYSTEM_ROLE)); } /** diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ControllerManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ControllerManagementTest.java index 825c6835d..a7c0d386b 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ControllerManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/ControllerManagementTest.java @@ -332,8 +332,8 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest { final SoftwareModule module = testdataFactory.createSoftwareModuleOs(); assertThat(controllerManagement.findActionWithDetails(NOT_EXIST_IDL)).isNotPresent(); - assertThat(controllerManagement.getByControllerId(NOT_EXIST_ID)).isNotPresent(); - assertThat(controllerManagement.get(NOT_EXIST_IDL)).isNotPresent(); + assertThat(controllerManagement.findByControllerId(NOT_EXIST_ID)).isNotPresent(); + assertThat(controllerManagement.find(NOT_EXIST_IDL)).isNotPresent(); assertThat(controllerManagement.getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(), module.getId())).isNotPresent(); @@ -1952,14 +1952,14 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest { } private void assertAssignedDistributionSetId(final String controllerId, final Long dsId) { - final Optional target = controllerManagement.getByControllerId(controllerId); + final Optional target = controllerManagement.findByControllerId(controllerId); assertThat(target).isPresent(); final DistributionSet assignedDistributionSet = ((JpaTarget) target.get()).getAssignedDistributionSet(); assertThat(assignedDistributionSet.getId()).isEqualTo(dsId); } private void assertInstalledDistributionSetId(final String controllerId, final Long dsId) { - final Optional target = controllerManagement.getByControllerId(controllerId); + final Optional target = controllerManagement.findByControllerId(controllerId); assertThat(target).isPresent(); final DistributionSet installedDistributionSet = ((JpaTarget) target.get()).getInstalledDistributionSet(); if (dsId == null) { diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DeploymentManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DeploymentManagementTest.java index cc54298e8..d02cb4c08 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DeploymentManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DeploymentManagementTest.java @@ -1341,12 +1341,12 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest { distributionSetManagement.delete(dsA.getId()); - assertThat(distributionSetManagement.get(dsA.getId())).isNotPresent(); + assertThat(distributionSetManagement.find(dsA.getId())).isNotPresent(); // // verify that the ds is not physically deleted for (final DistributionSet ds : deploymentResult.getDistributionSets()) { distributionSetManagement.delete(ds.getId()); - final DistributionSet foundDS = distributionSetManagement.get(ds.getId()).get(); + final DistributionSet foundDS = distributionSetManagement.find(ds.getId()).get(); assertThat(foundDS).as("founded should not be null").isNotNull(); assertThat(foundDS.isDeleted()).as("found ds should be deleted").isTrue(); } @@ -1780,7 +1780,7 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest { } private Slice findActionsByDistributionSet(final Pageable pageable, final long distributionSetId) { - distributionSetManagement.get(distributionSetId).orElseThrow(() -> + distributionSetManagement.find(distributionSetId).orElseThrow(() -> new EntityNotFoundException(DistributionSet.class, distributionSetId)); return actionRepository .findAll(byDistributionSetId(distributionSetId), pageable) diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetInvalidationManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetInvalidationManagementTest.java index 90a060461..348eb69f2 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetInvalidationManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetInvalidationManagementTest.java @@ -63,7 +63,7 @@ class DistributionSetInvalidationManagementTest extends AbstractJpaIntegrationTe distributionSetInvalidationManagement.invalidateDistributionSet(distributionSetInvalidation); rolloutHandler.handleAll(); - assertThat(targetFilterQueryManagement.get(invalidationTestData.getTargetFilterQuery().getId()).get() + assertThat(targetFilterQueryManagement.find(invalidationTestData.getTargetFilterQuery().getId()).get() .getAutoAssignDistributionSet()).isNull(); assertThat(rolloutRepository.findById(invalidationTestData.getRollout().getId()).get().getStatus()) .isNotIn(RolloutStatus.STOPPING, RolloutStatus.FINISHED); @@ -92,7 +92,7 @@ class DistributionSetInvalidationManagementTest extends AbstractJpaIntegrationTe distributionSetInvalidationManagement.invalidateDistributionSet(distributionSetInvalidation); rolloutHandler.handleAll(); - assertThat(targetFilterQueryManagement.get(invalidationTestData.getTargetFilterQuery().getId()).get() + assertThat(targetFilterQueryManagement.find(invalidationTestData.getTargetFilterQuery().getId()).get() .getAutoAssignDistributionSet()).isNull(); assertThat(rolloutRepository.findById(invalidationTestData.getRollout().getId()).get().getStatus()) .isEqualTo(RolloutStatus.READY); @@ -124,7 +124,7 @@ class DistributionSetInvalidationManagementTest extends AbstractJpaIntegrationTe distributionSetInvalidationManagement.invalidateDistributionSet(distributionSetInvalidation); rolloutHandler.handleAll(); - assertThat(targetFilterQueryManagement.get(invalidationTestData.getTargetFilterQuery().getId()).get() + assertThat(targetFilterQueryManagement.find(invalidationTestData.getTargetFilterQuery().getId()).get() .getAutoAssignDistributionSet()).isNull(); // rollout should be deleted when force invalidation assertThat(rolloutRepository.findById(invalidationTestData.getRollout().getId())).isEmpty(); @@ -146,7 +146,7 @@ class DistributionSetInvalidationManagementTest extends AbstractJpaIntegrationTe distributionSetInvalidationManagement.invalidateDistributionSet(distributionSetInvalidation); - assertThat(targetFilterQueryManagement.get(invalidationTestData.getTargetFilterQuery().getId()).get() + assertThat(targetFilterQueryManagement.find(invalidationTestData.getTargetFilterQuery().getId()).get() .getAutoAssignDistributionSet()).isNull(); assertThat(rolloutRepository.findById(invalidationTestData.getRollout().getId()).get().getStatus()) .isIn(RolloutStatus.STOPPING, RolloutStatus.FINISHED); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetManagementSecurityTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetManagementSecurityTest.java index 78586a80d..f2d2d8a91 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetManagementSecurityTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetManagementSecurityTest.java @@ -26,17 +26,17 @@ class DistributionSetManagementSecurityTest extends AbstractRepositoryManagementSecurityTest { @Override - protected DistributionSetManagement getRepositoryManagement() { + protected DistributionSetManagement findRepositoryManagement() { return distributionSetManagement; } @Override - protected DistributionSetManagement.Create getCreateObject() { + protected DistributionSetManagement.Create findCreateObject() { return DistributionSetManagement.Create.builder().name("name").version("1.0.0").type(defaultDsType()).build(); } @Override - protected DistributionSetManagement.Update getUpdateObject() { + protected DistributionSetManagement.Update findUpdateObject() { return DistributionSetManagement.Update.builder().id(0L).name("a new name") .description("a new description").version("a new version").requiredMigrationStep(true).build(); } @@ -157,8 +157,8 @@ class DistributionSetManagementSecurityTest * Tests ManagementAPI PreAuthorized method with correct and insufficient permissions. */ @Test - void getOrElseThrowExceptionPermissionsCheck() { - assertPermissions(() -> distributionSetManagement.getOrElseThrowException(1L), List.of(SpPermission.READ_REPOSITORY)); + void getPermissionsCheck() { + assertPermissions(() -> distributionSetManagement.get(1L), List.of(SpPermission.READ_REPOSITORY)); } /** diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetManagementTest.java index 8107bbaf7..584002382 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetManagementTest.java @@ -91,7 +91,7 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest { @Expect(type = SoftwareModuleCreatedEvent.class, count = 3) }) void nonExistingEntityAccessReturnsNotPresent() { final DistributionSet set = testdataFactory.createDistributionSet(); - assertThat(distributionSetManagement.get(NOT_EXIST_IDL)).isNotPresent(); + assertThat(distributionSetManagement.find(NOT_EXIST_IDL)).isNotPresent(); assertThat(distributionSetManagement.getWithDetails(NOT_EXIST_IDL)).isNotPresent(); assertThat(distributionSetManagement.findByNameAndVersion(NOT_EXIST_ID, NOT_EXIST_ID)).isNotPresent(); assertThat(distributionSetManagement.getMetadata(set.getId()).get(NOT_EXIST_ID)).isNull(); @@ -149,7 +149,7 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest { "DistributionSet"); verifyThrownExceptionBy(() -> distributionSetManagement.createMetadata(NOT_EXIST_IDL, "xxx", "xxx"), "DistributionSet"); - verifyThrownExceptionBy(() -> distributionSetManagement.getOrElseThrowException(NOT_EXIST_IDL), "DistributionSet"); + verifyThrownExceptionBy(() -> distributionSetManagement.get(NOT_EXIST_IDL), "DistributionSet"); verifyThrownExceptionBy(() -> distributionSetManagement.getValidAndComplete(NOT_EXIST_IDL), "DistributionSet"); } @@ -292,7 +292,7 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest { .as("ds has wrong tag size") .hasSize(1)); - final DistributionSetTag findDistributionSetTag = getOrThrow(distributionSetTagManagement.get(tag.getId())); + final DistributionSetTag findDistributionSetTag = getOrThrow(distributionSetTagManagement.find(tag.getId())); assertThat(assignedDS) .as("assigned ds has wrong size") @@ -302,7 +302,7 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest { .unassignTag(List.of(assignDS.get(0)), findDistributionSetTag.getId()).get(0); assertThat(unAssignDS.getId()).as("unassigned ds is wrong").isEqualTo(assignDS.get(0)); assertThat(unAssignDS.getTags()).as("unassigned ds has wrong tag size").isEmpty(); - assertThat(distributionSetTagManagement.get(tag.getId())).isPresent(); + assertThat(distributionSetTagManagement.find(tag.getId())).isPresent(); assertThat(distributionSetManagement.findByTag(tag.getId(), PAGE).getNumberOfElements()) .as("ds tag ds has wrong ds size").isEqualTo(3); @@ -508,7 +508,7 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest { // create an DS meta data entry insertMetadata(knownKey, knownValue, ds); - final DistributionSet changedLockRevisionDS = getOrThrow(distributionSetManagement.get(ds.getId())); + final DistributionSet changedLockRevisionDS = getOrThrow(distributionSetManagement.find(ds.getId())); assertThat(changedLockRevisionDS.getOptLockRevision()).isEqualTo(2); waitNextMillis(); @@ -516,7 +516,7 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest { distributionSetManagement.createMetadata(ds.getId(), knownKey, knownUpdateValue); // we are updating the sw metadata so also modifying the base software // module so opt lock revision must be three - final DistributionSet reloadedDS = getOrThrow(distributionSetManagement.get(ds.getId())); + final DistributionSet reloadedDS = getOrThrow(distributionSetManagement.find(ds.getId())); assertThat(reloadedDS.getOptLockRevision()).isEqualTo(3); assertThat(reloadedDS.getLastModifiedAt()).isPositive(); @@ -562,7 +562,7 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest { assignDistributionSet(dsDeleted, testdataFactory.createTargets(5)); distributionSetManagement.delete(dsDeleted.getId()); - dsDeleted = getOrThrow(distributionSetManagement.get(dsDeleted.getId())); + dsDeleted = getOrThrow(distributionSetManagement.find(dsDeleted.getId())); dsGroup1 = assignTag(dsGroup1, dsTagA); dsTagA = getOrThrow(distributionSetTagRepository.findById(dsTagA.getId())); @@ -600,9 +600,9 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest { @Test void lockDistributionSet() { final DistributionSet distributionSet = testdataFactory.createDistributionSet("ds-1"); - assertThat(distributionSetManagement.get(distributionSet.getId()).map(DistributionSet::isLocked).orElse(true)).isFalse(); + assertThat(distributionSetManagement.find(distributionSet.getId()).map(DistributionSet::isLocked).orElse(true)).isFalse(); distributionSetManagement.lock(distributionSet); - assertThat(distributionSetManagement.get(distributionSet.getId()).map(DistributionSet::isLocked).orElse(false)).isTrue(); + assertThat(distributionSetManagement.find(distributionSet.getId()).map(DistributionSet::isLocked).orElse(false)).isTrue(); // assert software modules are locked assertThat(distributionSet.getModules().size()).isNotZero(); distributionSetManagement.getWithDetails(distributionSet.getId()).map(DistributionSet::getModules).orElseThrow() @@ -616,10 +616,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest { void deleteUnassignedLockedDistributionSet() { final DistributionSet distributionSet = testdataFactory.createDistributionSet("ds-1"); distributionSetManagement.lock(distributionSet); - assertThat(distributionSetManagement.get(distributionSet.getId()).map(DistributionSet::isLocked).orElse(false)).isTrue(); + assertThat(distributionSetManagement.find(distributionSet.getId()).map(DistributionSet::isLocked).orElse(false)).isTrue(); distributionSetManagement.delete(distributionSet.getId()); - assertThat(distributionSetManagement.get(distributionSet.getId())).isEmpty(); + assertThat(distributionSetManagement.find(distributionSet.getId())).isEmpty(); } /** @@ -629,13 +629,13 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest { void deleteAssignedLockedDistributionSet() { final DistributionSet distributionSet = testdataFactory.createDistributionSet("ds-1"); distributionSetManagement.lock(distributionSet); - assertThat(distributionSetManagement.get(distributionSet.getId()).map(DistributionSet::isLocked).orElse(false)).isTrue(); + assertThat(distributionSetManagement.find(distributionSet.getId()).map(DistributionSet::isLocked).orElse(false)).isTrue(); final Target target = testdataFactory.createTarget(); assignDistributionSet(distributionSet.getId(), target.getControllerId()); distributionSetManagement.delete(distributionSet.getId()); - assertThat(distributionSetManagement.getOrElseThrowException(distributionSet.getId()).isDeleted()).isTrue(); + assertThat(distributionSetManagement.get(distributionSet.getId()).isDeleted()).isTrue(); } /** @@ -645,9 +645,9 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest { void unlockDistributionSet() { DistributionSet distributionSet = testdataFactory.createDistributionSet("ds-1"); distributionSet = distributionSetManagement.lock(distributionSet); - assertThat(distributionSetManagement.get(distributionSet.getId()).map(DistributionSet::isLocked).orElse(false)).isTrue(); + assertThat(distributionSetManagement.find(distributionSet.getId()).map(DistributionSet::isLocked).orElse(false)).isTrue(); distributionSet = distributionSetManagement.unlock(distributionSet); - assertThat(distributionSetManagement.get(distributionSet.getId()).map(DistributionSet::isLocked).orElse(true)).isFalse(); + assertThat(distributionSetManagement.find(distributionSet.getId()).map(DistributionSet::isLocked).orElse(true)).isFalse(); // assert software modules are not unlocked assertThat(distributionSet.getModules().size()).isNotZero(); distributionSetManagement.getWithDetails(distributionSet.getId()).map(DistributionSet::getModules).orElseThrow() @@ -664,7 +664,7 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest { assertThat(softwareModuleCount).isNotZero(); distributionSetManagement.lock(distributionSet); final Long distributionSetId = distributionSet.getId(); - assertThat(distributionSetManagement.get(distributionSetId).map(DistributionSet::isLocked).orElse(false)).isTrue(); + assertThat(distributionSetManagement.find(distributionSetId).map(DistributionSet::isLocked).orElse(false)).isTrue(); // try add final List moduleIds = List.of(testdataFactory.createSoftwareModule("sm-1").getId()); @@ -709,7 +709,7 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest { skipTags.forEach(skipTag -> { DistributionSet distributionSetWithSkipTag = testdataFactory.createDistributionSet("ds-skip-" + skipTag.getName()); distributionSetManagement.assignTag(List.of(distributionSetWithSkipTag.getId()), skipTag.getId()); - distributionSetWithSkipTag = distributionSetManagement.get(distributionSetWithSkipTag.getId()).orElseThrow(); + distributionSetWithSkipTag = distributionSetManagement.find(distributionSetWithSkipTag.getId()).orElseThrow(); // assert that implicit lock isn't applicable for skip tags assertThat(distributionSetManagement.shouldLockImplicitly(distributionSetWithSkipTag)).isFalse(); }); @@ -725,7 +725,7 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest { .as("Locking an incomplete distribution set should throw an exception") .isThrownBy(() -> distributionSetManagement.lock(incompleteDistributionSet)); assertThat( - distributionSetManagement.get(incompleteDistributionSet.getId()).map(DistributionSet::isLocked).orElse(true)) + distributionSetManagement.find(incompleteDistributionSet.getId()).map(DistributionSet::isLocked).orElse(true)) .isFalse(); } @@ -909,12 +909,12 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest { assertThat(distributionSetManagement.countRolloutsByStatusForDistributionSet(ds2.getId())).hasSize(1); assertThat(distributionSetManagement.countRolloutsByStatusForDistributionSet(ds3.getId())).isEmpty(); - Optional rollout = rolloutManagement.get(rollout1.getId()); + Optional rollout = rolloutManagement.find(rollout1.getId()); rollout.ifPresent(value -> assertThat(Rollout.RolloutStatus.valueOf( String.valueOf(distributionSetManagement.countRolloutsByStatusForDistributionSet(ds1.getId()).get(0).getName()))).isEqualTo( value.getStatus())); - rollout = rolloutManagement.get(rollout2.getId()); + rollout = rolloutManagement.find(rollout2.getId()); rollout.ifPresent(value -> assertThat(Rollout.RolloutStatus.valueOf( String.valueOf(distributionSetManagement.countRolloutsByStatusForDistributionSet(ds2.getId()).get(0).getName()))).isEqualTo( value.getStatus())); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetTagManagementSecurityTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetTagManagementSecurityTest.java index 0724d6e60..47da9f9bc 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetTagManagementSecurityTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetTagManagementSecurityTest.java @@ -28,17 +28,17 @@ class DistributionSetTagManagementSecurityTest extends AbstractRepositoryManagementSecurityTest { @Override - protected RepositoryManagement getRepositoryManagement() { + protected RepositoryManagement findRepositoryManagement() { return distributionSetTagManagement; } @Override - protected DistributionSetTagManagement.Create getCreateObject() { + protected DistributionSetTagManagement.Create findCreateObject() { return DistributionSetTagManagement.Create.builder().name(String.format("tag-%d", new Random().nextInt())).build(); } @Override - protected DistributionSetTagManagement.Update getUpdateObject() { + protected DistributionSetTagManagement.Update findUpdateObject() { return DistributionSetTagManagement.Update.builder().id(1L).name("tag").build(); } } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetTagManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetTagManagementTest.java index 9e75f80bf..db30e4d60 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetTagManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetTagManagementTest.java @@ -18,7 +18,6 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; -import java.util.Random; import java.util.stream.Stream; import org.eclipse.hawkbit.repository.DistributionSetTagManagement; @@ -51,7 +50,7 @@ class DistributionSetTagManagementTest extends AbstractJpaIntegrationTest { @Test @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) }) void nonExistingEntityAccessReturnsNotPresent() { - assertThat(distributionSetTagManagement.get(NOT_EXIST_IDL)).isNotPresent(); + assertThat(distributionSetTagManagement.find(NOT_EXIST_IDL)).isNotPresent(); } /** @@ -91,18 +90,18 @@ class DistributionSetTagManagementTest extends AbstractJpaIntegrationTest { assignTag(dsBs, tagB); assignTag(dsCs, tagC); - assignTag(dsABs, distributionSetTagManagement.get(tagA.getId()).orElseThrow()); - assignTag(dsABs, distributionSetTagManagement.get(tagB.getId()).orElseThrow()); + assignTag(dsABs, distributionSetTagManagement.find(tagA.getId()).orElseThrow()); + assignTag(dsABs, distributionSetTagManagement.find(tagB.getId()).orElseThrow()); - assignTag(dsACs, distributionSetTagManagement.get(tagA.getId()).orElseThrow()); - assignTag(dsACs, distributionSetTagManagement.get(tagC.getId()).orElseThrow()); + assignTag(dsACs, distributionSetTagManagement.find(tagA.getId()).orElseThrow()); + assignTag(dsACs, distributionSetTagManagement.find(tagC.getId()).orElseThrow()); - assignTag(dsBCs, distributionSetTagManagement.get(tagB.getId()).orElseThrow()); - assignTag(dsBCs, distributionSetTagManagement.get(tagC.getId()).orElseThrow()); + assignTag(dsBCs, distributionSetTagManagement.find(tagB.getId()).orElseThrow()); + assignTag(dsBCs, distributionSetTagManagement.find(tagC.getId()).orElseThrow()); - assignTag(dsABCs, distributionSetTagManagement.get(tagA.getId()).orElseThrow()); - assignTag(dsABCs, distributionSetTagManagement.get(tagB.getId()).orElseThrow()); - assignTag(dsABCs, distributionSetTagManagement.get(tagC.getId()).orElseThrow()); + assignTag(dsABCs, distributionSetTagManagement.find(tagA.getId()).orElseThrow()); + assignTag(dsABCs, distributionSetTagManagement.find(tagB.getId()).orElseThrow()); + assignTag(dsABCs, distributionSetTagManagement.find(tagC.getId()).orElseThrow()); // search for not deleted final DistributionSetFilter.DistributionSetFilterBuilder distributionSetFilterBuilder = getDistributionSetFilterBuilder() @@ -215,9 +214,9 @@ class DistributionSetTagManagementTest extends AbstractJpaIntegrationTest { assertThat(distributionSetTagRepository.findById(tag.getId()).orElseThrow().getDescription()).as("wrong tag found") .isEqualTo("kai2"); - assertThat(distributionSetTagManagement.get(tag.getId()).orElseThrow().getColour()).as("wrong tag found") + assertThat(distributionSetTagManagement.find(tag.getId()).orElseThrow().getColour()).as("wrong tag found") .isEqualTo("colour"); - assertThat(distributionSetTagManagement.get(tag.getId()).orElseThrow().getColour()).as("wrong tag found") + assertThat(distributionSetTagManagement.find(tag.getId()).orElseThrow().getColour()).as("wrong tag found") .isEqualTo("colour"); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetTypeManagementSecurityTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetTypeManagementSecurityTest.java index 6dc7e5da2..0f66e3ca0 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetTypeManagementSecurityTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetTypeManagementSecurityTest.java @@ -27,17 +27,17 @@ class DistributionSetTypeManagementSecurityTest extends AbstractRepositoryManagementSecurityTest { @Override - protected RepositoryManagement getRepositoryManagement() { + protected RepositoryManagement findRepositoryManagement() { return distributionSetTypeManagement; } @Override - protected DistributionSetTypeManagement.Create getCreateObject() { + protected DistributionSetTypeManagement.Create findCreateObject() { return DistributionSetTypeManagement.Create.builder().key(String.format("key-%d", new Random().nextInt())).name(String.format("name-%d", new Random().nextInt())).build(); } @Override - protected DistributionSetTypeManagement.Update getUpdateObject() { + protected DistributionSetTypeManagement.Update findUpdateObject() { return DistributionSetTypeManagement.Update.builder().id(1L).description("description").build(); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetTypeManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetTypeManagementTest.java index 80ac1e08e..ef1592325 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetTypeManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/DistributionSetTypeManagementTest.java @@ -56,7 +56,7 @@ class DistributionSetTypeManagementTest extends AbstractJpaIntegrationTest { @Test @ExpectEvents({ @Expect(type = DistributionSetCreatedEvent.class, count = 0) }) void nonExistingEntityAccessReturnsNotPresent() { - assertThat(distributionSetTypeManagement.get(NOT_EXIST_IDL)).isNotPresent(); + assertThat(distributionSetTypeManagement.find(NOT_EXIST_IDL)).isNotPresent(); assertThat(distributionSetTypeManagement.findByKey(NOT_EXIST_ID)).isNotPresent(); assertThat(distributionSetTypeManagement.findByName(NOT_EXIST_ID)).isNotPresent(); } @@ -165,8 +165,8 @@ class DistributionSetTypeManagementTest extends AbstractJpaIntegrationTest { final Long dsType2Id = dsType2.getId(); distributionSetTypeManagement.assignMandatorySoftwareModuleTypes(dsType2Id, moduleTypeIds.subList(0, quota)); - assertThat(distributionSetTypeManagement.get(dsType2Id)).isNotEmpty(); - assertThat(distributionSetTypeManagement.get(dsType2Id).get().getMandatoryModuleTypes()).hasSize(quota); + assertThat(distributionSetTypeManagement.find(dsType2Id)).isNotEmpty(); + assertThat(distributionSetTypeManagement.find(dsType2Id).get().getMandatoryModuleTypes()).hasSize(quota); // assign one more to trigger the quota exceeded error final List softwareModuleTypeIds = Collections.singletonList(moduleTypeIds.get(quota)); assertThatExceptionOfType(AssignmentQuotaExceededException.class) @@ -177,8 +177,8 @@ class DistributionSetTypeManagementTest extends AbstractJpaIntegrationTest { .create(DistributionSetTypeManagement.Create.builder().key("dst3").name("dst3").build()); final Long dsType3Id = dsType3.getId(); distributionSetTypeManagement.assignOptionalSoftwareModuleTypes(dsType3Id, moduleTypeIds.subList(0, quota)); - assertThat(distributionSetTypeManagement.get(dsType3Id)).isNotEmpty(); - assertThat(distributionSetTypeManagement.get(dsType3Id).get().getOptionalModuleTypes()).hasSize(quota); + assertThat(distributionSetTypeManagement.find(dsType3Id)).isNotEmpty(); + assertThat(distributionSetTypeManagement.find(dsType3Id).get().getOptionalModuleTypes()).hasSize(quota); // assign one more to trigger the quota exceeded error assertThatExceptionOfType(AssignmentQuotaExceededException.class) .isThrownBy(() -> distributionSetTypeManagement.assignOptionalSoftwareModuleTypes(dsType3Id, softwareModuleTypeIds)); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/LazyControllerManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/LazyControllerManagementTest.java index 04c59af9e..2006e7514 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/LazyControllerManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/LazyControllerManagementTest.java @@ -51,7 +51,7 @@ class LazyControllerManagementTest extends AbstractJpaIntegrationTest { controllerManagement.findOrRegisterTargetIfItDoesNotExist("AA", LOCALHOST); TimeUnit.MILLISECONDS.sleep(repositoryProperties.getPollPersistenceFlushTime() + 10); - final Target updated = targetManagement.get(target.getId()).get(); + final Target updated = targetManagement.find(target.getId()).get(); assertThat(updated.getOptLockRevision()).isEqualTo(target.getOptLockRevision()); assertThat(updated.getLastTargetQuery()).isGreaterThan(target.getLastTargetQuery()); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/RolloutManagementSecurityTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/RolloutManagementSecurityTest.java index 01a1d253d..f0e16bc26 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/RolloutManagementSecurityTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/RolloutManagementSecurityTest.java @@ -22,7 +22,6 @@ import org.eclipse.hawkbit.repository.RolloutManagement.Update; import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; import org.eclipse.hawkbit.repository.model.ActionCancellationType; import org.eclipse.hawkbit.repository.model.DistributionSet; -import org.eclipse.hawkbit.repository.model.DistributionSetInvalidation; import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.RolloutGroupConditionBuilder; import org.eclipse.hawkbit.repository.test.util.TestdataFactory; @@ -44,15 +43,15 @@ class RolloutManagementSecurityTest extends AbstractJpaIntegrationTest { * Tests ManagementAPI PreAuthorized method with correct and insufficient permissions. */ @Test - void getPermissionsCheck() { - assertPermissions(() -> rolloutManagement.get(1L), List.of(SpPermission.READ_ROLLOUT)); + void findPermissionsCheck() { + assertPermissions(() -> rolloutManagement.find(1L), List.of(SpPermission.READ_ROLLOUT)); } /** * Tests ManagementAPI PreAuthorized method with correct and insufficient permissions. */ @Test - void getByNamePermissionsCheck() { + void findByNamePermissionsCheck() { assertPermissions(() -> rolloutManagement.getByName("name"), List.of(SpPermission.READ_ROLLOUT)); } @@ -60,7 +59,7 @@ class RolloutManagementSecurityTest extends AbstractJpaIntegrationTest { * Tests ManagementAPI PreAuthorized method with correct and insufficient permissions. */ @Test - void getWithDetailedStatusPermissionsCheck() { + void findWithDetailedStatusPermissionsCheck() { assertPermissions(() -> rolloutManagement.getWithDetailedStatus(1L), List.of(SpPermission.READ_ROLLOUT)); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/RolloutManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/RolloutManagementTest.java index deaf2ba9f..ab9f6d218 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/RolloutManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/RolloutManagementTest.java @@ -289,7 +289,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest { @Test @ExpectEvents({ @Expect(type = TargetCreatedEvent.class) }) void nonExistingEntityAccessReturnsNotPresent() { - assertThat(rolloutManagement.get(NOT_EXIST_IDL)).isNotPresent(); + assertThat(rolloutManagement.find(NOT_EXIST_IDL)).isNotPresent(); assertThat(rolloutManagement.getByName(NOT_EXIST_ID)).isNotPresent(); assertThat(rolloutManagement.getWithDetailedStatus(NOT_EXIST_IDL)).isNotPresent(); } @@ -570,7 +570,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest { rolloutHandler.handleAll(); // finish running actions, 2 actions should be finished assertThat(changeStatusForAllRunningActions(createdRollout, Status.FINISHED)).isEqualTo(2); - assertThat(getRollout(createdRollout.getId()).getStatus()).isEqualTo(RolloutStatus.RUNNING); + assertThat(findRollout(createdRollout.getId()).getStatus()).isEqualTo(RolloutStatus.RUNNING); } // check rollout to see that all actions and all groups are finished and @@ -857,7 +857,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest { * Verify that target actions of a rollout get cancelled when another rollout with same targets gets started. */ @Test - void targetsOfRolloutGetDistributionSetAssignmentByOtherRollout() { + void targetsOfRolloutFindDistributionSetAssignmentByOtherRollout() { final int amountTargetsForRollout = 15; final int amountOtherTargets = 5; @@ -1187,7 +1187,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest { * Verify that the percent count is acting like aspected when targets move to the status finished or error. */ @Test - void getFinishedPercentForRunningGroup() { + void findFinishedPercentForRunningGroup() { final int amountTargetsForRollout = 10; final int amountGroups = 2; @@ -1363,7 +1363,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest { // Run here, because scheduler is disabled during tests rolloutHandler.handleAll(); - myRollout = getRollout(myRolloutId); + myRollout = findRollout(myRolloutId); assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.RUNNING); final Map expectedTargetCountStatus = createInitStatusMap(); expectedTargetCountStatus.put(TotalTargetCountStatus.Status.RUNNING, 1L); @@ -1389,7 +1389,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest { assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.READY); rolloutHandler.handleAll(); - myRollout = getRollout(myRollout.getId()); + myRollout = findRollout(myRollout.getId()); assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.READY); rolloutManagement.start(myRollout.getId()); @@ -1568,7 +1568,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest { rolloutHandler.handleAll(); // rollout should not have been started - myRollout = getRollout(myRolloutId); + myRollout = findRollout(myRolloutId); assertThat(myRollout.getName()).isEqualTo("newName"); assertThat(myRollout.getDescription()).isEqualTo("newDesc"); } @@ -1604,7 +1604,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest { rolloutGroups.add(generateRolloutGroup(2, percentTargetsInGroup3, null)); Rollout myRollout = rolloutManagement.create(rolloutcreate, rolloutGroups, conditions); - myRollout = getRollout(myRollout.getId()); + myRollout = findRollout(myRollout.getId()); assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.CREATING); for (final RolloutGroup group : rolloutGroupManagement.findByRollout(myRollout.getId(), PAGE).getContent()) { @@ -1616,7 +1616,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest { rolloutHandler.handleAll(); - myRollout = getRollout(myRollout.getId()); + myRollout = findRollout(myRollout.getId()); assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.READY); assertThat(myRollout.getTotalTargets()).isEqualTo(amountTargetsInGroup2and3 + amountTargetsInGroup1); @@ -1658,7 +1658,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest { final Long rolloutId = rolloutManagement.create(rolloutcreate, rolloutGroups, conditions).getId(); - assertThat(getRollout(rolloutId)).satisfies(rollout -> { + assertThat(findRollout(rolloutId)).satisfies(rollout -> { assertThat(rollout.getStatus()).isEqualTo(RolloutStatus.CREATING); for (final RolloutGroup group : rolloutGroupManagement.findByRollout(rollout.getId(), PAGE).getContent()) { assertThat(group.getStatus()).isEqualTo(RolloutGroupStatus.CREATING); @@ -1668,7 +1668,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest { // first handle iteration will put rollout in ready state rolloutHandler.handleAll(); - assertThat(getRollout(rolloutId)).satisfies(rollout -> { + assertThat(findRollout(rolloutId)).satisfies(rollout -> { assertThat(rollout.getStatus()).isEqualTo(RolloutStatus.READY); assertThat(rollout.getTotalTargets()).isEqualTo(amountTargetsInGroup1 + amountTargetsInGroup2); }); @@ -1796,7 +1796,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest { .build(); Rollout myRollout = rolloutManagement.create(rolloutToCreate, amountGroups, false, conditions); - myRollout = getRollout(myRollout.getId()); + myRollout = findRollout(myRollout.getId()); assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.CREATING); @@ -2215,10 +2215,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest { void testRolloutStatusConvert() { final long id = testdataFactory.createAndStartRollout(1, 0, 1, "100", "80").getId(); for (final RolloutStatus status : RolloutStatus.values()) { - final JpaRollout rollout = ((JpaRollout) rolloutManagement.get(id).orElseThrow()); + final JpaRollout rollout = ((JpaRollout) rolloutManagement.find(id).orElseThrow()); rollout.setStatus(status); rolloutRepository.save(rollout); - assertThat(rolloutManagement.get(id).orElseThrow().getStatus()).isEqualTo(status); + assertThat(rolloutManagement.find(id).orElseThrow().getStatus()).isEqualTo(status); } } @@ -2229,10 +2229,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest { void testActionTypeConvert() { final long id = testdataFactory.createAndStartRollout(1, 0, 1, "100", "80").getId(); for (final ActionType actionType : ActionType.values()) { - final JpaRollout rollout = ((JpaRollout) rolloutManagement.get(id).orElseThrow()); + final JpaRollout rollout = ((JpaRollout) rolloutManagement.find(id).orElseThrow()); rollout.setActionType(actionType); rolloutRepository.save(rollout); - assertThat(rolloutManagement.get(id).orElseThrow().getActionType()).isEqualTo(actionType); + assertThat(rolloutManagement.find(id).orElseThrow().getActionType()).isEqualTo(actionType); } } @@ -2355,11 +2355,11 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest { } private Rollout reloadRollout(final Rollout r) { - return getRollout(r.getId()); + return findRollout(r.getId()); } - private Rollout getRollout(final Long myRolloutId) { - return rolloutManagement.get(myRolloutId).orElseThrow(NoSuchElementException::new); + private Rollout findRollout(final Long myRolloutId) { + return rolloutManagement.find(myRolloutId).orElseThrow(NoSuchElementException::new); } private void assertRolloutGroup(final long rolloutGroupId, final RolloutGroupStatus status, diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/SoftwareManagementSecurityTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/SoftwareManagementSecurityTest.java index 3562b57ee..c7af40a2c 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/SoftwareManagementSecurityTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/SoftwareManagementSecurityTest.java @@ -29,17 +29,17 @@ class SoftwareManagementSecurityTest extends AbstractRepositoryManagementSecurityTest { @Override - protected RepositoryManagement getRepositoryManagement() { + protected RepositoryManagement findRepositoryManagement() { return softwareModuleManagement; } @Override - protected SoftwareModuleManagement.Create getCreateObject() { + protected SoftwareModuleManagement.Create findCreateObject() { return SoftwareModuleManagement.Create.builder().type(getASmType()).name("name").version("version").build(); } @Override - protected SoftwareModuleManagement.Update getUpdateObject() { + protected SoftwareModuleManagement.Update findUpdateObject() { return SoftwareModuleManagement.Update.builder().id(1L).locked(true).build(); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/SoftwareModuleManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/SoftwareModuleManagementTest.java index d9d5d90d0..2e34816d6 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/SoftwareModuleManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/SoftwareModuleManagementTest.java @@ -26,6 +26,7 @@ import jakarta.validation.ConstraintViolationException; import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.SoftwareModuleManagement; +import org.eclipse.hawkbit.repository.artifact.exception.ArtifactBinaryNotFoundException; import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleCreatedEvent; import org.eclipse.hawkbit.repository.exception.AssignmentQuotaExceededException; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; @@ -67,7 +68,7 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { @ExpectEvents({ @Expect(type = SoftwareModuleCreatedEvent.class, count = 1) }) void nonExistingEntityAccessReturnsNotPresent() { final SoftwareModule module = testdataFactory.createSoftwareModuleApp(); - assertThat(softwareModuleManagement.get(1234L)).isNotPresent(); + assertThat(softwareModuleManagement.find(1234L)).isNotPresent(); final Long moduleId = module.getId(); assertThatExceptionOfType(EntityNotFoundException.class).isThrownBy(() -> softwareModuleManagement.getMetadata(moduleId, NOT_EXIST_ID)); } @@ -223,10 +224,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { // [VERIFY EXPECTED RESULT]: // verify: SoftwareModule is deleted assertThat(softwareModuleRepository.findAll()).isEmpty(); - assertThat(softwareModuleManagement.get(unassignedModule.getId())).isNotPresent(); + assertThat(softwareModuleManagement.find(unassignedModule.getId())).isNotPresent(); // verify: binary data of artifact is deleted - assertArtifactNull(artifact1, artifact2); + assertArtifactDoesntExist(artifact1, artifact2); // verify: metadata of artifact is deleted assertThat(artifactRepository.findById(artifact1.getId())).isNotPresent(); @@ -249,7 +250,7 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { // [VERIFY EXPECTED RESULT]: // verify: assignedModule is marked as deleted - assignedModule = softwareModuleManagement.get(assignedModule.getId()).get(); + assignedModule = softwareModuleManagement.find(assignedModule.getId()).get(); assertTrue(assignedModule.isDeleted(), "The module should be flagged as deleted"); assertThat(softwareModuleManagement.findAll(PAGE)).isEmpty(); assertThat(softwareModuleManagement.findByRsql("name==*", PAGE)).isEmpty(); @@ -260,7 +261,7 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { final Iterator artifactsIt = assignedModule.getArtifacts().iterator(); final Artifact artifact1 = artifactsIt.next(); final Artifact artifact2 = artifactsIt.next(); - assertArtifactNull(artifact1, artifact2); + assertArtifactDoesntExist(artifact1, artifact2); // verify: artifact meta data is still available assertThat(artifactRepository.findById(artifact1.getId())).isNotNull(); @@ -293,7 +294,7 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { // [VERIFY EXPECTED RESULT]: // verify: assignedModule is marked as deleted - assignedModule = softwareModuleManagement.get(assignedModule.getId()).get(); + assignedModule = softwareModuleManagement.find(assignedModule.getId()).get(); assertTrue(assignedModule.isDeleted(), "The found module should be flagged deleted"); assertThat(softwareModuleManagement.findAll(PAGE)).isEmpty(); assertThat(softwareModuleRepository.findAll()).hasSize(1); @@ -302,7 +303,7 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { final Iterator artifactsIt = assignedModule.getArtifacts().iterator(); final Artifact artifact1 = artifactsIt.next(); final Artifact artifact2 = artifactsIt.next(); - assertArtifactNull(artifact1, artifact2); + assertArtifactDoesntExist(artifact1, artifact2); // verify: artifact meta data is still available assertThat(artifactRepository.findById(artifact1.getId())).isNotNull(); @@ -325,7 +326,7 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { // [STEP2]: Create newArtifactX and add it to SoftwareModuleX artifactManagement.create(new ArtifactUpload(new ByteArrayInputStream(source), moduleX.getId(), "artifactx", false, artifactSize)); - moduleX = softwareModuleManagement.get(moduleX.getId()).get(); + moduleX = softwareModuleManagement.find(moduleX.getId()).get(); final Artifact artifactX = moduleX.getArtifacts().iterator().next(); // [STEP3]: Create SoftwareModuleY and add the same ArtifactX @@ -334,7 +335,7 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { // [STEP4]: Assign the same ArtifactX to SoftwareModuleY artifactManagement.create(new ArtifactUpload(new ByteArrayInputStream(source), moduleY.getId(), "artifactx", false, artifactSize)); - moduleY = softwareModuleManagement.get(moduleY.getId()).get(); + moduleY = softwareModuleManagement.find(moduleY.getId()).get(); final Artifact artifactY = moduleY.getArtifacts().iterator().next(); // [STEP5]: Delete SoftwareModuleX @@ -343,8 +344,8 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { // [VERIFY EXPECTED RESULT]: // verify: SoftwareModuleX is deleted, and ModuelY still exists assertThat(softwareModuleRepository.findAll()).hasSize(1); - assertThat(softwareModuleManagement.get(moduleX.getId())).isNotPresent(); - assertThat(softwareModuleManagement.get(moduleY.getId())).isPresent(); + assertThat(softwareModuleManagement.find(moduleX.getId())).isNotPresent(); + assertThat(softwareModuleManagement.find(moduleY.getId())).isPresent(); // verify: binary data of artifact is not deleted assertArtifactNotNull(artifactY); @@ -370,9 +371,8 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { // [STEP1]: Create SoftwareModuleX and add a new ArtifactX SoftwareModule moduleX = createSoftwareModuleWithArtifacts(osType, "modulex", "v1.0", 0); - artifactManagement.create(new ArtifactUpload(new ByteArrayInputStream(source), moduleX.getId(), "artifactx", - false, artifactSize)); - moduleX = softwareModuleManagement.get(moduleX.getId()).get(); + artifactManagement.create(new ArtifactUpload(new ByteArrayInputStream(source), moduleX.getId(), "artifactx", false, artifactSize)); + moduleX = softwareModuleManagement.find(moduleX.getId()).get(); final Artifact artifactX = moduleX.getArtifacts().iterator().next(); // [STEP2]: Create SoftwareModuleY and add the same ArtifactX @@ -380,7 +380,7 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { artifactManagement.create(new ArtifactUpload(new ByteArrayInputStream(source), moduleY.getId(), "artifactx", false, artifactSize)); - moduleY = softwareModuleManagement.get(moduleY.getId()).get(); + moduleY = softwareModuleManagement.find(moduleY.getId()).get(); final Artifact artifactY = moduleY.getArtifacts().iterator().next(); // [STEP3]: Assign SoftwareModuleX to DistributionSetX and to target @@ -400,8 +400,8 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { softwareModuleManagement.delete(moduleY.getId()); // [VERIFY EXPECTED RESULT]: - moduleX = softwareModuleManagement.get(moduleX.getId()).get(); - moduleY = softwareModuleManagement.get(moduleY.getId()).get(); + moduleX = softwareModuleManagement.find(moduleX.getId()).get(); + moduleY = softwareModuleManagement.find(moduleY.getId()).get(); // verify: SoftwareModuleX and SoftwareModule are marked as deleted assertThat(moduleX).isNotNull(); @@ -412,7 +412,7 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { assertThat(softwareModuleRepository.findAll()).hasSize(2); // verify: binary data of artifact is deleted - assertArtifactNull(artifactX, artifactY); + assertArtifactDoesntExist(artifactX, artifactY); // verify: meta data of artifactX and artifactY is not deleted assertThat(artifactRepository.findById(artifactY.getId())).isNotNull(); @@ -475,7 +475,7 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { knownKey1, new MetadataValueCreate(knownValue1, true), knownKey2, new MetadataValueCreate(knownValue2))); - final SoftwareModule changedLockRevisionModule = softwareModuleManagement.get(softwareModule.getId()).get(); + final SoftwareModule changedLockRevisionModule = softwareModuleManagement.find(softwareModule.getId()).get(); assertThat(changedLockRevisionModule.getOptLockRevision()).isEqualTo(2); assertThat(softwareModuleManagement.getMetadata(softwareModule.getId(), knownKey1)).satisfies(metadata -> { @@ -560,7 +560,7 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { // base software module should have now the opt lock revision one // because we are modifying the base software module - SoftwareModule changedLockRevisionModule = softwareModuleManagement.get(ah.getId()).get(); + SoftwareModule changedLockRevisionModule = softwareModuleManagement.find(ah.getId()).get(); assertThat(changedLockRevisionModule.getOptLockRevision()).isEqualTo(2); // update the software module metadata @@ -569,7 +569,7 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { // we are updating the sw metadata so also modifying the base software // module so opt lock revision must be two - changedLockRevisionModule = softwareModuleManagement.get(ah.getId()).get(); + changedLockRevisionModule = softwareModuleManagement.find(ah.getId()).get(); assertThat(changedLockRevisionModule.getOptLockRevision()).isEqualTo(3); // verify updated meta data contains the updated value @@ -638,9 +638,9 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { @Test void lockSoftwareModule() { final SoftwareModule softwareModule = testdataFactory.createSoftwareModule("sm-1"); - assertThat(softwareModuleManagement.get(softwareModule.getId()).map(SoftwareModule::isLocked).orElse(true)).isFalse(); + assertThat(softwareModuleManagement.find(softwareModule.getId()).map(SoftwareModule::isLocked).orElse(true)).isFalse(); softwareModuleManagement.lock(softwareModule); - assertThat(softwareModuleManagement.get(softwareModule.getId()).map(SoftwareModule::isLocked).orElse(false)).isTrue(); + assertThat(softwareModuleManagement.find(softwareModule.getId()).map(SoftwareModule::isLocked).orElse(false)).isTrue(); } /** @@ -650,9 +650,9 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { void unlockSoftwareModule() { SoftwareModule softwareModule = testdataFactory.createSoftwareModule("sm-1"); softwareModule = softwareModuleManagement.lock(softwareModule); - assertThat(softwareModuleManagement.get(softwareModule.getId()).map(SoftwareModule::isLocked).orElse(false)).isTrue(); + assertThat(softwareModuleManagement.find(softwareModule.getId()).map(SoftwareModule::isLocked).orElse(false)).isTrue(); softwareModule = softwareModuleManagement.unlock(softwareModule); - assertThat(softwareModuleManagement.get(softwareModule.getId()).map(SoftwareModule::isLocked).orElse(true)).isFalse(); + assertThat(softwareModuleManagement.find(softwareModule.getId()).map(SoftwareModule::isLocked).orElse(true)).isFalse(); } /** @@ -664,10 +664,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { final Long softwareModuleId = softwareModule.getId(); artifactManagement.create(new ArtifactUpload(new ByteArrayInputStream(new byte[] { 1 }), softwareModuleId, "artifact1", false, 1)); // update software module reference since it is modified, old reference is stale - final int artifactCount = (softwareModule = softwareModuleManagement.get(softwareModuleId).orElseThrow()).getArtifacts().size(); + final int artifactCount = (softwareModule = softwareModuleManagement.find(softwareModuleId).orElseThrow()).getArtifacts().size(); assertThat(artifactCount).isNotZero(); softwareModuleManagement.lock(softwareModule); - assertThat(softwareModuleManagement.get(softwareModuleId).map(SoftwareModule::isLocked).orElse(false)).isTrue(); + assertThat(softwareModuleManagement.find(softwareModuleId).map(SoftwareModule::isLocked).orElse(false)).isTrue(); // try add final ArtifactUpload artifactUpload = new ArtifactUpload(new ByteArrayInputStream(new byte[] { 2 }), softwareModuleId, "artifact2", @@ -675,21 +675,18 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { assertThatExceptionOfType(LockedException.class) .as("Attempt to modify a locked SM artifacts should throw an exception") .isThrownBy(() -> artifactManagement.create(artifactUpload)); - assertThat(softwareModuleManagement.get(softwareModuleId).get().getArtifacts()) + assertThat(softwareModuleManagement.find(softwareModuleId).get().getArtifacts()) .as("Artifacts shall not be added to a locked SM.") .hasSize(artifactCount); // try remove - final long artifactId = softwareModuleManagement.get(softwareModuleId).get().getArtifacts().stream().findFirst().get().getId(); + final long artifactId = softwareModuleManagement.find(softwareModuleId).get().getArtifacts().stream().findFirst().get().getId(); assertThatExceptionOfType(LockedException.class) .as("Attempt to modify a locked SM artifacts should throw an exception") .isThrownBy(() -> artifactManagement.delete(artifactId)); - assertThat(softwareModuleManagement.get(softwareModuleId).get().getArtifacts()) + assertThat(softwareModuleManagement.find(softwareModuleId).get().getArtifacts()) .as("Artifact shall not be removed from a locked SM.") .hasSize(artifactCount); - assertThat(artifactManagement.get(artifactId)) - .as("Artifact shall not be removed if belongs to a locked SM.") - .isPresent(); } /** @@ -705,7 +702,7 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { softwareModuleManagement.delete(modules.get(0).getId()); distributionSetManagement.lock(distributionSet); - assertThat(distributionSetManagement.get(distributionSet.getId()).map(DistributionSet::isLocked).orElse(false)).isTrue(); + assertThat(distributionSetManagement.find(distributionSet.getId()).map(DistributionSet::isLocked).orElse(false)).isTrue(); // try to delete SM of a locked DS final Long moduleId = modules.get(1).getId(); @@ -749,7 +746,7 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { } // Verify correct Creation of SoftwareModule and corresponding artifacts - softwareModule = softwareModuleManagement.get(softwareModule.getId()).get(); + softwareModule = softwareModuleManagement.find(softwareModule.getId()).get(); assertThat(softwareModuleRepository.findAll()).hasSize((int) countSoftwareModule + 1); final List artifacts = softwareModule.getArtifacts(); @@ -767,15 +764,17 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest { assertThat(artifactRepository.findAll()).hasSize(results.length); for (final Artifact result : results) { assertThat(result.getId()).isNotNull(); - assertThat(binaryArtifactRepository.getArtifactBySha1(tenantAware.getCurrentTenant(), result.getSha1Hash())) + assertThat(binaryArtifactRepository.getBySha1(tenantAware.getCurrentTenant(), result.getSha1Hash())) .isNotNull(); } } - private void assertArtifactNull(final Artifact... results) { + private void assertArtifactDoesntExist(final Artifact... results) { for (final Artifact result : results) { - assertThat(binaryArtifactRepository.getArtifactBySha1(tenantAware.getCurrentTenant(), result.getSha1Hash())) - .isNull(); + final String currentTenant = tenantAware.getCurrentTenant(); + final String sha1Hash = result.getSha1Hash(); + assertThatExceptionOfType(ArtifactBinaryNotFoundException.class) + .isThrownBy(() -> binaryArtifactRepository.getBySha1(currentTenant, sha1Hash)); } } } \ No newline at end of file diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/SoftwareModuleTypeManagementSecurityTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/SoftwareModuleTypeManagementSecurityTest.java index c37f6db00..82cc6c994 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/SoftwareModuleTypeManagementSecurityTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/SoftwareModuleTypeManagementSecurityTest.java @@ -27,17 +27,17 @@ class SoftwareModuleTypeManagementSecurityTest extends AbstractRepositoryManagementSecurityTest { @Override - protected RepositoryManagement getRepositoryManagement() { + protected RepositoryManagement findRepositoryManagement() { return softwareModuleTypeManagement; } @Override - protected SoftwareModuleTypeManagement.Create getCreateObject() { + protected SoftwareModuleTypeManagement.Create findCreateObject() { return SoftwareModuleTypeManagement.Create.builder().key(String.format("key-%d", new Random().nextInt())).name(String.format("name-%d", new Random().nextInt())).build(); } @Override - protected SoftwareModuleTypeManagement.Update getUpdateObject() { + protected SoftwareModuleTypeManagement.Update findUpdateObject() { return SoftwareModuleTypeManagement.Update.builder().id(1L).description("description").build(); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/SoftwareModuleTypeManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/SoftwareModuleTypeManagementTest.java index 7a2a2a201..5470fef5b 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/SoftwareModuleTypeManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/SoftwareModuleTypeManagementTest.java @@ -44,7 +44,7 @@ class SoftwareModuleTypeManagementTest extends AbstractJpaIntegrationTest { @ExpectEvents({ @Expect(type = SoftwareModuleCreatedEvent.class) }) void nonExistingEntityAccessReturnsNotPresent() { - assertThat(softwareModuleTypeManagement.get(NOT_EXIST_IDL)).isNotPresent(); + assertThat(softwareModuleTypeManagement.find(NOT_EXIST_IDL)).isNotPresent(); assertThat(softwareModuleTypeManagement.findByKey(NOT_EXIST_ID)).isNotPresent(); assertThat(softwareModuleTypeManagement.findByName(NOT_EXIST_ID)).isNotPresent(); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetFilterQueryManagementSecurityTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetFilterQueryManagementSecurityTest.java index 15761ee49..65657f640 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetFilterQueryManagementSecurityTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetFilterQueryManagementSecurityTest.java @@ -107,7 +107,7 @@ class TargetFilterQueryManagementSecurityTest extends AbstractJpaIntegrationTest */ @Test void getTargetFilterQueryByIdPermissionsCheck() { - assertPermissions(() -> targetFilterQueryManagement.get(1L), List.of(SpPermission.READ_TARGET)); + assertPermissions(() -> targetFilterQueryManagement.find(1L), List.of(SpPermission.READ_TARGET)); } /** diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetFilterQueryManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetFilterQueryManagementTest.java index 78a350ea1..5ad0ac508 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetFilterQueryManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetFilterQueryManagementTest.java @@ -69,7 +69,7 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest { @Test @ExpectEvents({ @Expect(type = TargetCreatedEvent.class) }) void nonExistingEntityAccessReturnsNotPresent() { - assertThat(targetFilterQueryManagement.get(NOT_EXIST_IDL)).isNotPresent(); + assertThat(targetFilterQueryManagement.find(NOT_EXIST_IDL)).isNotPresent(); } /** @@ -117,7 +117,7 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest { final String filterName = "new target filter"; final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement .create(Create.builder().name(filterName).query("name==PendingTargets001").build()); - assertEquals(targetFilterQuery, targetFilterQueryManagement.get(targetFilterQuery.getId()).get(), + assertEquals(targetFilterQuery, targetFilterQueryManagement.find(targetFilterQuery.getId()).get(), "Retrieved newly created custom target filter"); } @@ -191,7 +191,7 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest { Create.builder().name(filterName).query("name==PendingTargets001").build()); targetFilterQueryManagement.delete(targetFilterQuery.getId()); assertFalse( - targetFilterQueryManagement.get(targetFilterQuery.getId()).isPresent(), + targetFilterQueryManagement.find(targetFilterQuery.getId()).isPresent(), "Returns null as the target filter is deleted"); } @@ -206,7 +206,7 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest { final String newQuery = "name==PendingTargets002"; targetFilterQueryManagement.update(Update.builder().id(targetFilterQuery.getId()).query(newQuery).build()); - assertEquals(newQuery, targetFilterQueryManagement.get(targetFilterQuery.getId()).get().getQuery(), + assertEquals(newQuery, targetFilterQueryManagement.find(targetFilterQuery.getId()).get().getQuery(), "Returns updated target filter query"); } @@ -286,14 +286,14 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest { implicitLock(distributionSet); // Check if target filter query is there - TargetFilterQuery tfq = targetFilterQueryManagement.get(targetFilterQuery.getId()).get(); + TargetFilterQuery tfq = targetFilterQueryManagement.find(targetFilterQuery.getId()).get(); assertEquals(distributionSet, tfq.getAutoAssignDistributionSet(), "Returns correct distribution set"); assertEquals(ActionType.FORCED, tfq.getAutoAssignActionType(), "Return correct action type"); distributionSetManagement.delete(distributionSet.getId()); // Check if auto assign distribution set is null - tfq = targetFilterQueryManagement.get(targetFilterQuery.getId()).get(); + tfq = targetFilterQueryManagement.find(targetFilterQuery.getId()).get(); assertNotNull(tfq, "Returns target filter query"); assertNull(tfq.getAutoAssignDistributionSet(), "Returns distribution set as null"); assertNull(tfq.getAutoAssignActionType(), "Returns action type as null"); @@ -319,17 +319,17 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest { implicitLock(distributionSet); // Check if target filter query is there with the distribution set - TargetFilterQuery tfq = targetFilterQueryManagement.get(filterId).get(); + TargetFilterQuery tfq = targetFilterQueryManagement.find(filterId).get(); assertEquals(distributionSet, tfq.getAutoAssignDistributionSet(), "Returns correct distribution set"); assertEquals(ActionType.FORCED, tfq.getAutoAssignActionType(), "Return correct action type"); distributionSetManagement.delete(distributionSet.getId()); // Check if distribution set is still in the database with deleted flag - assertTrue(distributionSetManagement.get(distributionSet.getId()).get().isDeleted(), "Distribution set should be deleted"); + assertTrue(distributionSetManagement.find(distributionSet.getId()).get().isDeleted(), "Distribution set should be deleted"); // Check if auto assign distribution set is null - tfq = targetFilterQueryManagement.get(filterId).get(); + tfq = targetFilterQueryManagement.find(filterId).get(); assertNotNull(tfq, "Returns target filter query"); assertNull(tfq.getAutoAssignDistributionSet(), "Returns distribution set as null"); assertNull(tfq.getAutoAssignActionType(), "Returns action type as null"); @@ -431,7 +431,7 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest { final Long filterId = targetFilterQueryManagement.create(Create.builder().name("a") .query("name==*").autoAssignDistributionSet(ds).autoAssignWeight(Action.WEIGHT_MAX).build()).getId(); - assertThat(targetFilterQueryManagement.get(filterId).get().getAutoAssignWeight()).contains(Action.WEIGHT_MAX); + assertThat(targetFilterQueryManagement.find(filterId).get().getAutoAssignWeight()).contains(Action.WEIGHT_MAX); final AutoAssignDistributionSetUpdate autoAssignDistributionSetUpdate = new AutoAssignDistributionSetUpdate(filterId) .ds(ds.getId()).weight(Action.WEIGHT_MAX + 1); @@ -445,7 +445,7 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest { new AutoAssignDistributionSetUpdate(filterId).ds(ds.getId()).weight(Action.WEIGHT_MAX)); targetFilterQueryManagement.updateAutoAssignDS( new AutoAssignDistributionSetUpdate(filterId).ds(ds.getId()).weight(Action.WEIGHT_MIN)); - assertThat(targetFilterQueryManagement.get(filterId).get().getAutoAssignWeight()).contains(Action.WEIGHT_MIN); + assertThat(targetFilterQueryManagement.find(filterId).get().getAutoAssignWeight()).contains(Action.WEIGHT_MIN); } /** @@ -531,7 +531,7 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest { if (actionType == ActionType.TIMEFORCED) { assertThatExceptionOfType(AbstractServerRtException.class).isThrownBy(create::get); } else { - assertThat(targetFilterQueryManagement.get(create.get()).orElseThrow().getAutoAssignActionType()).isEqualTo(actionType); + assertThat(targetFilterQueryManagement.find(create.get()).orElseThrow().getAutoAssignActionType()).isEqualTo(actionType); } } @@ -626,7 +626,7 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest { } private void verifyAutoAssignDsAndActionType(final Long filterId, final DistributionSet distributionSet, final ActionType actionType) { - final TargetFilterQuery tfq = targetFilterQueryManagement.get(filterId).get(); + final TargetFilterQuery tfq = targetFilterQueryManagement.find(filterId).get(); assertEquals(distributionSet, tfq.getAutoAssignDistributionSet(), "Returns correct distribution set"); assertEquals(actionType, tfq.getAutoAssignActionType(), "Return correct action type"); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetManagementSecurityTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetManagementSecurityTest.java index d0bfe9ffc..5411abe91 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetManagementSecurityTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetManagementSecurityTest.java @@ -322,7 +322,7 @@ class TargetManagementSecurityTest extends AbstractJpaIntegrationTest { */ @Test void getPermissionsCheck() { - assertPermissions(() -> targetManagement.get(1L), List.of(SpPermission.READ_TARGET)); + assertPermissions(() -> targetManagement.find(1L), List.of(SpPermission.READ_TARGET)); } /** diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetManagementTest.java index efd031f72..9eb836173 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetManagementTest.java @@ -108,7 +108,7 @@ class TargetManagementTest extends AbstractJpaIntegrationTest { void nonExistingEntityAccessReturnsNotPresent() { final Target target = testdataFactory.createTarget(); assertThat(targetManagement.getByControllerId(NOT_EXIST_ID)).isNotPresent(); - assertThat(targetManagement.get(NOT_EXIST_IDL)).isNotPresent(); + assertThat(targetManagement.find(NOT_EXIST_IDL)).isNotPresent(); assertThat(targetManagement.getMetadata(target.getControllerId()).get(NOT_EXIST_ID)).isNull(); } @@ -252,14 +252,14 @@ class TargetManagementTest extends AbstractJpaIntegrationTest { assertThat(assignedTargets).as("Assigned targets are wrong").hasSize(4); assignedTargets.forEach(target -> assertThat(getTargetTags(target.getControllerId())).hasSize(1)); - final TargetTag findTargetTag = targetTagManagement.get(targetTag.getId()).orElseThrow(IllegalStateException::new); + final TargetTag findTargetTag = targetTagManagement.find(targetTag.getId()).orElseThrow(IllegalStateException::new); assertThat(assignedTargets).as("Assigned targets are wrong") .hasSize(targetManagement.findByTag(targetTag.getId(), PAGE).getNumberOfElements()); final Target unAssignTarget = targetManagement.unassignTag(List.of("targetId123"), findTargetTag.getId()).get(0); assertThat(unAssignTarget.getControllerId()).as("Controller id is wrong").isEqualTo("targetId123"); assertThat(getTargetTags(unAssignTarget.getControllerId())).as("Tag size is wrong").isEmpty(); - targetTagManagement.get(targetTag.getId()).orElseThrow(NoSuchElementException::new); + targetTagManagement.find(targetTag.getId()).orElseThrow(NoSuchElementException::new); assertThat(targetManagement.findByTag(targetTag.getId(), PAGE)).as("Assigned targets are wrong").hasSize(3); assertThat(targetManagement.findByRsqlAndTag("controllerId==targetId123", targetTag.getId(), PAGE)) .as("Assigned targets are wrong").isEmpty(); @@ -812,13 +812,13 @@ class TargetManagementTest extends AbstractJpaIntegrationTest { // create target meta data entry insertMetadata(knownKey, knownValue, target); - final Target changedLockRevisionTarget = targetManagement.get(target.getId()).orElseThrow(NoSuchElementException::new); + final Target changedLockRevisionTarget = targetManagement.find(target.getId()).orElseThrow(NoSuchElementException::new); assertThat(changedLockRevisionTarget.getOptLockRevision()).isEqualTo(2); // update the target metadata targetManagement.createMetadata(target.getControllerId(), knownKey, knownUpdateValue); // we are updating the target meta-data so also modifying the target so opt lock revision must be three - final Target changedLockRevisionTarget2 = targetManagement.get(target.getId()).orElseThrow(NoSuchElementException::new); + final Target changedLockRevisionTarget2 = targetManagement.find(target.getId()).orElseThrow(NoSuchElementException::new); assertThat(changedLockRevisionTarget2.getOptLockRevision()).isEqualTo(3); assertThat(changedLockRevisionTarget2.getLastModifiedAt()).isPositive(); diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetTagManagementSecurityTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetTagManagementSecurityTest.java index cdbf5e3c1..f7a9b31ae 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetTagManagementSecurityTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetTagManagementSecurityTest.java @@ -84,7 +84,7 @@ class TargetTagManagementSecurityTest extends AbstractJpaIntegrationTest { */ @Test void getPermissionsCheck() { - assertPermissions(() -> targetTagManagement.get(1L), List.of(SpPermission.READ_TARGET)); + assertPermissions(() -> targetTagManagement.find(1L), List.of(SpPermission.READ_TARGET)); } /** diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetTagManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetTagManagementTest.java index f5736ef6a..fad9c4f70 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetTagManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetTagManagementTest.java @@ -91,7 +91,7 @@ class TargetTagManagementTest extends AbstractJpaIntegrationTest { @Test @ExpectEvents({ @Expect(type = TargetCreatedEvent.class) }) void nonExistingEntityAccessReturnsNotPresent() { - assertThat(targetTagManagement.get(NOT_EXIST_IDL)).isNotPresent(); + assertThat(targetTagManagement.find(NOT_EXIST_IDL)).isNotPresent(); } /** @@ -175,7 +175,7 @@ class TargetTagManagementTest extends AbstractJpaIntegrationTest { @Test void createTargetTag() { final Tag tag = targetTagManagement.create(Create.builder().name("k1").description("k2").colour("colour").build()); - assertThat(targetTagManagement.get(tag.getId()).orElseThrow().getColour()).as("wrong tag found").isEqualTo("colour"); + assertThat(targetTagManagement.find(tag.getId()).orElseThrow().getColour()).as("wrong tag found").isEqualTo("colour"); } /** diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetTypeManagementSecurityTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetTypeManagementSecurityTest.java index 60045af93..ae1c94e25 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetTypeManagementSecurityTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetTypeManagementSecurityTest.java @@ -13,7 +13,6 @@ import java.util.List; import lombok.extern.slf4j.Slf4j; import org.eclipse.hawkbit.im.authentication.SpPermission; -import org.eclipse.hawkbit.repository.TargetTypeManagement; import org.eclipse.hawkbit.repository.TargetTypeManagement.Create; import org.eclipse.hawkbit.repository.TargetTypeManagement.Update; import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest; @@ -101,7 +100,7 @@ class TargetTypeManagementSecurityTest extends AbstractJpaIntegrationTest { */ @Test void getPermissionsCheck() { - assertPermissions(() -> targetTypeManagement.get(1L), List.of(SpPermission.READ_TARGET)); + assertPermissions(() -> targetTypeManagement.find(1L), List.of(SpPermission.READ_TARGET)); } /** diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetTypeManagementTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetTypeManagementTest.java index 23363a92a..0970c7495 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetTypeManagementTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/management/TargetTypeManagementTest.java @@ -46,7 +46,7 @@ class TargetTypeManagementTest extends AbstractJpaIntegrationTest { @Test @ExpectEvents({ @Expect(type = TargetTypeCreatedEvent.class) }) void nonExistingEntityAccessReturnsNotPresent() { - assertThat(targetTypeManagement.get(NOT_EXIST_IDL)).isNotPresent(); + assertThat(targetTypeManagement.find(NOT_EXIST_IDL)).isNotPresent(); assertThat(targetTypeManagement.getByName(NOT_EXIST_ID)).isNotPresent(); } diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RsqlRolloutFieldTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RsqlRolloutFieldTest.java index 7c32c2408..a749dda70 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RsqlRolloutFieldTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RsqlRolloutFieldTest.java @@ -36,7 +36,7 @@ class RsqlRolloutFieldTest extends AbstractJpaIntegrationTest { testdataFactory.createTargets(20, "rollout", "rollout"); final DistributionSet dsA = testdataFactory.createDistributionSet(""); rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*"); - rollout = rolloutManagement.get(rollout.getId()).get(); + rollout = rolloutManagement.find(rollout.getId()).get(); } /** @@ -60,7 +60,7 @@ class RsqlRolloutFieldTest extends AbstractJpaIntegrationTest { private Rollout createRollout(final String name, final int amountGroups, final long distributionSetId, final String targetFilterQuery) { return rolloutManagement.create( Create.builder() - .distributionSet(distributionSetManagement.get(distributionSetId).get()).name(name).targetFilterQuery(targetFilterQuery) + .distributionSet(distributionSetManagement.find(distributionSetId).get()).name(name).targetFilterQuery(targetFilterQuery) .build(), amountGroups, false, diff --git a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RsqlRolloutGroupFieldTest.java b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RsqlRolloutGroupFieldTest.java index eb4b9c9cc..ed80790de 100644 --- a/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RsqlRolloutGroupFieldTest.java +++ b/hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/rsql/RsqlRolloutGroupFieldTest.java @@ -40,7 +40,7 @@ class RsqlRolloutGroupFieldTest extends AbstractJpaIntegrationTest { testdataFactory.createTargets(amountTargets, "rollout", "rollout"); final DistributionSet dsA = testdataFactory.createDistributionSet(""); rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*"); - rollout = rolloutManagement.get(rollout.getId()).get(); + rollout = rolloutManagement.find(rollout.getId()).get(); this.rolloutGroupId = rolloutGroupManagement.findByRollout(rollout.getId(), PAGE).getContent().get(0).getId(); } @@ -102,7 +102,7 @@ class RsqlRolloutGroupFieldTest extends AbstractJpaIntegrationTest { final String targetFilterQuery) { return rolloutManagement.create( Create.builder() - .distributionSet(distributionSetManagement.get(distributionSetId).get()).name(name).targetFilterQuery(targetFilterQuery) + .distributionSet(distributionSetManagement.find(distributionSetId).get()).name(name).targetFilterQuery(targetFilterQuery) .build(), amountGroups, false, new RolloutGroupConditionBuilder().withDefaults() .successCondition(RolloutGroupSuccessCondition.THRESHOLD, "100").build()); 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 e4df9a897..9485d5486 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 @@ -393,7 +393,7 @@ public class TestdataFactory { public DistributionSet createDistributionSet(final String prefix, final String version, final Collection tags) { final DistributionSet set = createDistributionSet(prefix, version, false); tags.forEach(tag -> distributionSetManagement.assignTag(List.of(set.getId()), tag.getId())); - return distributionSetManagement.get(set.getId()).orElseThrow(); + return distributionSetManagement.find(set.getId()).orElseThrow(); } /** @@ -1053,7 +1053,7 @@ public class TestdataFactory { // Run here, because Scheduler is disabled during tests rolloutHandleAll(); - return rolloutManagement.get(rollout.getId()).orElseThrow(); + return rolloutManagement.find(rollout.getId()).orElseThrow(); } /** @@ -1226,7 +1226,7 @@ public class TestdataFactory { final DistributionSet distributionSet = createDistributionSet(); distributionSetInvalidationManagement.invalidateDistributionSet( new DistributionSetInvalidation(List.of(distributionSet.getId()), ActionCancellationType.NONE)); - return distributionSetManagement.get(distributionSet.getId()).orElseThrow(); + return distributionSetManagement.find(distributionSet.getId()).orElseThrow(); } /** @@ -1298,6 +1298,6 @@ public class TestdataFactory { } private Rollout reloadRollout(final Rollout rollout) { - return rolloutManagement.get(rollout.getId()).orElseThrow(NoSuchElementException::new); + return rolloutManagement.find(rollout.getId()).orElseThrow(NoSuchElementException::new); } } \ No newline at end of file