20250828 cleanup (#2639)

* Cleanup

* Refactor artifact management
This commit is contained in:
Avgustin Marinov
2025-09-02 16:08:14 +03:00
committed by GitHub
parent 4f0a8893c7
commit 2a636328a0
305 changed files with 2253 additions and 4566 deletions

View File

@@ -1,66 +0,0 @@
/**
* Copyright (c) 2021 Bosch.IO GmbH and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.hawkbit.repository.jpa;
import java.io.InputStream;
import java.util.function.UnaryOperator;
import org.eclipse.hawkbit.repository.artifact.model.DbArtifact;
import org.eclipse.hawkbit.repository.artifact.model.DbArtifactHash;
/**
* {@link DbArtifact} implementation that decrypts the underlying artifact
* binary input stream.
*/
public class EncryptionAwareDbArtifact implements DbArtifact {
private final DbArtifact encryptedDbArtifact;
private final UnaryOperator<InputStream> decryptionFunction;
private final int encryptionOverhead;
public EncryptionAwareDbArtifact(final DbArtifact encryptedDbArtifact,
final UnaryOperator<InputStream> decryptionFunction) {
this.encryptedDbArtifact = encryptedDbArtifact;
this.decryptionFunction = decryptionFunction;
this.encryptionOverhead = 0;
}
public EncryptionAwareDbArtifact(final DbArtifact encryptedDbArtifact,
final UnaryOperator<InputStream> decryptionFunction, final int encryptionOverhead) {
this.encryptedDbArtifact = encryptedDbArtifact;
this.decryptionFunction = decryptionFunction;
this.encryptionOverhead = encryptionOverhead;
}
@Override
public String getArtifactId() {
return encryptedDbArtifact.getArtifactId();
}
@Override
public DbArtifactHash getHashes() {
return encryptedDbArtifact.getHashes();
}
@Override
public long getSize() {
return encryptedDbArtifact.getSize() - encryptionOverhead;
}
@Override
public String getContentType() {
return encryptedDbArtifact.getContentType();
}
@Override
public InputStream getFileInputStream() {
return decryptionFunction.apply(encryptedDbArtifact.getFileInputStream());
}
}

View File

@@ -20,6 +20,9 @@ import jakarta.validation.Validation;
import io.micrometer.core.instrument.MeterRegistry;
import org.aopalliance.intercept.MethodInvocation;
import org.eclipse.hawkbit.ContextAware;
import org.eclipse.hawkbit.artifact.encryption.ArtifactEncryption;
import org.eclipse.hawkbit.artifact.encryption.ArtifactEncryptionSecretsStorage;
import org.eclipse.hawkbit.artifact.encryption.ArtifactEncryptionService;
import org.eclipse.hawkbit.repository.DeploymentManagement;
import org.eclipse.hawkbit.repository.PropertiesQuotaManagement;
import org.eclipse.hawkbit.repository.QuotaManagement;
@@ -31,13 +34,11 @@ import org.eclipse.hawkbit.repository.RolloutGroupManagement;
import org.eclipse.hawkbit.repository.RolloutHandler;
import org.eclipse.hawkbit.repository.RolloutManagement;
import org.eclipse.hawkbit.repository.RolloutStatusCache;
import org.eclipse.hawkbit.repository.SecurityTokenGeneratorHolder;
import org.eclipse.hawkbit.repository.SystemManagement;
import org.eclipse.hawkbit.repository.TargetFilterQueryManagement;
import org.eclipse.hawkbit.repository.TargetManagement;
import org.eclipse.hawkbit.repository.TenantConfigurationManagement;
import org.eclipse.hawkbit.repository.artifact.encryption.ArtifactEncryption;
import org.eclipse.hawkbit.repository.artifact.encryption.ArtifactEncryptionSecretsStore;
import org.eclipse.hawkbit.repository.artifact.encryption.ArtifactEncryptionService;
import org.eclipse.hawkbit.repository.autoassign.AutoAssignExecutor;
import org.eclipse.hawkbit.repository.event.ApplicationEventFilter;
import org.eclipse.hawkbit.repository.event.remote.EventEntityManager;
@@ -55,7 +56,6 @@ import org.eclipse.hawkbit.repository.jpa.cluster.LockProperties;
import org.eclipse.hawkbit.repository.jpa.event.JpaEventEntityManager;
import org.eclipse.hawkbit.repository.jpa.executor.AfterTransactionCommitDefaultServiceExecutor;
import org.eclipse.hawkbit.repository.jpa.executor.AfterTransactionCommitExecutor;
import org.eclipse.hawkbit.repository.jpa.utils.ExceptionMapper;
import org.eclipse.hawkbit.repository.jpa.model.JpaAction;
import org.eclipse.hawkbit.repository.jpa.model.JpaArtifact;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
@@ -66,7 +66,6 @@ import org.eclipse.hawkbit.repository.jpa.model.JpaTarget;
import org.eclipse.hawkbit.repository.jpa.model.JpaTargetType;
import org.eclipse.hawkbit.repository.jpa.model.helper.AfterTransactionCommitExecutorHolder;
import org.eclipse.hawkbit.repository.jpa.model.helper.EntityInterceptorHolder;
import org.eclipse.hawkbit.repository.SecurityTokenGeneratorHolder;
import org.eclipse.hawkbit.repository.jpa.model.helper.TenantAwareHolder;
import org.eclipse.hawkbit.repository.jpa.repository.ActionRepository;
import org.eclipse.hawkbit.repository.jpa.repository.DistributionSetRepository;
@@ -88,6 +87,7 @@ import org.eclipse.hawkbit.repository.jpa.rollout.condition.StartNextGroupRollou
import org.eclipse.hawkbit.repository.jpa.rollout.condition.ThresholdRolloutGroupErrorCondition;
import org.eclipse.hawkbit.repository.jpa.rollout.condition.ThresholdRolloutGroupSuccessCondition;
import org.eclipse.hawkbit.repository.jpa.rsql.RsqlUtility;
import org.eclipse.hawkbit.repository.jpa.utils.ExceptionMapper;
import org.eclipse.hawkbit.repository.model.RolloutGroup;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.Target;
@@ -525,7 +525,7 @@ public class JpaRepositoryConfiguration {
/**
* Default artifact encryption service bean that internally uses {@link ArtifactEncryption} and
* {@link ArtifactEncryptionSecretsStore} beans for {@link SoftwareModule} artifacts encryption/decryption
* {@link ArtifactEncryptionSecretsStorage} beans for {@link SoftwareModule} artifacts encryption/decryption
*
* @return a {@link ArtifactEncryptionService} bean
*/

View File

@@ -16,23 +16,22 @@ import java.util.Optional;
import jakarta.persistence.EntityManager;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.artifact.ArtifactStorage;
import org.eclipse.hawkbit.artifact.encryption.ArtifactEncryptionService;
import org.eclipse.hawkbit.artifact.exception.ArtifactBinaryNotFoundException;
import org.eclipse.hawkbit.artifact.exception.ArtifactDeleteFailedException;
import org.eclipse.hawkbit.artifact.exception.ArtifactStoreException;
import org.eclipse.hawkbit.artifact.exception.ArtifactUploadFailedException;
import org.eclipse.hawkbit.artifact.exception.HashNotMatchException;
import org.eclipse.hawkbit.artifact.model.ArtifactHashes;
import org.eclipse.hawkbit.artifact.model.ArtifactStream;
import org.eclipse.hawkbit.artifact.model.StoredArtifactInfo;
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.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.exception.InvalidMD5HashException;
import org.eclipse.hawkbit.repository.exception.InvalidSHA1HashException;
import org.eclipse.hawkbit.repository.exception.InvalidSHA256HashException;
import org.eclipse.hawkbit.repository.jpa.EncryptionAwareDbArtifact;
import org.eclipse.hawkbit.repository.exception.InvalidMd5HashException;
import org.eclipse.hawkbit.repository.exception.InvalidSha1HashException;
import org.eclipse.hawkbit.repository.exception.InvalidSha256HashException;
import org.eclipse.hawkbit.repository.jpa.JpaManagementHelper;
import org.eclipse.hawkbit.repository.jpa.acm.AccessController;
import org.eclipse.hawkbit.repository.jpa.configuration.Constants;
@@ -69,7 +68,7 @@ import org.springframework.validation.annotation.Validated;
public class JpaArtifactManagement implements ArtifactManagement {
private final LocalArtifactRepository localArtifactRepository;
private final ArtifactRepository artifactRepository;
private final ArtifactStorage artifactRepository;
private final SoftwareModuleRepository softwareModuleRepository;
private final EntityManager entityManager;
private final PlatformTransactionManager txManager;
@@ -78,7 +77,7 @@ public class JpaArtifactManagement implements ArtifactManagement {
protected JpaArtifactManagement(
final LocalArtifactRepository localArtifactRepository,
final Optional<ArtifactRepository> artifactRepository,
final Optional<ArtifactStorage> artifactRepository,
final SoftwareModuleRepository softwareModuleRepository,
final EntityManager entityManager,
final PlatformTransactionManager txManager,
@@ -102,42 +101,40 @@ public class JpaArtifactManagement implements ArtifactManagement {
throw new UnsupportedOperationException();
}
final long moduleId = artifactUpload.getModuleId();
final long moduleId = artifactUpload.moduleId();
QuotaHelper.assertAssignmentQuota(
moduleId, 1, quotaManagement.getMaxArtifactsPerSoftwareModule(),
Artifact.class, SoftwareModule.class,
// get all artifacts without user context
softwareModuleId -> localArtifactRepository
.count(null, ArtifactSpecifications.bySoftwareModuleId(softwareModuleId)));
softwareModuleId -> localArtifactRepository.count(null, ArtifactSpecifications.bySoftwareModuleId(softwareModuleId)));
final JpaSoftwareModule softwareModule = softwareModuleRepository.getById(moduleId);
final String filename = artifactUpload.getFilename();
final String filename = artifactUpload.filename();
final Artifact existing = softwareModule.getArtifactByFilename(filename).orElse(null);
if (existing != null) {
if (artifactUpload.isOverrideExisting()) {
if (artifactUpload.overrideExisting()) {
log.debug("overriding existing artifact with new filename {}", filename);
} else {
throw new EntityAlreadyExistsException("File with that name already exists in the Software Module");
}
}
// touch it to update the lock revision because we are modifying the
// DS indirectly, it will, also check UPDATE access
// touch it to update the lock revision because we are modifying the DS indirectly, it will, also check UPDATE access
JpaManagementHelper.touch(entityManager, softwareModuleRepository, softwareModule);
final AbstractDbArtifact artifact = storeArtifact(artifactUpload, softwareModule.isEncrypted());
final StoredArtifactInfo artifact = storeArtifact(artifactUpload, softwareModule.isEncrypted());
try {
return storeArtifactMetadata(softwareModule, filename, artifact, existing);
return storeArtifactMetadata(softwareModule, filename, artifact.getHashes(), artifact.getSize(), existing);
} catch (final Exception e) {
artifactRepository.deleteBySha1(tenantAware.getCurrentTenant(), artifact.getHashes().getSha1());
artifactRepository.deleteBySha1(tenantAware.getCurrentTenant(), artifact.getHashes().sha1());
throw e;
}
}
@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) {
public ArtifactStream getArtifactStream(final String sha1Hash, final long softwareModuleId, final boolean isEncrypted) {
if (artifactRepository == null) {
throw new UnsupportedOperationException();
}
@@ -146,8 +143,15 @@ public class JpaArtifactManagement implements ArtifactManagement {
// 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;
if (isEncrypted) {
final ArtifactEncryptionService encryptionService = ArtifactEncryptionService.getInstance();
return new ArtifactStream(
encryptionService.decryptArtifact(softwareModuleId, artifactRepository.getBySha1(tenant, sha1Hash)),
artifact.getSize() - encryptionService.encryptionSizeOverhead(),
artifact.getSha1Hash());
} else {
return new ArtifactStream(artifactRepository.getBySha1(tenant, sha1Hash), artifact.getSize(), artifact.getSha1Hash());
}
}
}
throw new ArtifactBinaryNotFoundException(sha1Hash);
@@ -208,27 +212,23 @@ public class JpaArtifactManagement implements ArtifactManagement {
});
}
private AbstractDbArtifact storeArtifact(final ArtifactUpload artifactUpload, final boolean isSmEncrypted) {
final InputStream stream = artifactUpload.getInputStream();
private StoredArtifactInfo storeArtifact(final ArtifactUpload artifactUpload, final boolean isSmEncrypted) {
final InputStream stream = artifactUpload.inputStream();
try (final InputStream wrappedStream = wrapInQuotaStream(
isSmEncrypted
? wrapInEncryptionStream(artifactUpload.getModuleId(), stream)
: stream)) {
isSmEncrypted ? wrapInEncryptionStream(artifactUpload.moduleId(), stream) : stream)) {
return artifactRepository.store(
tenantAware.getCurrentTenant(), wrappedStream, artifactUpload.getFilename(), artifactUpload.getContentType(),
new DbArtifactHash(
artifactUpload.getProvidedSha1Sum(),
artifactUpload.getProvidedMd5Sum(),
artifactUpload.getProvidedSha256Sum()));
tenantAware.getCurrentTenant(),
wrappedStream, artifactUpload.filename(),
artifactUpload.contentType(), artifactUpload.hash());
} catch (final ArtifactStoreException | IOException e) {
throw new ArtifactUploadFailedException(e);
} catch (final HashNotMatchException e) {
if (e.getHashFunction().equals(HashNotMatchException.SHA1)) {
throw new InvalidSHA1HashException(e.getMessage(), e);
throw new InvalidSha1HashException(e.getMessage(), e);
} else if (e.getHashFunction().equals(HashNotMatchException.SHA256)) {
throw new InvalidSHA256HashException(e.getMessage(), e);
throw new InvalidSha256HashException(e.getMessage(), e);
} else {
throw new InvalidMD5HashException(e.getMessage(), e);
throw new InvalidMd5HashException(e.getMessage(), e);
}
}
}
@@ -243,33 +243,23 @@ public class JpaArtifactManagement implements ArtifactManagement {
final long currentlyUsed = localArtifactRepository.sumOfNonDeletedArtifactSize().orElse(0L);
final long maxArtifactSizeTotal = quotaManagement.getMaxArtifactStorage();
return new FileSizeAndStorageQuotaCheckingInputStream(in, maxArtifactSize,
maxArtifactSizeTotal - currentlyUsed);
}
private DbArtifact wrapInEncryptionAwareDbArtifact(final long softwareModuleId, final DbArtifact dbArtifact) {
if (dbArtifact == null) {
return null;
}
final ArtifactEncryptionService encryptionService = ArtifactEncryptionService.getInstance();
return new EncryptionAwareDbArtifact(dbArtifact,
stream -> encryptionService.decryptArtifact(softwareModuleId, stream),
encryptionService.encryptionSizeOverhead());
return new FileSizeAndStorageQuotaCheckingInputStream(in, maxArtifactSize, maxArtifactSizeTotal - currentlyUsed);
}
private Artifact storeArtifactMetadata(
final SoftwareModule softwareModule, final String providedFilename, final AbstractDbArtifact result,
final SoftwareModule softwareModule, final String providedFilename,
final ArtifactHashes hash, final long fileSize,
final Artifact existing) {
final JpaArtifact artifact;
if (existing == null) {
artifact = new JpaArtifact(result.getHashes().getSha1(), providedFilename, softwareModule);
artifact = new JpaArtifact(hash.sha1(), providedFilename, softwareModule);
} else {
artifact = (JpaArtifact) existing;
artifact.setSha1Hash(result.getHashes().getSha1());
artifact.setSha1Hash(hash.sha1());
}
artifact.setMd5Hash(result.getHashes().getMd5());
artifact.setSha256Hash(result.getHashes().getSha256());
artifact.setFileSize(result.getSize());
artifact.setMd5Hash(hash.md5());
artifact.setSha256Hash(hash.sha256());
artifact.setFileSize(fileSize);
log.debug("storing new artifact into repository {}", artifact);
return localArtifactRepository.save(AccessController.Operation.CREATE, artifact);

View File

@@ -146,7 +146,7 @@ public class JpaConfirmationManagement extends JpaActionManagement implements Co
}
@Override
public Optional<AutoConfirmationStatus> getStatus(final String controllerId) {
public Optional<AutoConfirmationStatus> findStatus(final String controllerId) {
return Optional.of(targetRepository.getWithDetailsByControllerId(controllerId, JpaTarget_.GRAPH_TARGET_AUTO_CONFIRMATION_STATUS))
.map(JpaTarget::getAutoConfirmationStatus);
}

View File

@@ -55,7 +55,6 @@ import org.eclipse.hawkbit.repository.RepositoryConstants;
import org.eclipse.hawkbit.repository.RepositoryProperties;
import org.eclipse.hawkbit.repository.SecurityTokenGeneratorHolder;
import org.eclipse.hawkbit.repository.SoftwareModuleManagement;
import org.eclipse.hawkbit.repository.TargetTypeManagement;
import org.eclipse.hawkbit.repository.TenantConfigurationManagement;
import org.eclipse.hawkbit.repository.UpdateMode;
import org.eclipse.hawkbit.repository.event.EventPublisherHolder;
@@ -66,6 +65,7 @@ import org.eclipse.hawkbit.repository.exception.CancelActionNotAllowedException;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.InvalidTargetAttributeException;
import org.eclipse.hawkbit.repository.exception.SoftwareModuleNotAssignedToTargetException;
import org.eclipse.hawkbit.repository.jpa.Jpa;
import org.eclipse.hawkbit.repository.jpa.acm.AccessController;
import org.eclipse.hawkbit.repository.jpa.configuration.Constants;
@@ -83,8 +83,10 @@ import org.eclipse.hawkbit.repository.jpa.repository.ActionRepository;
import org.eclipse.hawkbit.repository.jpa.repository.ActionStatusRepository;
import org.eclipse.hawkbit.repository.jpa.repository.SoftwareModuleRepository;
import org.eclipse.hawkbit.repository.jpa.repository.TargetRepository;
import org.eclipse.hawkbit.repository.jpa.repository.TargetTypeRepository;
import org.eclipse.hawkbit.repository.jpa.specifications.ActionSpecifications;
import org.eclipse.hawkbit.repository.jpa.specifications.TargetSpecifications;
import org.eclipse.hawkbit.repository.jpa.specifications.TargetTypeSpecification;
import org.eclipse.hawkbit.repository.jpa.utils.DeploymentHelper;
import org.eclipse.hawkbit.repository.jpa.utils.QuotaHelper;
import org.eclipse.hawkbit.repository.model.Action;
@@ -138,7 +140,7 @@ public class JpaControllerManagement extends JpaActionManagement implements Cont
// TODO - make it final
private TargetRepository targetRepository;
private final TargetTypeManagement<? extends TargetType> targetTypeManagement;
private final TargetTypeRepository targetTypeRepository;
private final DeploymentManagement deploymentManagement;
private final ConfirmationManagement confirmationManagement;
private final SoftwareModuleRepository softwareModuleRepository;
@@ -158,7 +160,7 @@ public class JpaControllerManagement extends JpaActionManagement implements Cont
protected JpaControllerManagement(
final ActionRepository actionRepository, final ActionStatusRepository actionStatusRepository, final QuotaManagement quotaManagement,
final RepositoryProperties repositoryProperties,
final TargetRepository targetRepository, final TargetTypeManagement<? extends TargetType> targetTypeManagement,
final TargetRepository targetRepository, final TargetTypeRepository targetTypeRepository,
final DeploymentManagement deploymentManagement, final ConfirmationManagement confirmationManagement,
final SoftwareModuleRepository softwareModuleRepository,
final SoftwareModuleManagement<? extends SoftwareModule> softwareModuleManagement,
@@ -171,7 +173,7 @@ public class JpaControllerManagement extends JpaActionManagement implements Cont
super(actionRepository, actionStatusRepository, quotaManagement, repositoryProperties);
this.targetRepository = targetRepository;
this.targetTypeManagement = targetTypeManagement;
this.targetTypeRepository = targetTypeRepository;
this.deploymentManagement = deploymentManagement;
this.confirmationManagement = confirmationManagement;
this.softwareModuleRepository = softwareModuleRepository;
@@ -270,8 +272,9 @@ public class JpaControllerManagement extends JpaActionManagement implements Cont
}
@Override
public Optional<SoftwareModule> getSoftwareModule(final long id) {
return softwareModuleRepository.findById(id).map(SoftwareModule.class::cast);
public SoftwareModule getSoftwareModule(final long id) {
return softwareModuleRepository.findById(id).map(SoftwareModule.class::cast)
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, id));
}
@Override
@@ -360,7 +363,7 @@ public class JpaControllerManagement extends JpaActionManagement implements Cont
}
@Override
public Optional<Action> getActionForDownloadByTargetAndSoftwareModule(final String controllerId, final long moduleId) {
public Action getActionForDownloadByTargetAndSoftwareModule(final String controllerId, final long moduleId) {
throwExceptionIfTargetDoesNotExist(controllerId);
throwExceptionIfSoftwareModuleDoesNotExist(moduleId);
@@ -376,7 +379,8 @@ public class JpaControllerManagement extends JpaActionManagement implements Cont
.stream()
.anyMatch(module -> module.getId() == moduleId))
.map(Action.class::cast)
.findFirst();
.findFirst()
.orElseThrow(() -> new SoftwareModuleNotAssignedToTargetException(moduleId, controllerId));
}
@Override
@@ -542,11 +546,6 @@ public class JpaControllerManagement extends JpaActionManagement implements Cont
actionRepository.updateExternalRef(actionId, externalRef);
}
@Override
public Optional<Action> getActionByExternalRef(@NotEmpty final String externalRef) {
return actionRepository.findByExternalRef(externalRef);
}
@Override
public void deleteExistingTarget(@NotEmpty final String controllerId) {
final JpaTarget target = targetRepository.getByControllerId(controllerId);
@@ -555,7 +554,7 @@ public class JpaControllerManagement extends JpaActionManagement implements Cont
}
@Override
public Optional<Action> getInstalledActionByTarget(final Target target) {
public Optional<Action> findInstalledActionByTarget(final Target target) {
final JpaTarget jpaTarget = (JpaTarget) target;
return Optional.ofNullable(jpaTarget.getInstalledDistributionSet())
.flatMap(installedDistributionSet -> actionRepository.findFirstByTargetIdAndDistributionSetIdAndStatusOrderByIdDesc(
@@ -575,12 +574,9 @@ public class JpaControllerManagement extends JpaActionManagement implements Cont
@Override
public boolean updateOfflineAssignedVersion(@NotEmpty final String controllerId, final String distributionName, final String version) {
List<DistributionSetAssignmentResult> distributionSetAssignmentResults =
systemSecurityContext.runAsSystem(() ->
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))));
systemSecurityContext.runAsSystem(() -> deploymentManagement.offlineAssignedDistributionSets(
controllerId,
List.of(Map.entry(controllerId, distributionSetManagement.findByNameAndVersion(distributionName, version).getId()))));
return distributionSetAssignmentResults.stream()
.findFirst()
@@ -588,8 +584,8 @@ public class JpaControllerManagement extends JpaActionManagement implements Cont
.orElseThrow();
}
Optional<TargetType> getTargetType(String targetTypeName) {
return systemSecurityContext.runAsSystem(() -> targetTypeManagement.getByName(targetTypeName));
private Optional<TargetType> findTargetType(String targetTypeName) {
return targetTypeRepository.findOne(TargetTypeSpecification.hasName(targetTypeName)).map(TargetType.class::cast);
}
// for testing
@@ -668,7 +664,7 @@ public class JpaControllerManagement extends JpaActionManagement implements Cont
jpaTarget.setAddress(Optional.ofNullable(address).map(URI::toString).orElse(null));
if (StringUtils.hasText(type)) {
var targetTypeOptional = getTargetType(type);
final Optional<TargetType> targetTypeOptional = findTargetType(type);
if (targetTypeOptional.isPresent()) {
log.debug("Setting target type for thing ID \"{}\" to \"{}\".", controllerId, type);
jpaTarget.setTargetType(targetTypeOptional.get());
@@ -772,7 +768,7 @@ public class JpaControllerManagement extends JpaActionManagement implements Cont
if (isTypeChanged(toUpdate.getTargetType(), type)) {
if (StringUtils.hasText(type)) {
final Optional<TargetType> targetTypeOptional = getTargetType(type);
final Optional<TargetType> targetTypeOptional = findTargetType(type);
if (targetTypeOptional.isPresent()) {
log.debug("Updating target type for thing ID \"{}\" to \"{}\".", toUpdate.getControllerId(), type);
toUpdate.setTargetType(targetTypeOptional.get());

View File

@@ -464,13 +464,13 @@ public class JpaDeploymentManagement extends JpaActionManagement implements Depl
}
@Override
public Optional<DistributionSet> getAssignedDistributionSet(final String controllerId) {
public Optional<DistributionSet> findAssignedDistributionSet(final String controllerId) {
return targetRepository.findWithDetailsByControllerId(controllerId, JpaTarget_.GRAPH_TARGET_ASSIGNED_DISTRIBUTION_SET)
.map(JpaTarget::getAssignedDistributionSet);
}
@Override
public Optional<DistributionSet> getInstalledDistributionSet(final String controllerId) {
public Optional<DistributionSet> findInstalledDistributionSet(final String controllerId) {
return targetRepository.findWithDetailsByControllerId(controllerId, JpaTarget_.GRAPH_TARGET_INSTALLED_DISTRIBUTION_SET)
.map(JpaTarget::getInstalledDistributionSet);
}

View File

@@ -154,8 +154,9 @@ public class JpaDistributionSetManagement
}
@Override
public Optional<JpaDistributionSet> getWithDetails(final long id) {
return jpaRepository.findOne(jpaRepository.byIdSpec(id), JpaDistributionSet_.GRAPH_DISTRIBUTION_SET_DETAIL);
public JpaDistributionSet getWithDetails(final long id) {
return jpaRepository.findOne(jpaRepository.byIdSpec(id), JpaDistributionSet_.GRAPH_DISTRIBUTION_SET_DETAIL)
.orElseThrow(() -> new EntityNotFoundException(DistributionSet.class, id));
}
// implicitly lock a distribution set if not already locked and implicit lock is enabled and not to skip
@@ -290,8 +291,9 @@ public class JpaDistributionSetManagement
}
@Override
public Optional<JpaDistributionSet> findByNameAndVersion(final String distributionName, final String version) {
return jpaRepository.findOne(DistributionSetSpecification.equalsNameAndVersionIgnoreCase(distributionName, version));
public JpaDistributionSet findByNameAndVersion(final String distributionName, final String version) {
return jpaRepository.findOne(DistributionSetSpecification.equalsNameAndVersionIgnoreCase(distributionName, version))
.orElseThrow(() -> new EntityNotFoundException(DistributionSet.class, Map.entry(distributionName, version)));
}
@Override

View File

@@ -94,11 +94,6 @@ public class JpaDistributionSetTypeManagement
return jpaRepository.findOne(DistributionSetTypeSpecification.byKey(key));
}
@Override
public Optional<JpaDistributionSetType> findByName(final String name) {
return jpaRepository.findOne(DistributionSetTypeSpecification.byName(name));
}
@Override
@Transactional
@Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = TX_RT_MAX, backoff = @Backoff(delay = TX_RT_DELAY))

View File

@@ -109,8 +109,26 @@ public class JpaRolloutGroupManagement implements RolloutGroupManagement {
}
@Override
public Optional<RolloutGroup> get(final long rolloutGroupId) {
return rolloutGroupRepository.findById(rolloutGroupId).map(RolloutGroup.class::cast);
public RolloutGroup get(final long rolloutGroupId) {
return rolloutGroupRepository.findById(rolloutGroupId).map(RolloutGroup.class::cast)
.orElseThrow(() -> new EntityNotFoundException(RolloutGroup.class, rolloutGroupId));
}
@Override
public RolloutGroup getWithDetailedStatus(final long rolloutGroupId) {
final JpaRolloutGroup jpaRolloutGroup = (JpaRolloutGroup) rolloutGroupRepository.findById(rolloutGroupId).map(RolloutGroup.class::cast)
.orElseThrow(() -> new EntityNotFoundException(RolloutGroup.class, rolloutGroupId));
List<TotalTargetCountActionStatus> rolloutStatusCountItems = rolloutStatusCache.getRolloutGroupStatus(rolloutGroupId);
if (CollectionUtils.isEmpty(rolloutStatusCountItems)) {
rolloutStatusCountItems = actionRepository.getStatusCountByRolloutGroupId(rolloutGroupId);
rolloutStatusCache.putRolloutGroupStatus(rolloutGroupId, rolloutStatusCountItems);
}
final TotalTargetCountStatus totalTargetCountStatus = new TotalTargetCountStatus(
rolloutStatusCountItems, (long) jpaRolloutGroup.getTotalTargets(), jpaRolloutGroup.getRollout().getActionType());
jpaRolloutGroup.setTotalTargetCountStatus(totalTargetCountStatus);
return jpaRolloutGroup;
}
@Override
@@ -185,30 +203,6 @@ public class JpaRolloutGroupManagement implements RolloutGroupManagement {
return JpaManagementHelper.findAllWithCountBySpec(targetRepository, specList, pageable);
}
@Override
public Optional<RolloutGroup> getWithDetailedStatus(final long rolloutGroupId) {
final Optional<RolloutGroup> rolloutGroup = get(rolloutGroupId);
if (rolloutGroup.isEmpty()) {
return rolloutGroup;
}
final JpaRolloutGroup jpaRolloutGroup = (JpaRolloutGroup) rolloutGroup.get();
List<TotalTargetCountActionStatus> rolloutStatusCountItems = rolloutStatusCache
.getRolloutGroupStatus(rolloutGroupId);
if (CollectionUtils.isEmpty(rolloutStatusCountItems)) {
rolloutStatusCountItems = actionRepository.getStatusCountByRolloutGroupId(rolloutGroupId);
rolloutStatusCache.putRolloutGroupStatus(rolloutGroupId, rolloutStatusCountItems);
}
final TotalTargetCountStatus totalTargetCountStatus = new TotalTargetCountStatus(
rolloutStatusCountItems, (long) jpaRolloutGroup.getTotalTargets(), jpaRolloutGroup.getRollout().getActionType());
jpaRolloutGroup.setTotalTargetCountStatus(totalTargetCountStatus);
return rolloutGroup;
}
@Override
public long countTargetsOfRolloutsGroup(final long rolloutGroupId) {
throwExceptionIfRolloutGroupDoesNotExist(rolloutGroupId);

View File

@@ -304,22 +304,21 @@ public class JpaRolloutManagement implements RolloutManagement {
return rolloutRepository.findByStatusIn(ACTIVE_ROLLOUTS);
}
@Override
public Rollout get(final long rolloutId) {
return rolloutRepository.findById(rolloutId).map(Rollout.class::cast)
.orElseThrow(() -> new EntityNotFoundException(Rollout.class, rolloutId));
}
@Override
public Optional<Rollout> find(final long rolloutId) {
return rolloutRepository.findById(rolloutId).map(Rollout.class::cast);
}
@Override
public Optional<Rollout> getByName(final String rolloutName) {
return rolloutRepository.findByName(rolloutName);
}
@Override
public Optional<Rollout> getWithDetailedStatus(final long rolloutId) {
final Optional<Rollout> rollout = find(rolloutId);
if (rollout.isEmpty()) {
return rollout;
}
public Rollout getWithDetailedStatus(final long rolloutId) {
final Rollout rollout = rolloutRepository.findById(rolloutId).map(Rollout.class::cast)
.orElseThrow(() -> new EntityNotFoundException(Rollout.class, rolloutId));
List<TotalTargetCountActionStatus> rolloutStatusCountItems = rolloutStatusCache.getRolloutStatus(rolloutId);
@@ -329,8 +328,8 @@ public class JpaRolloutManagement implements RolloutManagement {
}
final TotalTargetCountStatus totalTargetCountStatus = new TotalTargetCountStatus(
rolloutStatusCountItems, rollout.get().getTotalTargets(), rollout.get().getActionType());
((JpaRollout) rollout.get()).setTotalTargetCountStatus(totalTargetCountStatus);
rolloutStatusCountItems, rollout.getTotalTargets(), rollout.getActionType());
((JpaRollout) rollout).setTotalTargetCountStatus(totalTargetCountStatus);
return rollout;
}
@@ -831,7 +830,7 @@ public class JpaRolloutManagement implements RolloutManagement {
if (quotaManagement.getMaxTargetsPerRolloutGroup() > 0) {
validateTargetsInGroups(
srcGroups, rollout.getTargetFilterQuery(), rollout.getCreatedAt(),
distributionSetType.getId()).getTargetsPerGroup().forEach(this::assertTargetsPerRolloutGroupQuota);
distributionSetType.getId()).targetsPerGroup().forEach(this::assertTargetsPerRolloutGroupQuota);
}
// create and persist the groups (w/o filling them with targets)

View File

@@ -22,11 +22,11 @@ import java.util.stream.Collectors;
import jakarta.persistence.EntityManager;
import org.eclipse.hawkbit.artifact.encryption.ArtifactEncryptionService;
import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.QuotaManagement;
import org.eclipse.hawkbit.repository.SoftwareModuleFields;
import org.eclipse.hawkbit.repository.SoftwareModuleManagement;
import org.eclipse.hawkbit.repository.artifact.encryption.ArtifactEncryptionService;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.LockedException;
import org.eclipse.hawkbit.repository.jpa.JpaManagementHelper;
@@ -53,19 +53,17 @@ import org.springframework.util.ObjectUtils;
@Service
@ConditionalOnBooleanProperty(prefix = "hawkbit.jpa", name = { "enabled", "software-module-management" }, matchIfMissing = true)
public class JpaSoftwareModuleManagement
extends AbstractJpaRepositoryWithMetadataManagement<JpaSoftwareModule, SoftwareModuleManagement.Create, SoftwareModuleManagement.Update, SoftwareModuleRepository, SoftwareModuleFields, MetadataValue, JpaSoftwareModule.JpaMetadataValue>
public class JpaSoftwareModuleManagement extends
AbstractJpaRepositoryWithMetadataManagement<JpaSoftwareModule, SoftwareModuleManagement.Create, SoftwareModuleManagement.Update, SoftwareModuleRepository, SoftwareModuleFields, MetadataValue, JpaSoftwareModule.JpaMetadataValue>
implements SoftwareModuleManagement<JpaSoftwareModule> {
private final DistributionSetRepository distributionSetRepository;
private final ArtifactManagement artifactManagement;
private final QuotaManagement quotaManagement;
protected JpaSoftwareModuleManagement(
final SoftwareModuleRepository softwareModuleRepository,
final EntityManager entityManager,
final DistributionSetRepository distributionSetRepository,
final ArtifactManagement artifactManagement, final QuotaManagement quotaManagement) {
protected JpaSoftwareModuleManagement(final SoftwareModuleRepository softwareModuleRepository, final EntityManager entityManager,
final DistributionSetRepository distributionSetRepository, final ArtifactManagement artifactManagement,
final QuotaManagement quotaManagement) {
super(softwareModuleRepository, entityManager);
this.distributionSetRepository = distributionSetRepository;
this.artifactManagement = artifactManagement;
@@ -79,9 +77,7 @@ public class JpaSoftwareModuleManagement
if (createdModules.stream().anyMatch(SoftwareModule::isEncrypted)) {
// flush sm creation in order to get ids
entityManager.flush();
createdModules.stream()
.filter(SoftwareModule::isEncrypted)
.map(SoftwareModule::getId)
createdModules.stream().filter(SoftwareModule::isEncrypted).map(SoftwareModule::getId)
.forEach(encryptedModuleId -> ArtifactEncryptionService.getInstance().addEncryptionSecrets(encryptedModuleId));
}
@@ -103,48 +99,39 @@ public class JpaSoftwareModuleManagement
@Override
protected List<JpaSoftwareModule> softDelete(final Collection<JpaSoftwareModule> toDelete) {
return toDelete.stream()
.filter(swModule -> {
final List<DistributionSet> assignedTo = swModule.getAssignedTo();
if (assignedTo != null) {
final List<DistributionSet> lockedDS = assignedTo.stream()
.filter(DistributionSet::isLocked)
.filter(ds -> !ds.isDeleted())
.toList();
if (!lockedDS.isEmpty()) {
final StringBuilder sb = new StringBuilder("Part of ");
if (lockedDS.size() == 1) {
sb.append("a locked distribution set: ");
} else {
sb.append(lockedDS.size()).append(" locked distribution sets: ");
}
for (final DistributionSet ds : lockedDS) {
sb.append(ds.getName()).append(":").append(ds.getVersion()).append(" (").append(ds.getId()).append("), ");
}
sb.delete(sb.length() - 2, sb.length());
throw new LockedException(JpaSoftwareModule.class, swModule.getId(), "DELETE", sb.toString());
}
return toDelete.stream().filter(swModule -> {
final List<DistributionSet> assignedTo = swModule.getAssignedTo();
if (assignedTo != null) {
final List<DistributionSet> lockedDS = assignedTo.stream().filter(DistributionSet::isLocked).filter(ds -> !ds.isDeleted())
.toList();
if (!lockedDS.isEmpty()) {
final StringBuilder sb = new StringBuilder("Part of ");
if (lockedDS.size() == 1) {
sb.append("a locked distribution set: ");
} else {
sb.append(lockedDS.size()).append(" locked distribution sets: ");
}
final boolean isAssigned = !ObjectUtils.isEmpty(assignedTo);
// schedule delete binary data of artifacts for every soft or not soft deleted module
deleteGridFsArtifacts(swModule);
return isAssigned;
})
.toList();
for (final DistributionSet ds : lockedDS) {
sb.append(ds.getName()).append(":").append(ds.getVersion()).append(" (").append(ds.getId()).append("), ");
}
sb.delete(sb.length() - 2, sb.length());
throw new LockedException(JpaSoftwareModule.class, swModule.getId(), "DELETE", sb.toString());
}
}
final boolean isAssigned = !ObjectUtils.isEmpty(assignedTo);
// schedule delete binary data of artifacts for every soft or not soft deleted module
deleteGridFsArtifacts(swModule);
return isAssigned;
}).toList();
}
// called only with 'system code' access, so no need to check access control
@Override
public Map<Long, Map<String, String>> findMetaDataBySoftwareModuleIdsAndTargetVisible(final Collection<Long> ids) {
return jpaRepository.findVisibleMetadataByModuleIds(ids)
.stream()
.collect(Collectors.groupingBy(
entry -> (Long) entry[0],
Collectors.toMap(
entry -> (String) entry[1],
entry -> (String) entry[2],
(existing, replacement) -> existing, // in case of duplicates, keep the first one
HashMap::new)));
return jpaRepository.findVisibleMetadataByModuleIds(ids).stream().collect(Collectors.groupingBy(entry -> (Long) entry[0],
Collectors.toMap(entry -> (String) entry[1], entry -> (String) entry[2], (existing, replacement) -> existing,
// in case of duplicates, keep the first one
HashMap::new)));
}
@Override
@@ -177,10 +164,8 @@ public class JpaSoftwareModuleManagement
public Page<JpaSoftwareModule> findByAssignedTo(final long distributionSetId, final Pageable pageable) {
assertDistributionSetExists(distributionSetId);
return JpaManagementHelper.findAllWithCountBySpec(
jpaRepository,
Collections.singletonList(SoftwareModuleSpecification.byAssignedToDs(distributionSetId)),
pageable);
return JpaManagementHelper.findAllWithCountBySpec(jpaRepository,
Collections.singletonList(SoftwareModuleSpecification.byAssignedToDs(distributionSetId)), pageable);
}
/**
@@ -203,11 +188,11 @@ public class JpaSoftwareModuleManagement
}
private void deleteGridFsArtifacts(final JpaSoftwareModule swModule) {
jpaRepository.getAccessController().ifPresent(accessController ->
accessController.assertOperationAllowed(AccessController.Operation.DELETE, swModule));
jpaRepository.getAccessController()
.ifPresent(accessController -> accessController.assertOperationAllowed(AccessController.Operation.DELETE, swModule));
final Set<String> sha1Hashes = swModule.getArtifacts().stream().map(Artifact::getSha1Hash).collect(Collectors.toSet());
AfterTransactionCommitExecutorHolder.getInstance().getAfterCommit().afterCommit(() ->
sha1Hashes.forEach(((JpaArtifactManagement) artifactManagement)::clearArtifactBinary));
AfterTransactionCommitExecutorHolder.getInstance().getAfterCommit()
.afterCommit(() -> sha1Hashes.forEach(((JpaArtifactManagement) artifactManagement)::clearArtifactBinary));
}
private void assertDistributionSetExists(final long distributionSetId) {

View File

@@ -47,11 +47,6 @@ public class JpaSoftwareModuleTypeManagement
return jpaRepository.findByKey(key);
}
@Override
public Optional<JpaSoftwareModuleType> findByName(final String name) {
return jpaRepository.findByName(name);
}
@Override
protected Collection<JpaSoftwareModuleType> softDelete(final Collection<JpaSoftwareModuleType> toDelete) {
return toDelete.stream().filter(smt ->

View File

@@ -15,12 +15,12 @@ import java.util.function.Consumer;
import jakarta.persistence.EntityManager;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.cache.TenancyCacheManager;
import org.eclipse.hawkbit.artifact.ArtifactStorage;
import org.eclipse.hawkbit.tenancy.cache.TenantCacheManager;
import org.eclipse.hawkbit.repository.RepositoryProperties;
import org.eclipse.hawkbit.repository.RolloutStatusCache;
import org.eclipse.hawkbit.repository.SystemManagement;
import org.eclipse.hawkbit.repository.TenantStatsManagement;
import org.eclipse.hawkbit.repository.artifact.ArtifactRepository;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.jpa.CurrentTenantCacheKeyGenerator;
import org.eclipse.hawkbit.repository.jpa.SystemManagementCacheKeyGenerator;
@@ -44,8 +44,8 @@ import org.eclipse.hawkbit.repository.jpa.utils.DeploymentHelper;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.model.TenantMetaData;
import org.eclipse.hawkbit.repository.report.model.SystemUsageReport;
import org.eclipse.hawkbit.repository.report.model.SystemUsageReportWithTenants;
import org.eclipse.hawkbit.repository.model.report.SystemUsageReport;
import org.eclipse.hawkbit.repository.model.report.SystemUsageReportWithTenants;
import org.eclipse.hawkbit.security.SystemSecurityContext;
import org.eclipse.hawkbit.tenancy.TenantAware;
import org.springframework.beans.factory.annotation.Autowired;
@@ -98,13 +98,13 @@ public class JpaSystemManagement implements CurrentTenantCacheKeyGenerator, Syst
private final SystemSecurityContext systemSecurityContext;
private final TenantAware tenantAware;
private final PlatformTransactionManager txManager;
private final TenancyCacheManager cacheManager;
private final TenantCacheManager cacheManager;
private final RolloutStatusCache rolloutStatusCache;
private final EntityManager entityManager;
private final RepositoryProperties repositoryProperties;
@Nullable
private ArtifactRepository artifactRepository;
private ArtifactStorage artifactRepository;
@SuppressWarnings("squid:S00107")
protected JpaSystemManagement(
@@ -116,7 +116,7 @@ public class JpaSystemManagement implements CurrentTenantCacheKeyGenerator, Syst
final TenantConfigurationRepository tenantConfigurationRepository, final TenantMetaDataRepository tenantMetaDataRepository,
final TenantStatsManagement systemStatsManagement, final SystemManagementCacheKeyGenerator currentTenantCacheKeyGenerator,
final SystemSecurityContext systemSecurityContext, final TenantAware tenantAware, final PlatformTransactionManager txManager,
final TenancyCacheManager cacheManager, final RolloutStatusCache rolloutStatusCache,
final TenantCacheManager cacheManager, final RolloutStatusCache rolloutStatusCache,
final EntityManager entityManager, final RepositoryProperties repositoryProperties,
final JpaProperties properties) {
this.targetRepository = targetRepository;
@@ -147,7 +147,7 @@ public class JpaSystemManagement implements CurrentTenantCacheKeyGenerator, Syst
}
@Autowired(required = false) // it's not required on dmf/ddi only instances
public void setArtifactRepository(ArtifactRepository artifactRepository) {
public void setArtifactRepository(ArtifactStorage artifactRepository) {
this.artifactRepository = artifactRepository;
}

View File

@@ -126,6 +126,27 @@ public class JpaTargetManagement
return jpaRepository.exists(AccessController.Operation.UPDATE, combinedSpecification);
}
@Override
public Target getByControllerId(final String controllerId) {
return jpaRepository.findByControllerId(controllerId).map(Target.class::cast)
.orElseThrow(() -> new EntityNotFoundException(Target.class, controllerId));
}
@Override
public Optional<Target> findByControllerId(final String controllerId) {
return jpaRepository.findByControllerId(controllerId).map(Target.class::cast);
}
@Override
public List<Target> findByControllerId(final Collection<String> controllerIDs) {
return Collections.unmodifiableList(jpaRepository.findAll(TargetSpecifications.byControllerIdWithAssignedDsInJoin(controllerIDs)));
}
@Override
public Target getWithDetails(final String controllerId, final String detailsKey) {
return jpaRepository.getWithDetailsByControllerId(controllerId, "Target." + detailsKey);
}
@Override
public Slice<Target> findByTargetFilterQueryAndNonDSAndCompatibleAndUpdatable(
final long distributionSetId, final String rsql, final Pageable pageable) {
@@ -143,21 +164,6 @@ public class JpaTargetManagement
.map(Target.class::cast);
}
@Override
public List<Target> getByControllerId(final Collection<String> controllerIDs) {
return Collections.unmodifiableList(jpaRepository.findAll(TargetSpecifications.byControllerIdWithAssignedDsInJoin(controllerIDs)));
}
@Override
public Optional<Target> getByControllerId(final String controllerId) {
return jpaRepository.findByControllerId(controllerId).map(Target.class::cast);
}
@Override
public Target getWithDetails(final String controllerId, final String detailsKey) {
return jpaRepository.getWithDetailsByControllerId(controllerId, "Target." + detailsKey);
}
@Override
public Slice<Target> findByRsqlAndNotInRolloutGroupsAndCompatibleAndUpdatable(
final Collection<Long> groups, final String rsql, final DistributionSetType dsType, final Pageable pageable) {

View File

@@ -76,26 +76,21 @@ public class JpaTargetTypeManagement
}
@Override
public Optional<TargetType> getByKey(final String key) {
public Optional<TargetType> findByKey(final String key) {
return jpaRepository.findOne(TargetTypeSpecification.hasKey(key)).map(TargetType.class::cast);
}
@Override
public Optional<TargetType> getByName(final String name) {
return jpaRepository.findOne(TargetTypeSpecification.hasName(name)).map(TargetType.class::cast);
}
@Override
@Transactional
@Retryable(retryFor = { ConcurrencyFailureException.class }, maxAttempts = Constants.TX_RT_MAX,
backoff = @Backoff(delay = Constants.TX_RT_DELAY))
public TargetType assignCompatibleDistributionSetTypes(final long id,
final Collection<Long> distributionSetTypeIds) {
final Collection<JpaDistributionSetType> dsTypes = distributionSetTypeRepository
.findAllById(distributionSetTypeIds);
final Collection<JpaDistributionSetType> dsTypes = distributionSetTypeRepository.findAllById(distributionSetTypeIds);
if (dsTypes.size() < distributionSetTypeIds.size()) {
throw new EntityNotFoundException(DistributionSetType.class, distributionSetTypeIds,
throw new EntityNotFoundException(
DistributionSetType.class, distributionSetTypeIds,
dsTypes.stream().map(DistributionSetType::getId).toList());
}

View File

@@ -13,7 +13,7 @@ import org.eclipse.hawkbit.repository.TenantStatsManagement;
import org.eclipse.hawkbit.repository.jpa.repository.ActionRepository;
import org.eclipse.hawkbit.repository.jpa.repository.LocalArtifactRepository;
import org.eclipse.hawkbit.repository.jpa.repository.TargetRepository;
import org.eclipse.hawkbit.repository.report.model.TenantUsage;
import org.eclipse.hawkbit.repository.model.report.TenantUsage;
import org.eclipse.hawkbit.tenancy.TenantAware;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
import org.springframework.stereotype.Service;

View File

@@ -28,7 +28,6 @@ import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.eclipse.hawkbit.repository.artifact.model.AbstractDbArtifact;
import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
@@ -76,13 +75,6 @@ public class JpaArtifact extends AbstractJpaTenantAwareBaseEntity implements Art
@Column(name = "file_size", updatable = false)
private long fileSize;
/**
* Constructs artifact.
*
* @param sha1Hash that is the link to the {@link AbstractDbArtifact} entity.
* @param filename that is used by {@link AbstractDbArtifact} store.
* @param softwareModule of this artifact
*/
public JpaArtifact(@NotEmpty final String sha1Hash, @NotNull final String filename, final SoftwareModule softwareModule) {
this.sha1Hash = sha1Hash;
this.filename = filename;

View File

@@ -56,8 +56,7 @@ public class PauseRolloutGroupAction implements RolloutGroupActionEvaluator<Roll
and this one tries to pause the rollout too but throws an exception
and rollbacks rollout processing transaction
*/
final Rollout refreshedRollout = rolloutManagement.find(rollout.getId())
.orElseThrow(() -> new EntityNotFoundException(Rollout.class, rollout.getId()));
final Rollout refreshedRollout = rolloutManagement.get(rollout.getId());
if (Rollout.RolloutStatus.PAUSED != refreshedRollout.getStatus()) {
// if only the latest state is != paused then pause
rolloutManagement.pauseRollout(rollout.getId());

View File

@@ -25,18 +25,6 @@ import org.springframework.data.jpa.domain.Specification;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class DistributionSetTypeSpecification {
/**
* {@link Specification} for retrieving {@link DistributionSetType} with
* given {@link DistributionSetType#getName()} including fetching the
* elements list.
*
* @param name to search
* @return the {@link DistributionSet} {@link Specification}
*/
public static Specification<JpaDistributionSetType> byName(final String name) {
return (targetRoot, query, cb) -> cb.equal(targetRoot.get(AbstractJpaNamedEntity_.name), name);
}
/**
* {@link Specification} for retrieving {@link DistributionSetType} with
* given {@link DistributionSetType#getKey()} including fetching the

View File

@@ -9,8 +9,6 @@
*/
package org.eclipse.hawkbit.repository.jpa.specifications;
import java.util.Collection;
import jakarta.persistence.criteria.SetJoin;
import lombok.AccessLevel;

View File

@@ -13,11 +13,11 @@ import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.eclipse.hawkbit.repository.exception.FileSizeQuotaExceededException;
import org.eclipse.hawkbit.repository.exception.StorageQuotaExceededException;
import org.eclipse.hawkbit.artifact.exception.FileSizeQuotaExceededException;
import org.eclipse.hawkbit.artifact.exception.StorageQuotaExceededException;
/**
* A FilterInputStream that ensures file size and storage quotas are enforced. It check during read operations if the
* A FilterInputStream that ensures file size and storage quotas are enforced. It checks during read operations if the
* quota will be exceeded and throws an QuotaExceededException if this happens.
*/
public class FileSizeAndStorageQuotaCheckingInputStream extends FilterInputStream {

View File

@@ -12,7 +12,6 @@ package org.eclipse.hawkbit.repository.jpa;
import static org.assertj.core.api.Assertions.assertThat;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
@@ -43,7 +42,6 @@ import org.eclipse.hawkbit.repository.jpa.repository.TargetRepository;
import org.eclipse.hawkbit.repository.jpa.repository.TargetTagRepository;
import org.eclipse.hawkbit.repository.jpa.repository.TargetTypeRepository;
import org.eclipse.hawkbit.repository.jpa.repository.TenantMetaDataRepository;
import org.eclipse.hawkbit.repository.jpa.specifications.DistributionSetSpecification;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.ActionStatusCreate;
import org.eclipse.hawkbit.repository.model.DistributionSet;
@@ -61,15 +59,11 @@ import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
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.orm.jpa.vendor.Database;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
@Slf4j
@ContextConfiguration(classes = { JpaRepositoryConfiguration.class, TestConfiguration.class })

View File

@@ -10,6 +10,7 @@
package org.eclipse.hawkbit.repository.jpa.acm;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.eclipse.hawkbit.im.authentication.SpPermission.READ_DISTRIBUTION_SET;
import static org.eclipse.hawkbit.im.authentication.SpPermission.READ_REPOSITORY;
@@ -79,8 +80,8 @@ class DistributionSetAccessControllerTest extends AbstractJpaIntegrationTest {
assertThat(distributionSetManagement.find(hiddenId)).isEmpty();
// verify distributionSetManagement#getWithDetails
assertThat(distributionSetManagement.getWithDetails(permittedActionId)).isPresent();
assertThat(distributionSetManagement.getWithDetails(hiddenId)).isEmpty();
assertThat(distributionSetManagement.getWithDetails(permittedActionId)).isNotNull();
assertThatExceptionOfType(EntityNotFoundException.class).isThrownBy(() -> distributionSetManagement.getWithDetails(hiddenId));
// verify distributionSetManagement#get
final List<Long> allActionIds = Arrays.asList(permittedActionId, hiddenId);
@@ -88,8 +89,11 @@ class DistributionSetAccessControllerTest extends AbstractJpaIntegrationTest {
.as("Fail if request hidden.").isInstanceOf(EntityNotFoundException.class);
// verify distributionSetManagement#getByNameAndVersion
assertThat(distributionSetManagement.findByNameAndVersion(permitted.getName(), permitted.getVersion())).isPresent();
assertThat(distributionSetManagement.findByNameAndVersion(hidden.getName(), hidden.getVersion())).isEmpty();
assertThat(distributionSetManagement.findByNameAndVersion(permitted.getName(), permitted.getVersion())).isNotNull();
final String hiddenName = hidden.getName();
final String hiddenVersion = hidden.getVersion();
assertThatExceptionOfType(EntityNotFoundException.class)
.isThrownBy(() -> distributionSetManagement.findByNameAndVersion(hiddenName, hiddenVersion));
});
}

View File

@@ -76,15 +76,18 @@ class TargetAccessControllerTest extends AbstractJpaIntegrationTest {
.containsOnly(permittedTarget.getId());
// verify targetManagement#getByControllerID
assertThat(targetManagement.getByControllerId(permittedTarget.getControllerId())).isPresent();
assertThat(targetManagement.getByControllerId(permittedTarget.getControllerId())).isNotNull();
final String hiddenTargetControllerId = hiddenTarget.getControllerId();
assertThatThrownBy(() -> targetManagement.getByControllerId(hiddenTargetControllerId))
.as("Missing read permissions for hidden target.")
.isInstanceOf(InsufficientPermissionException.class);
assertThatThrownBy(() -> targetManagement.findByControllerId(hiddenTargetControllerId))
.as("Missing read permissions for hidden target.")
.isInstanceOf(InsufficientPermissionException.class);
// verify targetManagement#getByControllerId
assertThat(targetManagement
.getByControllerId(List.of(permittedTarget.getControllerId(), hiddenTargetControllerId))
.findByControllerId(List.of(permittedTarget.getControllerId(), hiddenTargetControllerId))
.stream().map(Identifiable::getId).toList()).containsOnly(permittedTarget.getId());
// verify targetManagement#get

View File

@@ -64,10 +64,6 @@ class TargetTypeAccessControllerTest extends AbstractJpaIntegrationTest {
final Long hiddenTargetTypeId = hiddenTargetType.getId();
assertThat(targetTypeManagement.find(hiddenTargetTypeId)).isEmpty();
// verify targetTypeManagement#getByName
assertThat(targetTypeManagement.getByName(permittedTargetType.getName())).isPresent();
assertThat(targetTypeManagement.getByName(hiddenTargetType.getName())).isEmpty();
// verify targetTypeManagement#get by ids
final List<Long> allEntityIds = Arrays.asList(permittedTargetType.getId(), hiddenTargetTypeId);
assertThatExceptionOfType(EntityNotFoundException.class).isThrownBy(() -> targetTypeManagement.get(allEntityIds));

View File

@@ -432,7 +432,7 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
for (final Target target : targetsAll) {
if (targetIds.contains(target.getId())) {
assertThat(deploymentManagement.getAssignedDistributionSet(target.getControllerId())).as("assigned DS").contains(set);
assertThat(deploymentManagement.findAssignedDistributionSet(target.getControllerId())).as("assigned DS").contains(set);
}
}
}
@@ -456,7 +456,7 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
for (final Target target : targetsAll) {
if (targetIds.contains(target.getId())) {
assertThat(deploymentManagement.getAssignedDistributionSet(target.getControllerId())).isEmpty();
assertThat(deploymentManagement.findAssignedDistributionSet(target.getControllerId())).isEmpty();
}
}
}

View File

@@ -26,20 +26,20 @@ 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.artifact.exception.ArtifactBinaryNotFoundException;
import org.eclipse.hawkbit.artifact.exception.FileSizeQuotaExceededException;
import org.eclipse.hawkbit.artifact.exception.StorageQuotaExceededException;
import org.eclipse.hawkbit.artifact.model.ArtifactHashes;
import org.eclipse.hawkbit.artifact.model.ArtifactStream;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.im.authentication.SpRole;
import org.eclipse.hawkbit.repository.ArtifactManagement;
import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleCreatedEvent;
import org.eclipse.hawkbit.repository.exception.AssignmentQuotaExceededException;
import org.eclipse.hawkbit.repository.exception.FileSizeQuotaExceededException;
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;
import org.eclipse.hawkbit.repository.exception.StorageQuotaExceededException;
import org.eclipse.hawkbit.repository.exception.InvalidMd5HashException;
import org.eclipse.hawkbit.repository.exception.InvalidSha1HashException;
import org.eclipse.hawkbit.repository.exception.InvalidSha256HashException;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.eclipse.hawkbit.repository.jpa.RandomGeneratedInputStream;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule;
@@ -48,7 +48,6 @@ import org.eclipse.hawkbit.repository.model.ArtifactUpload;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.eclipse.hawkbit.repository.test.util.HashGeneratorUtils;
import org.eclipse.hawkbit.repository.test.util.SecurityContextSwitch;
import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.junit.jupiter.api.Test;
@@ -72,13 +71,9 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
final long moduleId = module.getId();
final boolean encrypted = module.isEncrypted();
assertThatExceptionOfType(ArtifactBinaryNotFoundException.class)
.isThrownBy(() -> artifactManagement.loadArtifactBinary(NOT_EXIST_ID, moduleId, encrypted));
.isThrownBy(() -> artifactManagement.getArtifactStream(NOT_EXIST_ID, moduleId, encrypted));
}
/**
* Verifies that management queries react as specfied on calls for non existing entities by means of
* throwing EntityNotFoundException.
*/
@Test
@ExpectEvents()
void entityQueriesReferringToNotExistingEntitiesThrowsException() {
@@ -87,12 +82,12 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
verifyThrownExceptionBy(
() -> artifactManagement.create(new ArtifactUpload(
IOUtils.toInputStream(artifactData, "UTF-8"),
NOT_EXIST_IDL, "xxx", null, null, null, false, null, artifactSize)), "SoftwareModule");
null, artifactSize, null, NOT_EXIST_IDL, "xxx", false)), "SoftwareModule");
verifyThrownExceptionBy(
() -> artifactManagement.create(new ArtifactUpload(
IOUtils.toInputStream(artifactData, "UTF-8"),
NOT_EXIST_IDL, "xxx", null, null, null, false, null, artifactSize)), "SoftwareModule");
null, artifactSize, null, NOT_EXIST_IDL, "xxx", false)), "SoftwareModule");
verifyThrownExceptionBy(() -> artifactManagement.delete(NOT_EXIST_IDL), "Artifact");
}
@@ -130,16 +125,10 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
assertThat(artifact1).isNotEqualTo(artifact2);
assertThat(artifact1.getSha1Hash()).isEqualTo(artifact2.getSha1Hash());
final DbArtifact dbArtifact = artifactManagement.loadArtifactBinary(
HashGeneratorUtils.generateSHA1(randomBytes), sm.getId(), sm.isEncrypted());
final DbArtifactHash hash = dbArtifact.getHashes();
// md5 and sha256 are kept in local artifact db and should not be provided by "load", test only sha1
assertThat(hash.getSha1()).isEqualTo(HashGeneratorUtils.generateSHA1(randomBytes));
assertThat(artifactRepository.findAll()).hasSize(4);
assertThat(softwareModuleRepository.findAll()).hasSize(3);
assertThat(softwareModuleManagement.find(sm.getId()).get().getArtifacts()).hasSize(3);
assertThat(softwareModuleManagement.get(sm.getId()).getArtifacts()).hasSize(3);
}
}
@@ -154,16 +143,16 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
final long smID = softwareModuleRepository.save(new JpaSoftwareModule(osType, "smIllegalFilenameTest", "1.0")).getId();
final ArtifactUpload artifactUpload = new ArtifactUpload(
IOUtils.toInputStream(artifactData, "UTF-8"), smID, illegalFilename, false, artifactSize);
IOUtils.toInputStream(artifactData, "UTF-8"), null, artifactSize, null, smID, illegalFilename, false);
assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> artifactManagement.create(artifactUpload));
assertThat(softwareModuleManagement.find(smID).get().getArtifacts()).isEmpty();
assertThat(softwareModuleManagement.get(smID).getArtifacts()).isEmpty();
}
/**
* Verifies that the quota specifying the maximum number of artifacts per software module is enforced.
*/
@Test
void createArtifactsUntilQuotaIsExceeded() throws IOException {
void failIfMaxArtifactsPerSoftwareModuleQuotaIsExceeded() throws IOException {
// create a software module
final long smId = softwareModuleRepository.save(new JpaSoftwareModule(osType, "sm1", "1.0")).getId();
@@ -186,11 +175,8 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
createArtifactForSoftwareModule("fileXYZ", smId, artifactSize);
}
/**
* Verifies that the quota specifying the maximum artifact storage is enforced (across software modules).
*/
@Test
void createArtifactsUntilStorageQuotaIsExceeded() throws IOException {
void failIfMaxArtifactStorageQuotaIsExceeded() throws IOException {
// create as many small artifacts as possible w/o violating the storage quota
final long maxBytes = quotaManagement.getMaxArtifactStorage();
final List<Long> artifactIds = new ArrayList<>();
@@ -290,7 +276,7 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
}
/**
* Test the deletion of an artifact metadata where the binary is still linked to another metadata element.
* Test the deletion of an artifact metadata where the binary is still linked to another metadata element.
* The expected result is that the metadata is deleted but the binary kept.
*/
@Test
@@ -343,7 +329,7 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
final Artifact artifact2 = createArtifactForSoftwareModule("file2", sm2.getId(), artifactSize, inputStream2);
assertEqualFileContents(
artifactManagement.loadArtifactBinary(artifact2.getSha1Hash(), sm2.getId(), sm2.isEncrypted()), randomBytes);
artifactManagement.getArtifactStream(artifact2.getSha1Hash(), sm2.getId(), sm2.isEncrypted()), randomBytes);
assertThat(artifactRepository.findAll()).hasSize(2);
@@ -405,7 +391,7 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
final SoftwareModule smOs = testdataFactory.createSoftwareModuleOs();
final Artifact artifact = createArtifactForSoftwareModule("file1", smOs.getId(), artifactSize, input);
assertEqualFileContents(
artifactManagement.loadArtifactBinary(artifact.getSha1Hash(), smOs.getId(), smOs.isEncrypted()), randomBytes);
artifactManagement.getArtifactStream(artifact.getSha1Hash(), smOs.getId(), smOs.isEncrypted()), randomBytes);
}
}
@@ -415,10 +401,10 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
@Test
@WithUser(allSpPermissions = true, removeFromAllPermission = {
SpPermission.DOWNLOAD_REPOSITORY_ARTIFACT, SpRole.CONTROLLER_ROLE, SpRole.CONTROLLER_ROLE_ANONYMOUS })
void loadArtifactBinaryWithoutDownloadArtifactThrowsPermissionDenied() {
void getArtifactBinaryWithoutDownloadArtifactThrowsPermissionDenied() {
assertThatExceptionOfType(InsufficientPermissionException.class)
.as("Should not have worked with missing permission.")
.isThrownBy(() -> artifactManagement.loadArtifactBinary("123", 1, false));
.isThrownBy(() -> artifactManagement.getArtifactStream("123", 1, false));
}
/**
@@ -429,29 +415,29 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
final byte[] testData = randomBytes(100);
final DbArtifactHash artifactHashes = calcHashes(testData);
final ArtifactHashes artifactHashes = calcHashes(testData);
try (final InputStream inputStream = new ByteArrayInputStream(testData)) {
final ArtifactUpload artifactUploadWithInvalidSha1 = new ArtifactUpload(
inputStream, sm.getId(), "test-file",
artifactHashes.getMd5(), "sha1", artifactHashes.getSha256(), false, null, testData.length);
assertThatExceptionOfType(InvalidSHA1HashException.class)
inputStream, null, testData.length, new ArtifactHashes("sha1", artifactHashes.md5(), artifactHashes.sha256()),
sm.getId(), "test-file", false);
assertThatExceptionOfType(InvalidSha1HashException.class)
.isThrownBy(() -> artifactManagement.create(artifactUploadWithInvalidSha1));
}
try (final InputStream inputStream = new ByteArrayInputStream(testData)) {
final ArtifactUpload artifactUploadWithInvalidMd5 = new ArtifactUpload(
inputStream, sm.getId(), "test-file",
"md5", artifactHashes.getSha1(), artifactHashes.getSha256(), false, null, testData.length);
assertThatExceptionOfType(InvalidMD5HashException.class)
inputStream, null, testData.length, new ArtifactHashes(artifactHashes.sha1(), "md5", artifactHashes.sha256()),
sm.getId(), "test-file", false);
assertThatExceptionOfType(InvalidMd5HashException.class)
.isThrownBy(() -> artifactManagement.create(artifactUploadWithInvalidMd5));
}
try (final InputStream inputStream = new ByteArrayInputStream(testData)) {
final ArtifactUpload artifactUploadWithInvalidSha256 = new ArtifactUpload(
inputStream, sm.getId(), "test-file",
artifactHashes.getMd5(), artifactHashes.getSha1(), "sha256", false, null, testData.length);
assertThatExceptionOfType(InvalidSHA256HashException.class)
inputStream, null, testData.length, new ArtifactHashes(artifactHashes.sha1(), artifactHashes.md5(), "sha256"),
sm.getId(), "test-file", false);
assertThatExceptionOfType(InvalidSha256HashException.class)
.isThrownBy(() -> artifactManagement.create(artifactUploadWithInvalidSha256));
}
}
@@ -464,20 +450,20 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
final byte[] testData = randomBytes(100);
final DbArtifactHash artifactHashes = calcHashes(testData);
final ArtifactHashes artifactHashes = calcHashes(testData);
try (final InputStream inputStream = new ByteArrayInputStream(testData)) {
final ArtifactUpload artifactUpload = new ArtifactUpload(
inputStream, sm.getId(), "test-file",
artifactHashes.getMd5(), artifactHashes.getSha1(), artifactHashes.getSha256(), false, null, testData.length);
inputStream, null, testData.length,
new ArtifactHashes(artifactHashes.sha1(), artifactHashes.md5(), artifactHashes.sha256()),
sm.getId(), "test-file", false);
final Artifact createdArtifact = artifactManagement.create(artifactUpload);
assertThat(createdArtifact.getSha1Hash()).isEqualTo(artifactHashes.getSha1());
assertThat(createdArtifact.getMd5Hash()).isEqualTo(artifactHashes.getMd5());
assertThat(createdArtifact.getSha256Hash()).isEqualTo(artifactHashes.getSha256());
assertThat(createdArtifact.getSha1Hash()).isEqualTo(artifactHashes.sha1());
assertThat(createdArtifact.getMd5Hash()).isEqualTo(artifactHashes.md5());
assertThat(createdArtifact.getSha256Hash()).isEqualTo(artifactHashes.sha256());
}
final DbArtifact dbArtifact = artifactManagement.loadArtifactBinary(artifactHashes.getSha1(), sm.getId(), sm.isEncrypted());
assertThat(dbArtifact).isNotNull();
assertThat(artifactManagement.getArtifactStream(artifactHashes.sha1(), sm.getId(), sm.isEncrypted())).isNotNull();
}
/**
@@ -489,34 +475,35 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
final SoftwareModule smApp = testdataFactory.createSoftwareModuleApp();
final byte[] testData = randomBytes(100);
final DbArtifactHash artifactHashes = calcHashes(testData);
final ArtifactHashes artifactHashes = calcHashes(testData);
try (final InputStream inputStream = new ByteArrayInputStream(testData)) {
final ArtifactUpload artifactUpload = new ArtifactUpload(
inputStream, smOs.getId(), "test-file",
artifactHashes.getMd5(), artifactHashes.getSha1(), artifactHashes.getSha256(), false, null, testData.length);
inputStream, null, testData.length,
new ArtifactHashes(artifactHashes.sha1(), artifactHashes.md5(), artifactHashes.sha256()),
smOs.getId(), "test-file", false);
final Artifact artifact = artifactManagement.create(artifactUpload);
assertThat(artifact).isNotNull();
}
final DbArtifact dbArtifact = artifactManagement.loadArtifactBinary(artifactHashes.getSha1(), smOs.getId(), smOs.isEncrypted());
assertThat(dbArtifact).isNotNull();
assertThat(artifactManagement.getArtifactStream(artifactHashes.sha1(), smOs.getId(), smOs.isEncrypted())).isNotNull();
try (final InputStream inputStream = new ByteArrayInputStream(testData)) {
final ArtifactUpload existingArtifactUpload = new ArtifactUpload(
inputStream, smApp.getId(), "test-file", false, testData.length);
inputStream, null, testData.length, null, smApp.getId(), "test-file", false);
final Artifact createdArtifact = artifactManagement.create(existingArtifactUpload);
assertThat(createdArtifact.getSha1Hash()).isEqualTo(artifactHashes.getSha1());
assertThat(createdArtifact.getMd5Hash()).isEqualTo(artifactHashes.getMd5());
assertThat(createdArtifact.getSha256Hash()).isEqualTo(artifactHashes.getSha256());
assertThat(createdArtifact.getSha1Hash()).isEqualTo(artifactHashes.sha1());
assertThat(createdArtifact.getMd5Hash()).isEqualTo(artifactHashes.md5());
assertThat(createdArtifact.getSha256Hash()).isEqualTo(artifactHashes.sha256());
}
}
private DbArtifactHash calcHashes(final byte[] input) throws NoSuchAlgorithmException {
private ArtifactHashes calcHashes(final byte[] input) throws NoSuchAlgorithmException {
final String sha1Hash = toBase16Hash("SHA1", input);
final String md5Hash = toBase16Hash("MD5", input);
final String sha256Hash = toBase16Hash("SHA-256", input);
return new DbArtifactHash(sha1Hash, md5Hash, sha256Hash);
return new ArtifactHashes(sha1Hash, md5Hash, sha256Hash);
}
private String toBase16Hash(final String algorithm, final byte[] input) throws NoSuchAlgorithmException {
@@ -534,7 +521,7 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
private Artifact createArtifactForSoftwareModule(
final String filename, final long moduleId, final int artifactSize, final InputStream inputStream) {
return artifactManagement.create(new ArtifactUpload(inputStream, moduleId, filename, false, artifactSize));
return artifactManagement.create(new ArtifactUpload(inputStream, null, artifactSize, null, moduleId, filename, false));
}
private <T> T runAsTenant(final String tenant, final Callable<T> callable) throws Exception {
@@ -554,8 +541,8 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
assertThat(runAsTenant(tenant, () -> artifactRepository.findAll())).hasSize(count);
}
private void assertEqualFileContents(final DbArtifact artifact, final byte[] randomBytes) throws IOException {
try (final InputStream inputStream = artifact.getFileInputStream()) {
private void assertEqualFileContents(final ArtifactStream artifact, final byte[] randomBytes) throws IOException {
try (final InputStream inputStream = artifact) {
assertTrue(
IOUtils.contentEquals(new ByteArrayInputStream(randomBytes), inputStream),
"The stored binary matches the given binary");

View File

@@ -334,8 +334,8 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(controllerManagement.findActionWithDetails(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();
assertThatExceptionOfType(EntityNotFoundException.class)
.isThrownBy(() -> controllerManagement.getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(), module.getId()));
assertThat(controllerManagement.findActiveActionWithHighestWeight(NOT_EXIST_ID)).isNotPresent();
@@ -654,10 +654,12 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
Target savedTarget = testdataFactory.createTarget();
// create two artifacts with identical SHA1 hash
final Artifact artifact = artifactManagement.create(new ArtifactUpload(new ByteArrayInputStream(random),
findFirstModuleByType(ds, osType).orElseThrow().getId(), "file1", false, artifactSize));
final Artifact artifact2 = artifactManagement.create(new ArtifactUpload(new ByteArrayInputStream(random),
findFirstModuleByType(ds2, osType).orElseThrow().getId(), "file1", false, artifactSize));
final Artifact artifact = artifactManagement.create(new ArtifactUpload(
new ByteArrayInputStream(random), null, artifactSize, null,
findFirstModuleByType(ds, osType).orElseThrow().getId(), "file1", false));
final Artifact artifact2 = artifactManagement.create(new ArtifactUpload(
new ByteArrayInputStream(random), null, artifactSize, null,
findFirstModuleByType(ds2, osType).orElseThrow().getId(), "file1", false));
assertThat(artifact.getSha1Hash()).isEqualTo(artifact2.getSha1Hash());
assertThat(
@@ -1107,13 +1109,11 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
ActionStatusCreate.builder().actionId(action.getId()).status(Action.Status.RUNNING).build()));
// nothing changed as "feedback after close" is disabled
assertThat(targetManagement.getByControllerId(DEFAULT_CONTROLLER_ID).get().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.IN_SYNC);
assertThat(targetManagement.getByControllerId(DEFAULT_CONTROLLER_ID).getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC);
assertThat(actionRepository.findById(action.getId()))
.hasValueSatisfying(a -> assertThat(a.getStatus()).isEqualTo(Status.FINISHED));
assertThat(actionStatusRepository.count()).isEqualTo(3);
assertThat(controllerManagement.findActionStatusByAction(action.getId(), PAGE).getNumberOfElements())
.isEqualTo(3);
assertThat(controllerManagement.findActionStatusByAction(action.getId(), PAGE).getNumberOfElements()).isEqualTo(3);
}
/**
@@ -1139,7 +1139,7 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
ActionStatusCreate.builder().actionId(action.getId()).status(Action.Status.RUNNING).build()));
// nothing changed as "feedback after close" is disabled
assertThat(targetManagement.getByControllerId(DEFAULT_CONTROLLER_ID).get().getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC);
assertThat(targetManagement.getByControllerId(DEFAULT_CONTROLLER_ID).getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC);
// however, additional action status has been stored
assertThat(actionStatusRepository.findAll(PAGE).getNumberOfElements()).isEqualTo(4);
assertThat(controllerManagement.findActionStatusByAction(action.getId(), PAGE).getNumberOfElements()).isEqualTo(4);
@@ -1166,11 +1166,12 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
});
// verify that audit information has not changed
final Target targetVerify = targetManagement.getByControllerId(controllerId).get();
assertThat(targetVerify.getCreatedBy()).isEqualTo(target.getCreatedBy());
assertThat(targetVerify.getCreatedAt()).isEqualTo(target.getCreatedAt());
assertThat(targetVerify.getLastModifiedBy()).isEqualTo(target.getLastModifiedBy());
assertThat(targetVerify.getLastModifiedAt()).isEqualTo(target.getLastModifiedAt());
assertThat(targetManagement.getByControllerId(controllerId)).satisfies(targetVerify -> {
assertThat(targetVerify.getCreatedBy()).isEqualTo(target.getCreatedBy());
assertThat(targetVerify.getCreatedAt()).isEqualTo(target.getCreatedAt());
assertThat(targetVerify.getLastModifiedBy()).isEqualTo(target.getLastModifiedBy());
assertThat(targetVerify.getLastModifiedAt()).isEqualTo(target.getLastModifiedAt());
});
}
/**
@@ -1442,31 +1443,6 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
}
}
/**
* Verify that getting a single action using externalRef works
*/
@Test
void getActionUsingSingleExternalRef() {
final String knownControllerId = "controllerId";
final String knownExternalRef = "externalRefId";
final DistributionSet knownDistributionSet = testdataFactory.createDistributionSet();
// GIVEN
testdataFactory.createTarget(knownControllerId);
final DistributionSetAssignmentResult assignmentResult = assignDistributionSet(knownDistributionSet.getId(),
knownControllerId);
final Long actionId = getFirstAssignedActionId(assignmentResult);
controllerManagement.updateActionExternalRef(actionId, knownExternalRef);
// WHEN
final Optional<Action> foundAction = controllerManagement.getActionByExternalRef(knownExternalRef);
// THEN
assertThat(foundAction).isPresent();
assertThat(foundAction.get().getId()).isEqualTo(actionId);
}
/**
* Verify that assigning version form target works
*/
@@ -1728,9 +1704,7 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
final Long dsId = testdataFactory.createDistributionSet().getId();
testdataFactory.createTarget();
assignDistributionSet(dsId, DEFAULT_CONTROLLER_ID);
assertThat(targetManagement.getByControllerId(DEFAULT_CONTROLLER_ID).get().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.PENDING);
assertThat(targetManagement.getByControllerId(DEFAULT_CONTROLLER_ID).getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
return deploymentManagement.findActiveActionsByTarget(DEFAULT_CONTROLLER_ID, PAGE).getContent().get(0).getId();
}
@@ -1738,7 +1712,7 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
final DistributionSet ds = testdataFactory.createDistributionSet(dsName);
final Long dsId = ds.getId();
assignDistributionSet(dsId, defaultControllerId, DOWNLOAD_ONLY);
assertThat(targetManagement.getByControllerId(defaultControllerId).get().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
assertThat(targetManagement.getByControllerId(defaultControllerId).getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
final Long id = deploymentManagement.findActiveActionsByTarget(defaultControllerId, PAGE).getContent().get(0).getId();
assertThat(id).isNotNull();
@@ -1747,11 +1721,9 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
private Long assignDs(final Long dsId, final String defaultControllerId, final Action.ActionType actionType) {
assignDistributionSet(dsId, defaultControllerId, actionType);
assertThat(targetManagement.getByControllerId(defaultControllerId).get().getUpdateStatus())
.isEqualTo(TargetUpdateStatus.PENDING);
assertThat(targetManagement.getByControllerId(defaultControllerId).getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
final Long id = deploymentManagement.findActiveActionsByTarget(defaultControllerId, PAGE).getContent().get(0)
.getId();
final Long id = deploymentManagement.findActiveActionsByTarget(defaultControllerId, PAGE).getContent().get(0).getId();
assertThat(id).isNotNull();
return id;
}
@@ -1809,7 +1781,7 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
final Long actionId, final String controllerId,
final TargetUpdateStatus expectedTargetUpdateStatus, final Action.Status expectedActionActionStatus,
final Action.Status expectedActionStatus, final boolean actionActive) {
final TargetUpdateStatus targetStatus = targetManagement.getByControllerId(controllerId).get().getUpdateStatus();
final TargetUpdateStatus targetStatus = targetManagement.getByControllerId(controllerId).getUpdateStatus();
assertThat(targetStatus).isEqualTo(expectedTargetUpdateStatus);
final Action action = deploymentManagement.findAction(actionId).get();
assertThat(action.getStatus()).isEqualTo(expectedActionActionStatus);

View File

@@ -180,7 +180,7 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertThat(action.getDistributionSet()).as("DistributionSet in action").isNotNull();
assertThat(action.getTarget()).as("Target in action").isNotNull();
assertThat(deploymentManagement.getAssignedDistributionSet(action.getTarget().getControllerId()).get())
assertThat(deploymentManagement.findAssignedDistributionSet(action.getTarget().getControllerId()).get())
.as("AssignedDistributionSet of target in action")
.isNotNull();
}
@@ -348,7 +348,7 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
final DistributionSet dsInstalled = action.getDistributionSet();
// check initial status
assertThat(targetManagement.getByControllerId("4712").get().getUpdateStatus())
assertThat(targetManagement.getByControllerId("4712").getUpdateStatus())
.as("target has update status")
.isEqualTo(TargetUpdateStatus.IN_SYNC);
@@ -366,8 +366,8 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
controllerManagement.addCancelActionStatus(ActionStatusCreate.builder()
.actionId(secondAction.getId()).status(Status.CANCELED).build());
assertThat(actionStatusRepository.findAll()).as("wrong size of actions status").hasSize(7);
assertThat(deploymentManagement.getAssignedDistributionSet("4712")).as("wrong ds").contains(dsFirst);
assertThat(targetManagement.getByControllerId("4712").get().getUpdateStatus())
assertThat(deploymentManagement.findAssignedDistributionSet("4712")).as("wrong ds").contains(dsFirst);
assertThat(targetManagement.getByControllerId("4712").getUpdateStatus())
.as("wrong update status")
.isEqualTo(TargetUpdateStatus.PENDING);
@@ -378,9 +378,9 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
controllerManagement.addCancelActionStatus(
ActionStatusCreate.builder().actionId(firstAction.getId()).status(Status.CANCELED).build());
assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(9);
assertThat(deploymentManagement.getAssignedDistributionSet("4712")).as("wrong assigned ds")
assertThat(deploymentManagement.findAssignedDistributionSet("4712")).as("wrong assigned ds")
.contains(dsInstalled);
assertThat(targetManagement.getByControllerId("4712").get().getUpdateStatus()).as("wrong update status")
assertThat(targetManagement.getByControllerId("4712").getUpdateStatus()).as("wrong update status")
.isEqualTo(TargetUpdateStatus.IN_SYNC);
}
@@ -397,7 +397,7 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
final DistributionSet dsInstalled = action.getDistributionSet();
// check initial status
assertThat(targetManagement.getByControllerId("4712").get().getUpdateStatus())
assertThat(targetManagement.getByControllerId("4712").getUpdateStatus())
.as("wrong update status")
.isEqualTo(TargetUpdateStatus.IN_SYNC);
@@ -415,23 +415,23 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
controllerManagement.addCancelActionStatus(
ActionStatusCreate.builder().actionId(firstAction.getId()).status(Status.CANCELED).build());
assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(7);
assertThat(deploymentManagement.getAssignedDistributionSet("4712")).as("wrong assigned ds").contains(dsSecond);
assertThat(targetManagement.getByControllerId("4712").get().getUpdateStatus()).as("wrong target update status")
assertThat(deploymentManagement.findAssignedDistributionSet("4712")).as("wrong assigned ds").contains(dsSecond);
assertThat(targetManagement.getByControllerId("4712").getUpdateStatus()).as("wrong target update status")
.isEqualTo(TargetUpdateStatus.PENDING);
// we cancel second -> remain assigned until finished cancellation
deploymentManagement.cancelAction(secondAction.getId());
secondAction = (JpaAction) deploymentManagement.findActionWithDetails(secondAction.getId()).get();
assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(8);
assertThat(deploymentManagement.getAssignedDistributionSet("4712")).as("wrong assigned ds").contains(dsSecond);
assertThat(deploymentManagement.findAssignedDistributionSet("4712")).as("wrong assigned ds").contains(dsSecond);
// confirm cancellation
controllerManagement.addCancelActionStatus(
ActionStatusCreate.builder().actionId(secondAction.getId()).status(Status.CANCELED).build());
// cancelled success -> back to dsInstalled
assertThat(deploymentManagement.getAssignedDistributionSet("4712"))
assertThat(deploymentManagement.findAssignedDistributionSet("4712"))
.as("wrong installed ds")
.contains(dsInstalled);
assertThat(targetManagement.getByControllerId("4712").get().getUpdateStatus())
assertThat(targetManagement.getByControllerId("4712").getUpdateStatus())
.as("wrong target info update status")
.isEqualTo(TargetUpdateStatus.IN_SYNC);
}
@@ -448,7 +448,7 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
final DistributionSet ds = testdataFactory.createDistributionSet("newDS", true);
// verify initial status
assertThat(targetManagement.getByControllerId("4712").get().getUpdateStatus())
assertThat(targetManagement.getByControllerId("4712").getUpdateStatus())
.as("wrong target info update status").isEqualTo(TargetUpdateStatus.IN_SYNC);
Action assigningAction = assignSet(target, ds);
@@ -467,9 +467,9 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
// verify
assertThat(assigningAction.getStatus()).as("wrong size of status").isEqualTo(Status.CANCELED);
assertThat(deploymentManagement.getAssignedDistributionSet("4712")).as("wrong assigned ds")
assertThat(deploymentManagement.findAssignedDistributionSet("4712")).as("wrong assigned ds")
.contains(dsInstalled);
assertThat(targetManagement.getByControllerId("4712").get().getUpdateStatus()).as("wrong target update status")
assertThat(targetManagement.getByControllerId("4712").getUpdateStatus()).as("wrong target update status")
.isEqualTo(TargetUpdateStatus.IN_SYNC);
}
@@ -480,7 +480,7 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
void forceQuitNotAllowedThrowsException() {
final Action action = prepareFinishedUpdate("4712", "installed", true);
// verify initial status
assertThat(targetManagement.getByControllerId("4712").get().getUpdateStatus()).as("wrong update status")
assertThat(targetManagement.getByControllerId("4712").getUpdateStatus()).as("wrong update status")
.isEqualTo(TargetUpdateStatus.IN_SYNC);
final Target target = action.getTarget();
@@ -1096,21 +1096,21 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
final Iterable<? extends Target> allFoundTargets = targetManagement.findAll(PAGE).getContent();
// get final updated version of targets
savedDeployedTargets = targetManagement.getByControllerId(savedDeployedTargets.stream().map(Target::getControllerId).toList());
savedDeployedTargets = targetManagement.findByControllerId(savedDeployedTargets.stream().map(Target::getControllerId).toList());
Assertions.<Target>assertThat(allFoundTargets).as("founded targets are wrong")
Assertions.<Target> assertThat(allFoundTargets).as("founded targets are wrong")
.containsAll(savedDeployedTargets)
.containsAll(savedNakedTargets);
assertThat(savedDeployedTargets).as("saved target are wrong").doesNotContain(toArray(savedNakedTargets, Target.class));
assertThat(savedNakedTargets).as("saved target are wrong").doesNotContain(toArray(savedDeployedTargets, Target.class));
for (final Target myt : savedNakedTargets) {
final Target t = targetManagement.getByControllerId(myt.getControllerId()).get();
final Target t = targetManagement.getByControllerId(myt.getControllerId());
assertThat(deploymentManagement.countActionsByTarget(t.getControllerId())).as("action should be empty").isZero();
}
for (final Target myt : savedDeployedTargets) {
final Target t = targetManagement.getByControllerId(myt.getControllerId()).get();
final Target t = targetManagement.getByControllerId(myt.getControllerId());
final List<Action> activeActionsByTarget = deploymentManagement.findActiveActionsByTarget(t.getControllerId(), PAGE).getContent();
assertThat(activeActionsByTarget).as("action should not be empty").isNotEmpty();
assertThat(t.getUpdateStatus()).as("wrong target update status").isEqualTo(TargetUpdateStatus.PENDING);
@@ -1247,23 +1247,23 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
// verifying the correctness of the assignments
for (final Target t : deployResWithDsA.getDeployedTargets()) {
assertThat(deploymentManagement.getAssignedDistributionSet(t.getControllerId()).get().getId())
assertThat(deploymentManagement.findAssignedDistributionSet(t.getControllerId()).get().getId())
.as("assignment is not correct").isEqualTo(dsA.getId());
assertThat(deploymentManagement.getInstalledDistributionSet(t.getControllerId()))
assertThat(deploymentManagement.findInstalledDistributionSet(t.getControllerId()))
.as("installed ds should be null").isNotPresent();
}
for (final Target t : deployResWithDsB.getDeployedTargets()) {
assertThat(deploymentManagement.getAssignedDistributionSet(t.getControllerId()).get().getId())
assertThat(deploymentManagement.findAssignedDistributionSet(t.getControllerId()).get().getId())
.as("assigned ds is wrong").isEqualTo(dsB.getId());
assertThat(deploymentManagement.getInstalledDistributionSet(t.getControllerId()))
assertThat(deploymentManagement.findInstalledDistributionSet(t.getControllerId()))
.as("installed ds should be null").isNotPresent();
}
for (final Target t : deployResWithDsC.getDeployedTargets()) {
assertThat(deploymentManagement.getAssignedDistributionSet(t.getControllerId()).get().getId())
assertThat(deploymentManagement.findAssignedDistributionSet(t.getControllerId()).get().getId())
.isEqualTo(dsC.getId());
assertThat(deploymentManagement.getInstalledDistributionSet(t.getControllerId()))
assertThat(deploymentManagement.findInstalledDistributionSet(t.getControllerId()))
.as("installed ds should not be null").isNotPresent();
assertThat(targetManagement.getByControllerId(t.getControllerId()).get().getUpdateStatus())
assertThat(targetManagement.getByControllerId(t.getControllerId()).getUpdateStatus())
.as("wrong target info update status").isEqualTo(TargetUpdateStatus.PENDING);
}
@@ -1274,12 +1274,12 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
// verify, that dsA is deployed correctly
for (final Target t_ : updatedTsDsA) {
final Target t = targetManagement.getByControllerId(t_.getControllerId()).get();
assertThat(deploymentManagement.getAssignedDistributionSet(t.getControllerId()))
final Target t = targetManagement.getByControllerId(t_.getControllerId());
assertThat(deploymentManagement.findAssignedDistributionSet(t.getControllerId()))
.as("assigned ds is wrong").contains(dsA);
assertThat(deploymentManagement.getInstalledDistributionSet(t.getControllerId()))
assertThat(deploymentManagement.findInstalledDistributionSet(t.getControllerId()))
.as("installed ds is wrong").contains(dsA);
assertThat(targetManagement.getByControllerId(t.getControllerId()).get().getUpdateStatus())
assertThat(targetManagement.getByControllerId(t.getControllerId()).getUpdateStatus())
.as("wrong target info update status").isEqualTo(TargetUpdateStatus.IN_SYNC);
assertThat(deploymentManagement.findActiveActionsByTarget(t.getControllerId(), PAGE))
.as("no actions should be active").isEmpty();
@@ -1294,20 +1294,20 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
findActionsByDistributionSet(pageRequest, dsA.getId()).getContent().get(1);
// get final updated version of targets
final List<Target> deployResWithDsBTargets = targetManagement.getByControllerId(deployResWithDsB
.getDeployedTargets().stream().map(Target::getControllerId).toList());
final List<Target> deployResWithDsBTargets = targetManagement.findByControllerId(
deployResWithDsB.getDeployedTargets().stream().map(Target::getControllerId).toList());
assertThat(deployed2DS).as("deployed ds is wrong").usingElementComparator(controllerIdComparator())
.containsAll(deployResWithDsBTargets);
assertThat(deployed2DS).as("deployed ds is wrong").hasSameSizeAs(deployResWithDsBTargets);
for (final Target t_ : deployed2DS) {
final Target t = targetManagement.getByControllerId(t_.getControllerId()).get();
assertThat(deploymentManagement.getAssignedDistributionSet(t.getControllerId())).as("assigned ds is wrong")
final Target t = targetManagement.getByControllerId(t_.getControllerId());
assertThat(deploymentManagement.findAssignedDistributionSet(t.getControllerId())).as("assigned ds is wrong")
.contains(dsA);
assertThat(deploymentManagement.getInstalledDistributionSet(t.getControllerId()))
assertThat(deploymentManagement.findInstalledDistributionSet(t.getControllerId()))
.as("installed ds should be null").isNotPresent();
assertThat(targetManagement.getByControllerId(t.getControllerId()).get().getUpdateStatus())
assertThat(targetManagement.getByControllerId(t.getControllerId()).getUpdateStatus())
.as("wrong target info update status").isEqualTo(TargetUpdateStatus.PENDING);
}
@@ -1412,17 +1412,16 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
List<Target> targs = Collections.singletonList(testdataFactory.createTarget("target-id-A"));
// doing the assignment
targs = assignDistributionSet(dsA, targs).getAssignedEntity().stream().map(Action::getTarget)
.toList();
targs = assignDistributionSet(dsA, targs).getAssignedEntity().stream().map(Action::getTarget).toList();
implicitLock(dsA);
Target targ = targetManagement.getByControllerId(targs.iterator().next().getControllerId()).get();
Target targ = targetManagement.getByControllerId(targs.iterator().next().getControllerId());
// checking the revisions of the created entities
// verifying that the revision of the object and the revision within the
// DB has incremented by implicit lock
assertThat(dsA.getOptLockRevision())
.as("lock revision is wrong")
.isEqualTo(distributionSetManagement.getWithDetails(dsA.getId()).get().getOptLockRevision());
.isEqualTo(distributionSetManagement.getWithDetails(dsA.getId()).getOptLockRevision());
// verifying that the assignment is correct
assertThat(deploymentManagement.findActiveActionsByTarget(targ.getControllerId(), PAGE).getTotalElements())
@@ -1430,7 +1429,7 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertThat(deploymentManagement.countActionsByTarget(targ.getControllerId())).as("Target actions are wrong")
.isEqualTo(1);
assertThat(targ.getUpdateStatus()).as("UpdateStatus of target is wrong").isEqualTo(TargetUpdateStatus.PENDING);
assertThat(deploymentManagement.getAssignedDistributionSet(targ.getControllerId()))
assertThat(deploymentManagement.findAssignedDistributionSet(targ.getControllerId()))
.as("Assigned distribution set of target is wrong").contains(dsA);
assertThat(deploymentManagement.findActiveActionsByTarget(targ.getControllerId(), PAGE).getContent().get(0)
.getDistributionSet()).as("Distribution set of action is wrong").isEqualTo(dsA);
@@ -1441,8 +1440,7 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
controllerManagement.addUpdateActionStatus(
ActionStatusCreate.builder().actionId(updAct.getContent().get(0).getId()).status(Status.FINISHED).build());
targ = targetManagement.getByControllerId(targ.getControllerId()).get();
targ = targetManagement.getByControllerId(targ.getControllerId());
assertEquals(0, deploymentManagement.findActiveActionsByTarget(targ.getControllerId(), PAGE).getTotalElements(),
"active target actions are wrong");
assertEquals(1,
@@ -1450,9 +1448,9 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
"active actions are wrong");
assertEquals(TargetUpdateStatus.IN_SYNC, targ.getUpdateStatus(), "tagret update status is not correct");
assertEquals(dsA, deploymentManagement.getAssignedDistributionSet(targ.getControllerId()).get(),
assertEquals(dsA, deploymentManagement.findAssignedDistributionSet(targ.getControllerId()).get(),
"wrong assigned ds");
assertEquals(dsA, deploymentManagement.getInstalledDistributionSet(targ.getControllerId()).get(),
assertEquals(dsA, deploymentManagement.findInstalledDistributionSet(targ.getControllerId()).get(),
"wrong installed ds");
targs = assignDistributionSet(dsB.getId(), "target-id-A").getAssignedEntity().stream().map(Action::getTarget)
@@ -1464,12 +1462,12 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertEquals(1, deploymentManagement.findActiveActionsByTarget(targ.getControllerId(), PAGE).getTotalElements(),
"active actions are wrong");
assertEquals(TargetUpdateStatus.PENDING,
targetManagement.getByControllerId(targ.getControllerId()).get().getUpdateStatus(),
targetManagement.getByControllerId(targ.getControllerId()).getUpdateStatus(),
"target status is wrong");
assertEquals(dsB, deploymentManagement.getAssignedDistributionSet(targ.getControllerId()).get(),
assertEquals(dsB, deploymentManagement.findAssignedDistributionSet(targ.getControllerId()).get(),
"wrong assigned ds");
assertEquals(dsA.getId(),
deploymentManagement.getInstalledDistributionSet(targ.getControllerId()).get().getId(),
deploymentManagement.findInstalledDistributionSet(targ.getControllerId()).get().getId(),
"Installed ds is wrong");
assertEquals(dsB, deploymentManagement.findActiveActionsByTarget(targ.getControllerId(), PAGE).getContent()
.get(0).getDistributionSet(), "Active ds is wrong");
@@ -1487,13 +1485,13 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertThat(dsA.getOptLockRevision())
.as("lock revision is wrong")
.isEqualTo(distributionSetManagement.getWithDetails(dsA.getId()).get().getOptLockRevision());
.isEqualTo(distributionSetManagement.getWithDetails(dsA.getId()).getOptLockRevision());
assignDistributionSet(dsA, Collections.singletonList(targ));
// implicit lock - incremented the version
assertThat(dsA.getOptLockRevision() + 1).as("lock revision is wrong")
.isEqualTo(distributionSetManagement.getWithDetails(dsA.getId()).get().getOptLockRevision());
.isEqualTo(distributionSetManagement.getWithDetails(dsA.getId()).getOptLockRevision());
}
/**
@@ -1696,10 +1694,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
private JpaAction assignSet(final Target target, final DistributionSet ds) {
assignDistributionSet(ds.getId(), target.getControllerId());
implicitLock(ds);
assertThat(targetManagement.getByControllerId(target.getControllerId()).get().getUpdateStatus())
assertThat(targetManagement.getByControllerId(target.getControllerId()).getUpdateStatus())
.as("wrong update status").isEqualTo(TargetUpdateStatus.PENDING);
assertThat(deploymentManagement.getAssignedDistributionSet(target.getControllerId())).as("wrong assigned ds")
.contains(ds);
assertThat(deploymentManagement.findAssignedDistributionSet(target.getControllerId()))
.as("wrong assigned ds").contains(ds);
final JpaAction action = actionRepository
.findAll(
(root, query, cb) ->

View File

@@ -267,9 +267,9 @@ class DistributionSetInvalidationManagementTest extends AbstractJpaIntegrationTe
private void assertDistributionSetInvalidationCount(
final DistributionSetInvalidationCount distributionSetInvalidationCount,
final long expectedAutoAssignmentCount, final long expectedActionCount, final long expectedRolloutCount) {
assertThat(distributionSetInvalidationCount.getAutoAssignmentCount()).isEqualTo(expectedAutoAssignmentCount);
assertThat(distributionSetInvalidationCount.getActionCount()).isEqualTo(expectedActionCount);
assertThat(distributionSetInvalidationCount.getRolloutsCount()).isEqualTo(expectedRolloutCount);
assertThat(distributionSetInvalidationCount.autoAssignmentCount()).isEqualTo(expectedAutoAssignmentCount);
assertThat(distributionSetInvalidationCount.actionCount()).isEqualTo(expectedActionCount);
assertThat(distributionSetInvalidationCount.rolloutsCount()).isEqualTo(expectedRolloutCount);
}
private List<JpaAction> findActionsByTarget(@Param("target") Target target) { // order by id ?

View File

@@ -40,6 +40,7 @@ import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetUpdated
import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleCreatedEvent;
import org.eclipse.hawkbit.repository.exception.AssignmentQuotaExceededException;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.EntityReadOnlyException;
import org.eclipse.hawkbit.repository.exception.IncompleteDistributionSetException;
import org.eclipse.hawkbit.repository.exception.InvalidDistributionSetException;
@@ -85,8 +86,9 @@ class DistributionSetManagementTest extends AbstractRepositoryManagementWithMeta
void nonExistingEntityAccessReturnsNotPresent() {
final DistributionSet set = testdataFactory.createDistributionSet();
assertThat(distributionSetManagement.find(NOT_EXIST_IDL)).isNotPresent();
assertThat(distributionSetManagement.getWithDetails(NOT_EXIST_IDL)).isNotPresent();
assertThat(distributionSetManagement.findByNameAndVersion(NOT_EXIST_ID, NOT_EXIST_ID)).isNotPresent();
assertThatExceptionOfType(EntityNotFoundException.class).isThrownBy(() -> distributionSetManagement.getWithDetails(NOT_EXIST_IDL));
assertThatExceptionOfType(EntityNotFoundException.class)
.isThrownBy(() -> distributionSetManagement.findByNameAndVersion(NOT_EXIST_ID, NOT_EXIST_ID));
assertThat(distributionSetManagement.getMetadata(set.getId()).get(NOT_EXIST_ID)).isNull();
}
@@ -277,7 +279,7 @@ class DistributionSetManagementTest extends AbstractRepositoryManagementWithMeta
// assign target
assignDistributionSet(ds.getId(), target.getControllerId());
ds = distributionSetManagement.getWithDetails(ds.getId()).orElseThrow();
ds = distributionSetManagement.getWithDetails(ds.getId());
final Long dsId = ds.getId();
// not allowed as it is assigned now
@@ -348,6 +350,7 @@ class DistributionSetManagementTest extends AbstractRepositoryManagementWithMeta
assertThatExceptionOfType(InvalidDistributionSetException.class)
.as("Invalid distributionSet should throw an exception").isThrownBy(() -> distributionSetManagement.update(update));
}
@Test
void failToModifyMetadataForInvalidDistributionSet() {
final String key = forType(String.class);
@@ -464,7 +467,7 @@ class DistributionSetManagementTest extends AbstractRepositoryManagementWithMeta
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()
distributionSetManagement.getWithDetails(distributionSet.getId()).getModules()
.forEach(module -> assertThat(module.isLocked()).isTrue());
}
@@ -509,7 +512,7 @@ class DistributionSetManagementTest extends AbstractRepositoryManagementWithMeta
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()
distributionSetManagement.getWithDetails(distributionSet.getId()).getModules()
.forEach(module -> assertThat(module.isLocked()).isTrue());
}
@@ -530,7 +533,7 @@ class DistributionSetManagementTest extends AbstractRepositoryManagementWithMeta
assertThatExceptionOfType(LockedException.class)
.as("Attempt to modify a locked DS software modules should throw an exception")
.isThrownBy(() -> distributionSetManagement.assignSoftwareModules(distributionSetId, moduleIds));
assertThat(distributionSetManagement.getWithDetails(distributionSetId).orElseThrow().getModules())
assertThat(distributionSetManagement.getWithDetails(distributionSetId).getModules())
.as("Software module shall not be added to a locked DS.")
.hasSize(softwareModuleCount);
@@ -539,7 +542,7 @@ class DistributionSetManagementTest extends AbstractRepositoryManagementWithMeta
assertThatExceptionOfType(LockedException.class)
.as("Attempt to modify a locked DS software modules should throw an exception")
.isThrownBy(() -> distributionSetManagement.unassignSoftwareModule(distributionSetId, firstModuleId));
assertThat(distributionSetManagement.getWithDetails(distributionSetId).orElseThrow().getModules())
assertThat(distributionSetManagement.getWithDetails(distributionSetId).getModules())
.as("Software module shall not be removed from a locked DS.")
.hasSize(softwareModuleCount);
}
@@ -705,15 +708,15 @@ class DistributionSetManagementTest extends AbstractRepositoryManagementWithMeta
assertThat(distributionSetManagement.countRolloutsByStatusForDistributionSet(ds2.getId())).hasSize(1);
assertThat(distributionSetManagement.countRolloutsByStatusForDistributionSet(ds3.getId())).isEmpty();
Optional<Rollout> rollout = rolloutManagement.find(rollout1.getId());
rollout.ifPresent(value -> assertThat(Rollout.RolloutStatus.valueOf(
Rollout rollout = rolloutManagement.get(rollout1.getId());
assertThat(Rollout.RolloutStatus.valueOf(
String.valueOf(distributionSetManagement.countRolloutsByStatusForDistributionSet(ds1.getId()).get(0).getName()))).isEqualTo(
value.getStatus()));
rollout.getStatus());
rollout = rolloutManagement.find(rollout2.getId());
rollout.ifPresent(value -> assertThat(Rollout.RolloutStatus.valueOf(
rollout = rolloutManagement.get(rollout2.getId());
assertThat(Rollout.RolloutStatus.valueOf(
String.valueOf(distributionSetManagement.countRolloutsByStatusForDistributionSet(ds2.getId()).get(0).getName()))).isEqualTo(
value.getStatus()));
rollout.getStatus());
}
/**

View File

@@ -10,6 +10,7 @@
package org.eclipse.hawkbit.repository.jpa.management;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import org.eclipse.hawkbit.repository.event.remote.RolloutDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetCreatedEvent;
@@ -21,6 +22,7 @@ import org.eclipse.hawkbit.repository.event.remote.entity.RolloutUpdatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleUpdatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetCreatedEvent;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.eclipse.hawkbit.repository.jpa.model.JpaRolloutGroup;
import org.eclipse.hawkbit.repository.model.RolloutGroup;
@@ -41,8 +43,8 @@ class RolloutGroupManagementTest extends AbstractJpaIntegrationTest {
@Test
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
void nonExistingEntityAccessReturnsNotPresent() {
assertThat(rolloutGroupManagement.get(NOT_EXIST_IDL)).isNotPresent();
assertThat(rolloutGroupManagement.getWithDetailedStatus(NOT_EXIST_IDL)).isNotPresent();
assertThatExceptionOfType(EntityNotFoundException.class).isThrownBy(() -> rolloutGroupManagement.get(NOT_EXIST_IDL));
assertThatExceptionOfType(EntityNotFoundException.class).isThrownBy(() -> rolloutGroupManagement.getWithDetailedStatus(NOT_EXIST_IDL));
}
/**
@@ -81,10 +83,10 @@ class RolloutGroupManagementTest extends AbstractJpaIntegrationTest {
testdataFactory.createAndStartRollout(1, 0, 1, "100", "80").getId(), PAGE).getContent()
.get(0).getId();
for (final RolloutGroup.RolloutGroupStatus status : RolloutGroup.RolloutGroupStatus.values()) {
final JpaRolloutGroup rolloutGroup = ((JpaRolloutGroup) rolloutGroupManagement.get(id).orElseThrow());
final JpaRolloutGroup rolloutGroup = (JpaRolloutGroup) rolloutGroupManagement.get(id);
rolloutGroup.setStatus(status);
rolloutGroupRepository.save(rolloutGroup);
assertThat(rolloutGroupManagement.get(id).orElseThrow().getStatus()).isEqualTo(status);
assertThat(rolloutGroupManagement.get(id).getStatus()).isEqualTo(status);
}
}
}

View File

@@ -17,7 +17,6 @@ import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
@@ -52,6 +51,7 @@ import org.eclipse.hawkbit.repository.event.remote.entity.TargetCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetUpdatedEvent;
import org.eclipse.hawkbit.repository.exception.AssignmentQuotaExceededException;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.EntityReadOnlyException;
import org.eclipse.hawkbit.repository.exception.IncompleteDistributionSetException;
import org.eclipse.hawkbit.repository.exception.InsufficientPermissionException;
@@ -289,9 +289,8 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
@Test
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class) })
void nonExistingEntityAccessReturnsNotPresent() {
assertThat(rolloutManagement.find(NOT_EXIST_IDL)).isNotPresent();
assertThat(rolloutManagement.getByName(NOT_EXIST_ID)).isNotPresent();
assertThat(rolloutManagement.getWithDetailedStatus(NOT_EXIST_IDL)).isNotPresent();
assertThatExceptionOfType(EntityNotFoundException.class).isThrownBy(() -> rolloutManagement.get(NOT_EXIST_IDL));
assertThatExceptionOfType(EntityNotFoundException.class).isThrownBy(() -> rolloutManagement.getWithDetailedStatus(NOT_EXIST_IDL));
}
/**
@@ -570,7 +569,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
rolloutHandler.handleAll();
// finish running actions, 2 actions should be finished
assertThat(changeStatusForAllRunningActions(createdRollout, Status.FINISHED)).isEqualTo(2);
assertThat(findRollout(createdRollout.getId()).getStatus()).isEqualTo(RolloutStatus.RUNNING);
assertThat(rolloutManagement.get(createdRollout.getId()).getStatus()).isEqualTo(RolloutStatus.RUNNING);
}
// check rollout to see that all actions and all groups are finished and
@@ -836,7 +835,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
final List<Target> targetList = targets.getContent();
assertThat(targetList).hasSize(5);
targets.getContent().stream().map(Target::getControllerId).map(deploymentManagement::getAssignedDistributionSet)
targets.getContent().stream().map(Target::getControllerId).map(deploymentManagement::findAssignedDistributionSet)
.forEach(d -> assertThat(d.get().getId()).isEqualTo(ds.getId()));
final List<Target> targetToCancel = new ArrayList<>();
@@ -955,7 +954,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetList).hasSize(amountTargetsForRollout);
targetList.stream()
.map(Target::getControllerId)
.map(deploymentManagement::getAssignedDistributionSet)
.map(deploymentManagement::findAssignedDistributionSet)
.forEach(d -> assertThat(d).contains(distributionSet));
}
@@ -1164,25 +1163,6 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
}
}
/**
* Verify that the expected rollout is found by name.
*/
@Test
void findRolloutByName() {
final int amountTargetsForRollout = 12;
final int amountGroups = 2;
final String successCondition = "50";
final String errorCondition = "80";
final String rolloutName = "Rollout137";
final Rollout rolloutCreated = createTestRolloutWithTargetsAndDistributionSet(amountTargetsForRollout,
amountGroups, successCondition, errorCondition, rolloutName, "RolloutA");
final Rollout rolloutFound = rolloutManagement.getByName(rolloutName).get();
assertThat(rolloutCreated).isEqualTo(rolloutFound);
}
/**
* Verify that the percent count is acting like aspected when targets move to the status finished or error.
*/
@@ -1194,8 +1174,8 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
final String successCondition = "50";
final String errorCondition = "80";
final String rolloutName = "MyRollout";
Rollout myRollout = createTestRolloutWithTargetsAndDistributionSet(amountTargetsForRollout, amountGroups,
successCondition, errorCondition, rolloutName, rolloutName);
Rollout myRollout = createTestRolloutWithTargetsAndDistributionSet(
amountTargetsForRollout, amountGroups, successCondition, errorCondition, rolloutName, rolloutName);
rolloutManagement.start(myRollout.getId());
// Run here, because scheduler is disabled during tests
@@ -1206,18 +1186,16 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
myRollout = reloadRollout(myRollout);
float percent = rolloutGroupManagement
.getWithDetailedStatus(
rolloutGroupManagement.findByRollout(myRollout.getId(), PAGE).getContent().get(0).getId())
.get().getTotalTargetCountStatus().getFinishedPercent();
.getWithDetailedStatus(rolloutGroupManagement.findByRollout(myRollout.getId(), PAGE).getContent().get(0).getId())
.getTotalTargetCountStatus().getFinishedPercent();
assertThat(percent).isEqualTo(40);
changeStatusForRunningActions(myRollout, Status.FINISHED, 3);
rolloutHandler.handleAll();
percent = rolloutGroupManagement
.getWithDetailedStatus(
rolloutGroupManagement.findByRollout(myRollout.getId(), PAGE).getContent().get(0).getId())
.get().getTotalTargetCountStatus().getFinishedPercent();
.getWithDetailedStatus(rolloutGroupManagement.findByRollout(myRollout.getId(), PAGE).getContent().get(0).getId())
.getTotalTargetCountStatus().getFinishedPercent();
assertThat(percent).isEqualTo(100);
changeStatusForRunningActions(myRollout, Status.FINISHED, 4);
@@ -1225,9 +1203,8 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
rolloutHandler.handleAll();
percent = rolloutGroupManagement
.getWithDetailedStatus(
rolloutGroupManagement.findByRollout(myRollout.getId(), PAGE).getContent().get(1).getId())
.get().getTotalTargetCountStatus().getFinishedPercent();
.getWithDetailedStatus(rolloutGroupManagement.findByRollout(myRollout.getId(), PAGE).getContent().get(1).getId())
.getTotalTargetCountStatus().getFinishedPercent();
assertThat(percent).isEqualTo(80);
}
@@ -1363,7 +1340,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
// Run here, because scheduler is disabled during tests
rolloutHandler.handleAll();
myRollout = findRollout(myRolloutId);
myRollout = rolloutManagement.get(myRolloutId);
assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.RUNNING);
final Map<TotalTargetCountStatus.Status, Long> expectedTargetCountStatus = createInitStatusMap();
expectedTargetCountStatus.put(TotalTargetCountStatus.Status.RUNNING, 1L);
@@ -1389,7 +1366,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.READY);
rolloutHandler.handleAll();
myRollout = findRollout(myRollout.getId());
myRollout = rolloutManagement.get(myRollout.getId());
assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.READY);
rolloutManagement.start(myRollout.getId());
@@ -1568,7 +1545,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
rolloutHandler.handleAll();
// rollout should not have been started
myRollout = findRollout(myRolloutId);
myRollout = rolloutManagement.get(myRolloutId);
assertThat(myRollout.getName()).isEqualTo("newName");
assertThat(myRollout.getDescription()).isEqualTo("newDesc");
}
@@ -1604,7 +1581,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
rolloutGroups.add(generateRolloutGroup(2, percentTargetsInGroup3, null));
Rollout myRollout = rolloutManagement.create(rolloutcreate, rolloutGroups, conditions);
myRollout = findRollout(myRollout.getId());
myRollout = rolloutManagement.get(myRollout.getId());
assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.CREATING);
for (final RolloutGroup group : rolloutGroupManagement.findByRollout(myRollout.getId(), PAGE).getContent()) {
@@ -1616,7 +1593,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
rolloutHandler.handleAll();
myRollout = findRollout(myRollout.getId());
myRollout = rolloutManagement.get(myRollout.getId());
assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.READY);
assertThat(myRollout.getTotalTargets()).isEqualTo(amountTargetsInGroup2and3 + amountTargetsInGroup1);
@@ -1658,7 +1635,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
final Long rolloutId = rolloutManagement.create(rolloutcreate, rolloutGroups, conditions).getId();
assertThat(findRollout(rolloutId)).satisfies(rollout -> {
assertThat(rolloutManagement.get(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 +1645,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
// first handle iteration will put rollout in ready state
rolloutHandler.handleAll();
assertThat(findRollout(rolloutId)).satisfies(rollout -> {
assertThat(rolloutManagement.get(rolloutId)).satisfies(rollout -> {
assertThat(rollout.getStatus()).isEqualTo(RolloutStatus.READY);
assertThat(rollout.getTotalTargets()).isEqualTo(amountTargetsInGroup1 + amountTargetsInGroup2);
});
@@ -1796,7 +1773,7 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
.build();
Rollout myRollout = rolloutManagement.create(rolloutToCreate, amountGroups, false, conditions);
myRollout = findRollout(myRollout.getId());
myRollout = rolloutManagement.get(myRollout.getId());
assertThat(myRollout.getStatus()).isEqualTo(RolloutStatus.CREATING);
@@ -2215,10 +2192,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.find(id).orElseThrow());
final JpaRollout rollout = (JpaRollout) rolloutManagement.get(id);
rollout.setStatus(status);
rolloutRepository.save(rollout);
assertThat(rolloutManagement.find(id).orElseThrow().getStatus()).isEqualTo(status);
assertThat(rolloutManagement.get(id).getStatus()).isEqualTo(status);
}
}
@@ -2229,10 +2206,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.find(id).orElseThrow());
final JpaRollout rollout = ((JpaRollout) rolloutManagement.get(id));
rollout.setActionType(actionType);
rolloutRepository.save(rollout);
assertThat(rolloutManagement.find(id).orElseThrow().getActionType()).isEqualTo(actionType);
assertThat(rolloutManagement.get(id).getActionType()).isEqualTo(actionType);
}
}
@@ -2355,16 +2332,12 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
}
private Rollout reloadRollout(final Rollout r) {
return findRollout(r.getId());
}
private Rollout findRollout(final Long myRolloutId) {
return rolloutManagement.find(myRolloutId).orElseThrow(NoSuchElementException::new);
return rolloutManagement.get(r.getId());
}
private void assertRolloutGroup(final long rolloutGroupId, final RolloutGroupStatus status,
final boolean isConfirmationRequired, final long totalTargets, final Status actionStatusToCheck) {
assertThat(rolloutGroupManagement.get(rolloutGroupId)).hasValueSatisfying(rolloutGroup -> {
assertThat(rolloutGroupManagement.get(rolloutGroupId)).satisfies(rolloutGroup -> {
assertThat(rolloutGroup.getStatus()).isEqualTo(status);
assertThat(rolloutGroup.isConfirmationRequired()).isEqualTo(isConfirmationRequired);
assertThat(rolloutGroup.getTotalTargets()).isEqualTo(totalTargets);
@@ -2419,17 +2392,14 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
.build();
}
private void validateRolloutGroupActionStatus(final RolloutGroup rolloutGroup,
final Map<TotalTargetCountStatus.Status, Long> expectedTargetCountStatus) {
final RolloutGroup rolloutGroupWithDetail = rolloutGroupManagement.getWithDetailedStatus(rolloutGroup.getId())
.get();
validateStatus(rolloutGroupWithDetail.getTotalTargetCountStatus(), expectedTargetCountStatus);
private void validateRolloutGroupActionStatus(
final RolloutGroup rolloutGroup, final Map<TotalTargetCountStatus.Status, Long> expectedTargetCountStatus) {
validateStatus(
rolloutGroupManagement.getWithDetailedStatus(rolloutGroup.getId()).getTotalTargetCountStatus(), expectedTargetCountStatus);
}
private void validateRolloutActionStatus(final Long rolloutId,
final Map<TotalTargetCountStatus.Status, Long> expectedTargetCountStatus) {
final Rollout rolloutWithDetail = rolloutManagement.getWithDetailedStatus(rolloutId).get();
validateStatus(rolloutWithDetail.getTotalTargetCountStatus(), expectedTargetCountStatus);
private void validateRolloutActionStatus(final Long rolloutId, final Map<TotalTargetCountStatus.Status, Long> expectedTargetCountStatus) {
validateStatus(rolloutManagement.getWithDetailedStatus(rolloutId).getTotalTargetCountStatus(), expectedTargetCountStatus);
}
private void validateStatus(final TotalTargetCountStatus totalTargetCountStatus,

View File

@@ -19,16 +19,14 @@ import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
import jakarta.validation.ConstraintViolationException;
import org.eclipse.hawkbit.artifact.exception.ArtifactBinaryNotFoundException;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.SoftwareModuleManagement.Create;
import org.eclipse.hawkbit.repository.SoftwareModuleManagement.Update;
import org.eclipse.hawkbit.repository.artifact.exception.ArtifactBinaryNotFoundException;
import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleCreatedEvent;
import org.eclipse.hawkbit.repository.exception.LockedException;
import org.eclipse.hawkbit.repository.jpa.RandomGeneratedInputStream;
@@ -185,8 +183,9 @@ class SoftwareModuleManagementTest
SoftwareModule moduleX = createSoftwareModuleWithArtifacts(osType, "modulex", "v1.0", 0);
// [STEP2]: Create newArtifactX and add it to SoftwareModuleX
artifactManagement.create(new ArtifactUpload(new ByteArrayInputStream(source), moduleX.getId(), "artifactx",
false, artifactSize));
artifactManagement.create(new ArtifactUpload(
new ByteArrayInputStream(source), null, artifactSize, null,
moduleX.getId(), "artifactx", false));
moduleX = softwareModuleManagement.find(moduleX.getId()).get();
final Artifact artifactX = moduleX.getArtifacts().iterator().next();
@@ -194,8 +193,9 @@ class SoftwareModuleManagementTest
SoftwareModule moduleY = createSoftwareModuleWithArtifacts(osType, "moduley", "v1.0", 0);
// [STEP4]: Assign the same ArtifactX to SoftwareModuleY
artifactManagement.create(new ArtifactUpload(new ByteArrayInputStream(source), moduleY.getId(), "artifactx",
false, artifactSize));
artifactManagement.create(new ArtifactUpload(
new ByteArrayInputStream(source), null, artifactSize, null,
moduleY.getId(), "artifactx", false));
moduleY = softwareModuleManagement.find(moduleY.getId()).get();
final Artifact artifactY = moduleY.getArtifacts().iterator().next();
@@ -231,15 +231,18 @@ class SoftwareModuleManagementTest
// [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));
artifactManagement.create(new ArtifactUpload(
new ByteArrayInputStream(source), null, artifactSize, null,
moduleX.getId(), "artifactx", false));
moduleX = softwareModuleManagement.find(moduleX.getId()).get();
final Artifact artifactX = moduleX.getArtifacts().iterator().next();
// [STEP2]: Create SoftwareModuleY and add the same ArtifactX
SoftwareModule moduleY = createSoftwareModuleWithArtifacts(osType, "moduley", "v1.0", 0);
artifactManagement.create(new ArtifactUpload(new ByteArrayInputStream(source), moduleY.getId(), "artifactx",
false, artifactSize));
artifactManagement.create(new ArtifactUpload(
new ByteArrayInputStream(source), null, artifactSize, null,
moduleY.getId(), "artifactx", false));
moduleY = softwareModuleManagement.find(moduleY.getId()).get();
final Artifact artifactY = moduleY.getArtifacts().iterator().next();
@@ -338,7 +341,8 @@ class SoftwareModuleManagementTest
void lockSoftwareModuleApplied() {
SoftwareModule softwareModule = testdataFactory.createSoftwareModule("sm-1");
final Long softwareModuleId = softwareModule.getId();
artifactManagement.create(new ArtifactUpload(new ByteArrayInputStream(new byte[] { 1 }), softwareModuleId, "artifact1", false, 1));
artifactManagement.create(new ArtifactUpload(
new ByteArrayInputStream(new byte[] { 1 }), null, 1, null, softwareModuleId, "artifact1", false));
// update software module reference since it is modified, old reference is stale
final int artifactCount = (softwareModule = softwareModuleManagement.find(softwareModuleId).orElseThrow()).getArtifacts().size();
assertThat(artifactCount).isNotZero();
@@ -346,8 +350,8 @@ class SoftwareModuleManagementTest
assertThat(softwareModuleManagement.find(softwareModuleId).map(SoftwareModule::isLocked).orElse(false)).isTrue();
// try add
final ArtifactUpload artifactUpload = new ArtifactUpload(new ByteArrayInputStream(new byte[] { 2 }), softwareModuleId, "artifact2",
false, 1);
final ArtifactUpload artifactUpload = new ArtifactUpload(
new ByteArrayInputStream(new byte[] { 2 }), null, 1, null, softwareModuleId, "artifact2", false);
assertThatExceptionOfType(LockedException.class)
.as("Attempt to modify a locked SM artifacts should throw an exception")
.isThrownBy(() -> artifactManagement.create(artifactUpload));
@@ -425,8 +429,9 @@ class SoftwareModuleManagementTest
final int artifactSize = 5 * 1024;
for (int i = 0; i < numberArtifacts; i++) {
artifactManagement.create(new ArtifactUpload(new RandomGeneratedInputStream(artifactSize),
softwareModule.getId(), "file" + (i + 1), false, artifactSize));
artifactManagement.create(new ArtifactUpload(
new RandomGeneratedInputStream(artifactSize), null, artifactSize, null,
softwareModule.getId(), "file" + (i + 1), false));
}
// Verify correct Creation of SoftwareModule and corresponding artifacts

View File

@@ -35,7 +35,6 @@ class SoftwareModuleTypeManagementTest extends AbstractRepositoryManagementTest<
@Test
void failIfReferNotExistingEntity() {
assertThat(softwareModuleTypeManagement.findByKey(NOT_EXIST_ID)).isNotPresent();
assertThat(softwareModuleTypeManagement.findByName(NOT_EXIST_ID)).isNotPresent();
verifyThrownExceptionBy(() -> softwareModuleTypeManagement.delete(NOT_EXIST_IDL), "SoftwareModuleType");
verifyThrownExceptionBy(() -> softwareModuleTypeManagement.update(Update.builder().id(NOT_EXIST_IDL).build()), "SoftwareModuleType");
}
@@ -88,19 +87,6 @@ class SoftwareModuleTypeManagementTest extends AbstractRepositoryManagementTest<
softwareModuleTypeRepository.findById(type.getId()).orElseThrow());
}
@SuppressWarnings("unchecked")
@Test
void findSoftwareModuleTypeByName() {
testdataFactory.createSoftwareModuleOs();
final SoftwareModuleType found = softwareModuleTypeManagement
.create(Create.builder().key("thetype").name("thename").build());
softwareModuleTypeManagement
.create(Create.builder().key("thetype2").name("anothername").build());
Assertions.assertThat(((SoftwareModuleTypeManagement<SoftwareModuleType>) softwareModuleTypeManagement).findByName("thename"))
.as("Type with given name").contains(found);
}
/**
* Verifies that the creation of a softwareModuleType is failing because of invalid max assignment
*/

View File

@@ -21,7 +21,7 @@ import org.eclipse.hawkbit.repository.model.ArtifactUpload;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.report.model.TenantUsage;
import org.eclipse.hawkbit.repository.model.report.TenantUsage;
import org.eclipse.hawkbit.repository.test.util.DisposableSqlTestDatabaseExtension;
import org.eclipse.hawkbit.repository.test.util.SecurityContextSwitch;
import org.junit.jupiter.api.Test;
@@ -38,7 +38,7 @@ class SystemManagementTest extends AbstractJpaIntegrationTest {
* Ensures that findTenants returns all tenants and not only restricted to the tenant which currently is logged in
*/
@Test
void findTenantsReturnsAllTenantsNotOnlyWhichLoggedIn() throws Exception {
void findTenantsReturnsAllTenantsNotOnlyWhichLoggedIn() {
assertThat(systemManagement.findTenants(PAGE).getContent()).hasSize(1);
createTestTenantsForSystemStatistics(2, 0, 0, 0);
@@ -50,7 +50,7 @@ class SystemManagementTest extends AbstractJpaIntegrationTest {
* Ensures that getSystemUsageStatisticsWithTenants returns the usage of all tenants and not only the first 1000 (max page size).
*/
@Test
void systemUsageReportCollectsStatisticsOfManyTenants() throws Exception {
void systemUsageReportCollectsStatisticsOfManyTenants() {
// Prepare tenants
createTestTenantsForSystemStatistics(1050, 0, 0, 0);
@@ -62,7 +62,7 @@ class SystemManagementTest extends AbstractJpaIntegrationTest {
* Checks that the system report calculates correctly the artifact size of all tenants in the system. It ignores deleted software modules with their artifacts.
*/
@Test
void systemUsageReportCollectsArtifactsOfAllTenants() throws Exception {
void systemUsageReportCollectsArtifactsOfAllTenants() {
// Prepare tenants
createTestTenantsForSystemStatistics(2, 1234, 0, 0);
@@ -88,7 +88,7 @@ class SystemManagementTest extends AbstractJpaIntegrationTest {
* Checks that the system report calculates correctly the targets size of all tenants in the system
*/
@Test
void systemUsageReportCollectsTargetsOfAllTenants() throws Exception {
void systemUsageReportCollectsTargetsOfAllTenants() {
// Prepare tenants
createTestTenantsForSystemStatistics(2, 0, 100, 0);
@@ -110,7 +110,7 @@ class SystemManagementTest extends AbstractJpaIntegrationTest {
* Checks that the system report calculates correctly the actions size of all tenants in the system
*/
@Test
void systemUsageReportCollectsActionsOfAllTenants() throws Exception {
void systemUsageReportCollectsActionsOfAllTenants() {
// Prepare tenants
createTestTenantsForSystemStatistics(2, 0, 20, 2);
@@ -129,7 +129,7 @@ class SystemManagementTest extends AbstractJpaIntegrationTest {
assertThat(tenants).containsOnly(new TenantUsage("DEFAULT"), tenantUsage0, tenantUsage1);
}
private byte[] createTestTenantsForSystemStatistics(final int tenants, final int artifactSize, final int targets, final int updates) {
private void createTestTenantsForSystemStatistics(final int tenants, final int artifactSize, final int targets, final int updates) {
final Random randomgen = new Random();
final byte[] random = new byte[artifactSize];
randomgen.nextBytes(random);
@@ -158,8 +158,6 @@ class SystemManagementTest extends AbstractJpaIntegrationTest {
return null;
});
}
return random;
}
private List<Target> createTestTargets(final int targets) {
@@ -170,14 +168,14 @@ class SystemManagementTest extends AbstractJpaIntegrationTest {
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
artifactManagement.create(
new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file1", false, random.length));
new ArtifactUpload(new ByteArrayInputStream(random), null, random.length, null, sm.getId(), "file1", false));
}
private void createDeletedTestArtifact(final byte[] random) {
final DistributionSet ds = testdataFactory.createDistributionSet("deleted garbage", true);
ds.getModules().forEach(module -> {
artifactManagement.create(
new ArtifactUpload(new ByteArrayInputStream(random), module.getId(), "file1", false, random.length));
new ArtifactUpload(new ByteArrayInputStream(random), null, random.length, null, module.getId(), "file1", false));
softwareModuleManagement.delete(module.getId());
});
}

View File

@@ -45,7 +45,7 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
assignDistributionSet(assignedSet, assignedtargets);
// get final updated version of targets
assignedtargets = targetManagement.getByControllerId(assignedtargets.stream().map(Target::getControllerId).toList());
assignedtargets = targetManagement.findByControllerId(assignedtargets.stream().map(Target::getControllerId).toList());
assertThat(targetManagement.findByAssignedDistributionSet(assignedSet.getId(), PAGE))
.as("Contains the assigned targets").containsAll(assignedtargets)
@@ -90,7 +90,7 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
assignDistributionSet(assignedSet, installedtargets);
// get final updated version of targets
installedtargets = targetManagement.getByControllerId(installedtargets.stream().map(Target::getControllerId).toList());
installedtargets = targetManagement.findByControllerId(installedtargets.stream().map(Target::getControllerId).toList());
assertThat(targetManagement.findByInstalledDistributionSet(installedSet.getId(), PAGE))
.as("Contains the assigned targets").containsAll(installedtargets)

View File

@@ -233,15 +233,15 @@ class TargetManagementTest extends AbstractRepositoryManagementWithMetadataTest<
assignDistributionSet(testDs2.getId(), "4711");
implicitLock(testDs2);
Target target = targetManagement.getByControllerId("4711").orElseThrow(IllegalStateException::new);
final Target target = targetManagement.getByControllerId("4711");
// read data
assertThat(target.getLastTargetQuery()).as("Target query is not work").isGreaterThanOrEqualTo(current);
final DistributionSet assignedDs = deploymentManagement.getAssignedDistributionSet("4711")
final DistributionSet assignedDs = deploymentManagement.findAssignedDistributionSet("4711")
.orElseThrow(NoSuchElementException::new);
assertThat(assignedDs).as("Assigned ds size is wrong").isEqualTo(testDs2);
final DistributionSet installedDs = deploymentManagement.getInstalledDistributionSet("4711")
final DistributionSet installedDs = deploymentManagement.findInstalledDistributionSet("4711")
.orElseThrow(NoSuchElementException::new);
assertThat(installedDs).as("Installed ds is wrong").isEqualTo(testDs1);
}
@@ -266,17 +266,13 @@ class TargetManagementTest extends AbstractRepositoryManagementWithMetadataTest<
final List<? extends TargetTag> t2Tags = testdataFactory.createTargetTags(noT2Tags, "tag2");
t2Tags.forEach(tag -> targetManagement.assignTag(Collections.singletonList(t2.getControllerId()), tag.getId()));
final Target t11 = targetManagement.getByControllerId(t1.getControllerId())
.orElseThrow(IllegalStateException::new);
assertThat(getTargetTags(t11.getControllerId())).as("Tag size is wrong")
.hasSize(noT1Tags).containsAll(t1Tags);
final Target t11 = targetManagement.getByControllerId(t1.getControllerId());
assertThat(getTargetTags(t11.getControllerId())).as("Tag size is wrong").hasSize(noT1Tags).containsAll(t1Tags);
assertThat(getTargetTags(t11.getControllerId())).as("Tag size is wrong")
.hasSize(noT1Tags).doesNotContain(toArray(t2Tags, TargetTag.class));
final Target t21 = targetManagement.getByControllerId(t2.getControllerId())
.orElseThrow(IllegalStateException::new);
assertThat(getTargetTags(t21.getControllerId())).as("Tag size is wrong")
.hasSize(noT2Tags).containsAll(t2Tags);
final Target t21 = targetManagement.getByControllerId(t2.getControllerId());
assertThat(getTargetTags(t21.getControllerId())).as("Tag size is wrong").hasSize(noT2Tags).containsAll(t2Tags);
assertThat(getTargetTags(t21.getControllerId())).as("Tag size is wrong")
.hasSize(noT2Tags).doesNotContain(toArray(t1Tags, TargetTag.class));
}
@@ -445,8 +441,7 @@ class TargetManagementTest extends AbstractRepositoryManagementWithMetadataTest<
controllerManagement.findOrRegisterTargetIfItDoesNotExist(knownTargetControllerId, new URI("http://127.0.0.1"));
SecurityContextSwitch.getAs(SecurityContextSwitch.withUser("bumlux", "READ_TARGET"), () -> {
final Target findTargetByControllerID = targetManagement.getByControllerId(knownTargetControllerId)
.orElseThrow(IllegalStateException::new);
final Target findTargetByControllerID = targetManagement.getByControllerId(knownTargetControllerId);
assertThat(findTargetByControllerID).isNotNull();
assertThat(findTargetByControllerID.getPollStatus()).isNotNull();
return null;
@@ -485,8 +480,7 @@ class TargetManagementTest extends AbstractRepositoryManagementWithMetadataTest<
assertThat(target.isRequestControllerAttributes()).isFalse();
targetManagement.update(Update.builder().id(target.getId()).requestControllerAttributes(true).build());
final Target updated = targetManagement.getByControllerId(knownControllerId).orElseThrow();
assertThat(updated.isRequestControllerAttributes()).isTrue();
assertThat(targetManagement.getByControllerId(knownControllerId).isRequestControllerAttributes()).isTrue();
}
/**
@@ -1093,7 +1087,7 @@ class TargetManagementTest extends AbstractRepositoryManagementWithMetadataTest<
private void checkTargetHasNotTags(final Iterable<Target> targets, final TargetTag... tags) {
for (final Target tl : targets) {
targetManagement.getByControllerId(tl.getControllerId()).orElseThrow();
assertThat(targetManagement.getByControllerId(tl.getControllerId())).isNotNull();
for (final Tag tag : tags) {
for (final Tag tt : getTargetTags(tl.getControllerId())) {
if (tag.getName().equals(tt.getName())) {

View File

@@ -54,7 +54,7 @@ class TargetTagManagementTest extends AbstractRepositoryManagementTest<TargetTag
// toggle A only -> A is now assigned
List<Target> result = assignTag(groupA, tag);
assertThat(result)
.containsAll(targetManagement.getByControllerId(groupA.stream().map(Target::getControllerId).toList()))
.containsAll(targetManagement.findByControllerId(groupA.stream().map(Target::getControllerId).toList()))
.size().isEqualTo(20);
assertThat(targetManagement.findByTag(tag.getId(), Pageable.unpaged()).getContent().stream().map(Target::getControllerId).sorted()
.toList())
@@ -64,7 +64,7 @@ class TargetTagManagementTest extends AbstractRepositoryManagementTest<TargetTag
final Collection<Target> groupAB = concat(groupA, groupB);
result = assignTag(groupAB, tag);
assertThat(result)
.containsAll(targetManagement.getByControllerId(groupAB.stream().map(Target::getControllerId).toList()))
.containsAll(targetManagement.findByControllerId(groupAB.stream().map(Target::getControllerId).toList()))
.size().isEqualTo(40);
assertThat(targetManagement.findByTag(tag.getId(), Pageable.unpaged()).getContent().stream().map(Target::getControllerId).sorted()
.toList())
@@ -73,7 +73,7 @@ class TargetTagManagementTest extends AbstractRepositoryManagementTest<TargetTag
// toggle A+B -> both unassigned
result = unassignTag(groupAB, tag);
assertThat(result)
.containsAll(targetManagement.getByControllerId(groupAB.stream().map(Target::getControllerId).toList()))
.containsAll(targetManagement.findByControllerId(groupAB.stream().map(Target::getControllerId).toList()))
.size().isEqualTo(40);
assertThat(targetManagement.findByTag(tag.getId(), Pageable.unpaged()).getContent()).isEmpty();
}

View File

@@ -60,7 +60,7 @@ class EntityInterceptorListenerTest extends AbstractJpaIntegrationTest {
final Target targetToBeCreated = testdataFactory.createTarget("targetToBeCreated");
final Target loadedTarget = targetManagement.getByControllerId(targetToBeCreated.getControllerId()).get();
final Target loadedTarget = targetManagement.getByControllerId(targetToBeCreated.getControllerId());
assertThat(postLoadEntityListener.getEntity()).isNotNull();
assertThat(postLoadEntityListener.getEntity()).isEqualTo(loadedTarget);
}

View File

@@ -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.find(rollout.getId()).get();
rollout = rolloutManagement.get(rollout.getId());
}
/**

View File

@@ -40,9 +40,9 @@ class RsqlRolloutGroupFieldTest extends AbstractJpaIntegrationTest {
testdataFactory.createTargets(amountTargets, "rollout", "rollout");
final DistributionSet dsA = testdataFactory.createDistributionSet("");
rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
rollout = rolloutManagement.find(rollout.getId()).get();
rollout = rolloutManagement.get(rollout.getId());
this.rolloutGroupId = rolloutGroupManagement.findByRollout(rollout.getId(), PAGE).getContent().get(0).getId();
rolloutGroupId = rolloutGroupManagement.findByRollout(rollout.getId(), PAGE).getContent().get(0).getId();
}
/**