Sonar Fixes (#2240)

Signed-off-by: Avgustin Marinov <Avgustin.Marinov@bosch.com>
This commit is contained in:
Avgustin Marinov
2025-01-27 11:45:14 +02:00
committed by GitHub
parent cbadd4c249
commit c766fd76da
24 changed files with 374 additions and 346 deletions

View File

@@ -79,6 +79,7 @@ public class TargetWithActionType {
* cron expression is relative to this time zone. * cron expression is relative to this time zone.
* @throws InvalidMaintenanceScheduleException if the parameters do not define a valid maintenance schedule. * @throws InvalidMaintenanceScheduleException if the parameters do not define a valid maintenance schedule.
*/ */
@SuppressWarnings("java:S107")
public TargetWithActionType( public TargetWithActionType(
final String controllerId, final ActionType actionType, final long forceTime, final Integer weight, final String controllerId, final ActionType actionType, final long forceTime, final Integer weight,
final String maintenanceSchedule, final String maintenanceWindowDuration, final String maintenanceWindowTimeZone, final String maintenanceSchedule, final String maintenanceWindowDuration, final String maintenanceWindowTimeZone,

View File

@@ -113,12 +113,7 @@ public class TotalTargetCountStatus {
return Status.FINISHED; return Status.FINISHED;
case CANCELED: case CANCELED:
return Status.CANCELLED; return Status.CANCELLED;
case RETRIEVED: case RETRIEVED, RUNNING, WARNING, DOWNLOAD, WAIT_FOR_CONFIRMATION, CANCELING:
case RUNNING:
case WARNING:
case DOWNLOAD:
case WAIT_FOR_CONFIRMATION:
case CANCELING:
return Status.RUNNING; return Status.RUNNING;
case DOWNLOADED: case DOWNLOADED:
return Action.ActionType.DOWNLOAD_ONLY == rolloutType ? Status.FINISHED : Status.RUNNING; return Action.ActionType.DOWNLOAD_ONLY == rolloutType ? Status.FINISHED : Status.RUNNING;

View File

@@ -15,7 +15,6 @@ import java.time.format.DateTimeParseException;
import org.eclipse.hawkbit.repository.exception.TenantConfigurationValidatorException; import org.eclipse.hawkbit.repository.exception.TenantConfigurationValidatorException;
import org.eclipse.hawkbit.tenancy.configuration.ControllerPollProperties; import org.eclipse.hawkbit.tenancy.configuration.ControllerPollProperties;
import org.eclipse.hawkbit.tenancy.configuration.DurationHelper; import org.eclipse.hawkbit.tenancy.configuration.DurationHelper;
import org.springframework.beans.factory.annotation.Autowired;
/** /**
* This class is used to validate, that the property is a String and that it is in the correct duration format. * This class is used to validate, that the property is a String and that it is in the correct duration format.

View File

@@ -22,7 +22,7 @@ import org.junit.jupiter.api.Test;
@Feature("Component Tests - TotalTargetCountStatus") @Feature("Component Tests - TotalTargetCountStatus")
@Story("TotalTargetCountStatus should correctly present finished DOWNLOAD_ONLY actions") @Story("TotalTargetCountStatus should correctly present finished DOWNLOAD_ONLY actions")
public class TotalTargetCountStatusTest { class TotalTargetCountStatusTest {
private final List<TotalTargetCountActionStatus> targetCountActionStatuses = Arrays.asList( private final List<TotalTargetCountActionStatus> targetCountActionStatuses = Arrays.asList(
new TotalTargetCountActionStatus(Action.Status.SCHEDULED, 1L), new TotalTargetCountActionStatus(Action.Status.SCHEDULED, 1L),
@@ -39,7 +39,7 @@ public class TotalTargetCountStatusTest {
@Test @Test
@Description("Different Action Statuses should be correctly mapped to the corresponding " + @Description("Different Action Statuses should be correctly mapped to the corresponding " +
"TotalTargetCountStatus.Status") "TotalTargetCountStatus.Status")
public void shouldCorrectlyMapActionStatuses() { void shouldCorrectlyMapActionStatuses() {
TotalTargetCountStatus status = new TotalTargetCountStatus(targetCountActionStatuses, 55L, TotalTargetCountStatus status = new TotalTargetCountStatus(targetCountActionStatuses, 55L,
Action.ActionType.FORCED); Action.ActionType.FORCED);
assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.SCHEDULED)).isEqualTo(1L); assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.SCHEDULED)).isEqualTo(1L);
@@ -47,28 +47,28 @@ public class TotalTargetCountStatusTest {
assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.FINISHED)).isEqualTo(3L); assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.FINISHED)).isEqualTo(3L);
assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.CANCELLED)).isEqualTo(4L); assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.CANCELLED)).isEqualTo(4L);
assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.RUNNING)).isEqualTo(45L); assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.RUNNING)).isEqualTo(45L);
assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.NOTSTARTED)).isEqualTo(0L); assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.NOTSTARTED)).isZero();
assertThat(status.getFinishedPercent()).isEqualTo((float) 100 * 3 / 55); assertThat(status.getFinishedPercent()).isEqualTo((float) 100 * 3 / 55);
} }
@Test @Test
@Description("When an empty list is passed to the TotalTargetCountStatus, all actions should be displayed as " + @Description("When an empty list is passed to the TotalTargetCountStatus, all actions should be displayed as " +
"NOTSTARTED") "NOTSTARTED")
public void shouldCorrectlyMapActionStatusesToNotStarted() { void shouldCorrectlyMapActionStatusesToNotStarted() {
TotalTargetCountStatus status = new TotalTargetCountStatus(Collections.emptyList(), 55L, TotalTargetCountStatus status = new TotalTargetCountStatus(Collections.emptyList(), 55L,
Action.ActionType.FORCED); Action.ActionType.FORCED);
assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.SCHEDULED)).isEqualTo(0L); assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.SCHEDULED)).isZero();
assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.ERROR)).isEqualTo(0L); assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.ERROR)).isZero();
assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.FINISHED)).isEqualTo(0L); assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.FINISHED)).isZero();
assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.CANCELLED)).isEqualTo(0L); assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.CANCELLED)).isZero();
assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.RUNNING)).isEqualTo(0L); assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.RUNNING)).isZero();
assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.NOTSTARTED)).isEqualTo(55L); assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.NOTSTARTED)).isEqualTo(55L);
assertThat(status.getFinishedPercent()).isEqualTo(0); assertThat(status.getFinishedPercent()).isZero();
} }
@Test @Test
@Description("DownloadOnly actions should be displayed as FINISHED when they have ActionStatus.DOWNLOADED") @Description("DownloadOnly actions should be displayed as FINISHED when they have ActionStatus.DOWNLOADED")
public void shouldCorrectlyMapActionStatusesInDownloadOnlyCase() { void shouldCorrectlyMapActionStatusesInDownloadOnlyCase() {
TotalTargetCountStatus status = new TotalTargetCountStatus(targetCountActionStatuses, 55L, TotalTargetCountStatus status = new TotalTargetCountStatus(targetCountActionStatuses, 55L,
Action.ActionType.DOWNLOAD_ONLY); Action.ActionType.DOWNLOAD_ONLY);
assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.SCHEDULED)).isEqualTo(1L); assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.SCHEDULED)).isEqualTo(1L);
@@ -76,7 +76,7 @@ public class TotalTargetCountStatusTest {
assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.FINISHED)).isEqualTo(13L); assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.FINISHED)).isEqualTo(13L);
assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.CANCELLED)).isEqualTo(4L); assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.CANCELLED)).isEqualTo(4L);
assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.RUNNING)).isEqualTo(35L); assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.RUNNING)).isEqualTo(35L);
assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.NOTSTARTED)).isEqualTo(0L); assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.NOTSTARTED)).isZero();
assertThat(status.getFinishedPercent()).isEqualTo((float) 100 * 13 / 55); assertThat(status.getFinishedPercent()).isEqualTo((float) 100 * 13 / 55);
} }
} }

View File

@@ -11,8 +11,6 @@ package org.eclipse.hawkbit.repository.jpa.model.helper;
import lombok.AccessLevel; import lombok.AccessLevel;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.Setter;
import org.eclipse.hawkbit.repository.SystemManagement;
import org.eclipse.hawkbit.tenancy.TenantAware; import org.eclipse.hawkbit.tenancy.TenantAware;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;

View File

@@ -12,7 +12,6 @@ package org.eclipse.hawkbit.repository.jpa;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import org.eclipse.hawkbit.tenancy.TenantAware; import org.eclipse.hawkbit.tenancy.TenantAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -22,12 +21,14 @@ import org.springframework.stereotype.Service;
@Service @Service
public class TenantKeyGenerator implements KeyGenerator { public class TenantKeyGenerator implements KeyGenerator {
@Autowired private final TenantAware tenantAware;
private TenantAware tenantAware;
public TenantKeyGenerator(final TenantAware tenantAware) {
this.tenantAware = tenantAware;
}
@Override @Override
public Object generate(final Object target, final Method method, final Object... params) { public Object generate(final Object target, final Method method, final Object... params) {
return tenantAware.getCurrentTenant().toUpperCase(); return tenantAware.getCurrentTenant().toUpperCase();
} }
} }

View File

@@ -13,7 +13,6 @@ import java.util.List;
import org.eclipse.hawkbit.repository.jpa.model.JpaTargetType; import org.eclipse.hawkbit.repository.jpa.model.JpaTargetType;
import org.eclipse.hawkbit.repository.jpa.specifications.TargetTypeSpecification; import org.eclipse.hawkbit.repository.jpa.specifications.TargetTypeSpecification;
import org.eclipse.hawkbit.repository.model.TargetType;
import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;

View File

@@ -15,8 +15,10 @@ import jakarta.persistence.criteria.SetJoin;
import lombok.AccessLevel; import lombok.AccessLevel;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import org.eclipse.hawkbit.repository.jpa.model.AbstractJpaBaseEntity_;
import org.eclipse.hawkbit.repository.jpa.model.AbstractJpaNamedEntity_;
import org.eclipse.hawkbit.repository.jpa.model.AbstractJpaTypeEntity_;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType_;
import org.eclipse.hawkbit.repository.jpa.model.JpaTargetType; import org.eclipse.hawkbit.repository.jpa.model.JpaTargetType;
import org.eclipse.hawkbit.repository.jpa.model.JpaTargetType_; import org.eclipse.hawkbit.repository.jpa.model.JpaTargetType_;
import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.DistributionSetType;
@@ -36,7 +38,7 @@ public final class TargetTypeSpecification {
* @return the {@link TargetType} {@link Specification} * @return the {@link TargetType} {@link Specification}
*/ */
public static Specification<JpaTargetType> hasIdIn(final Collection<Long> ids) { public static Specification<JpaTargetType> hasIdIn(final Collection<Long> ids) {
return (targetRoot, query, cb) -> targetRoot.get(JpaTargetType_.id).in(ids); return (targetRoot, query, cb) -> targetRoot.get(AbstractJpaBaseEntity_.id).in(ids);
} }
/** /**
@@ -48,32 +50,28 @@ public final class TargetTypeSpecification {
public static Specification<JpaTargetType> hasDsSetType(final Long dsTypeId) { public static Specification<JpaTargetType> hasDsSetType(final Long dsTypeId) {
return (targetRoot, query, cb) -> { return (targetRoot, query, cb) -> {
final SetJoin<JpaTargetType, JpaDistributionSetType> join = targetRoot.join(JpaTargetType_.distributionSetTypes); final SetJoin<JpaTargetType, JpaDistributionSetType> join = targetRoot.join(JpaTargetType_.distributionSetTypes);
return cb.equal(join.get(JpaDistributionSetType_.id), dsTypeId); return cb.equal(join.get(AbstractJpaBaseEntity_.id), dsTypeId);
}; };
} }
/** /**
* {@link Specification} for retrieving {@link TargetType} with * {@link Specification} for retrieving {@link TargetType} with given {@link TargetType#getKey()} including fetching the elements list.
* given {@link TargetType#getKey()} including fetching the
* elements list.
* *
* @param key to search * @param key to search
* @return the {@link TargetType} {@link Specification} * @return the {@link TargetType} {@link Specification}
*/ */
public static Specification<JpaTargetType> hasKey(final String key) { public static Specification<JpaTargetType> hasKey(final String key) {
return (targetRoot, query, cb) -> cb.equal(targetRoot.get(JpaTargetType_.key), key); return (targetRoot, query, cb) -> cb.equal(targetRoot.get(AbstractJpaTypeEntity_.key), key);
} }
/** /**
* {@link Specification} for retrieving {@link TargetType} with * {@link Specification} for retrieving {@link TargetType} with given {@link TargetType#getName()} including fetching the elements list.
* given {@link TargetType#getName()} including fetching the
* elements list.
* *
* @param name to search * @param name to search
* @return the {@link TargetType} {@link Specification} * @return the {@link TargetType} {@link Specification}
*/ */
public static Specification<JpaTargetType> hasName(final String name) { public static Specification<JpaTargetType> hasName(final String name) {
return (targetRoot, query, cb) -> cb.equal(targetRoot.get(JpaTargetType_.name), name); return (targetRoot, query, cb) -> cb.equal(targetRoot.get(AbstractJpaNamedEntity_.name), name);
} }
/** /**
@@ -83,6 +81,6 @@ public final class TargetTypeSpecification {
* @return the {@link TargetType} {@link Specification} * @return the {@link TargetType} {@link Specification}
*/ */
public static Specification<JpaTargetType> likeName(final String name) { public static Specification<JpaTargetType> likeName(final String name) {
return (targetRoot, query, cb) -> cb.like(cb.lower(targetRoot.get(JpaTargetType_.name)), name.toLowerCase()); return (targetRoot, query, cb) -> cb.like(cb.lower(targetRoot.get(AbstractJpaNamedEntity_.name)), name.toLowerCase());
} }
} }

View File

@@ -108,11 +108,11 @@ public final class WeightValidationHelper {
* @param hasNoWeight indicator of the weight if it doesn't have a numerical value * @param hasNoWeight indicator of the weight if it doesn't have a numerical value
*/ */
public void validateWeight(final boolean hasWeight, final boolean hasNoWeight) { public void validateWeight(final boolean hasWeight, final boolean hasNoWeight) {
// remove bypassing the weight enforcement as soon as weight can be set // remove bypassing the weight enforcement as soon as weight can be set via UI
// via UI
final boolean bypassWeightEnforcement = true; final boolean bypassWeightEnforcement = true;
final boolean multiAssignmentsEnabled = TenantConfigHelper final boolean multiAssignmentsEnabled = TenantConfigHelper
.usingContext(systemSecurityContext, tenantConfigurationManagement).isMultiAssignmentsEnabled(); .usingContext(systemSecurityContext, tenantConfigurationManagement)
.isMultiAssignmentsEnabled();
if (bypassWeightEnforcement) { if (bypassWeightEnforcement) {
return; return;
} else if (multiAssignmentsEnabled && hasNoWeight) { } else if (multiAssignmentsEnabled && hasNoWeight) {

View File

@@ -36,7 +36,6 @@ import org.eclipse.hawkbit.repository.model.Rollout;
import org.eclipse.hawkbit.repository.model.RolloutGroup; import org.eclipse.hawkbit.repository.model.RolloutGroup;
import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.eclipse.hawkbit.repository.model.TargetFilterQuery;
import org.eclipse.hawkbit.repository.model.TargetTag;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -126,15 +125,16 @@ class TargetAccessControllerTest extends AbstractAccessControllerTest {
final Target readOnlyTarget = targetManagement final Target readOnlyTarget = targetManagement
.create(entityFactory.target().create().controllerId("device02").status(TargetUpdateStatus.REGISTERED)); .create(entityFactory.target().create().controllerId("device02").status(TargetUpdateStatus.REGISTERED));
final String readOnlyTargetControllerId = readOnlyTarget.getControllerId();
final Target hiddenTarget = targetManagement final Target hiddenTarget = targetManagement
.create(entityFactory.target().create().controllerId("device03").status(TargetUpdateStatus.REGISTERED)); .create(entityFactory.target().create().controllerId("device03").status(TargetUpdateStatus.REGISTERED));
final TargetTag myTag = targetTagManagement.create(entityFactory.tag().create().name("myTag")); final Long myTagId = targetTagManagement.create(entityFactory.tag().create().name("myTag")).getId();
// perform tag assignment before setting access rules // perform tag assignment before setting access rules
targetManagement.assignTag(Arrays.asList(permittedTarget.getControllerId(), readOnlyTarget.getControllerId(), targetManagement.assignTag(Arrays.asList(permittedTarget.getControllerId(), readOnlyTargetControllerId,
hiddenTarget.getControllerId()), myTag.getId()); hiddenTarget.getControllerId()), myTagId);
// define access controlling rule // define access controlling rule
testAccessControlManger.deleteAllRules(); testAccessControlManger.deleteAllRules();
@@ -145,24 +145,24 @@ class TargetAccessControllerTest extends AbstractAccessControllerTest {
// verify targetManagement#findByTag // verify targetManagement#findByTag
assertThat( assertThat(
targetManagement.findByTag(Pageable.unpaged(), myTag.getId()).get().map(Identifiable::getId).toList()) targetManagement.findByTag(Pageable.unpaged(), myTagId).get().map(Identifiable::getId).toList())
.containsOnly(permittedTarget.getId(), readOnlyTarget.getId()); .containsOnly(permittedTarget.getId(), readOnlyTarget.getId());
// verify targetManagement#findByRsqlAndTag // verify targetManagement#findByRsqlAndTag
assertThat(targetManagement.findByRsqlAndTag(Pageable.unpaged(), "id==*", myTag.getId()).get() assertThat(targetManagement.findByRsqlAndTag(Pageable.unpaged(), "id==*", myTagId).get()
.map(Identifiable::getId).toList()).containsOnly(permittedTarget.getId(), readOnlyTarget.getId()); .map(Identifiable::getId).toList()).containsOnly(permittedTarget.getId(), readOnlyTarget.getId());
// verify targetManagement#assignTag on permitted target // verify targetManagement#assignTag on permitted target
assertThat(targetManagement.assignTag(Collections.singletonList(permittedTarget.getControllerId()), myTag.getId())) assertThat(targetManagement.assignTag(Collections.singletonList(permittedTarget.getControllerId()), myTagId))
.hasSize(1); .hasSize(1);
// verify targetManagement#unassignTag on permitted target // verify targetManagement#unassignTag on permitted target
assertThat(targetManagement.unassignTag(Collections.singletonList(permittedTarget.getControllerId()), myTag.getId())) assertThat(targetManagement.unassignTag(Collections.singletonList(permittedTarget.getControllerId()), myTagId))
.hasSize(1); .hasSize(1);
// verify targetManagement#assignTag on permitted target // verify targetManagement#assignTag on permitted target
assertThat(targetManagement.assignTag(Collections.singletonList(permittedTarget.getControllerId()), myTag.getId())) assertThat(targetManagement.assignTag(Collections.singletonList(permittedTarget.getControllerId()), myTagId))
.hasSize(1); .hasSize(1);
// verify targetManagement#unAssignTag on permitted target // verify targetManagement#unAssignTag on permitted target
assertThat(targetManagement.unassignTag(List.of(permittedTarget.getControllerId()), myTag.getId()).get(0).getControllerId()) assertThat(targetManagement.unassignTag(List.of(permittedTarget.getControllerId()), myTagId).get(0).getControllerId())
.isEqualTo(permittedTarget.getControllerId()); .isEqualTo(permittedTarget.getControllerId());
// assignment is denied for readOnlyTarget (read, but no update permissions) // assignment is denied for readOnlyTarget (read, but no update permissions)
@@ -175,27 +175,30 @@ class TargetAccessControllerTest extends AbstractAccessControllerTest {
// .isInstanceOf(InsufficientPermissionException.class); // .isInstanceOf(InsufficientPermissionException.class);
// assignment is denied for readOnlyTarget (read, but no update permissions) // assignment is denied for readOnlyTarget (read, but no update permissions)
assertThatThrownBy(() -> targetManagement.assignTag(Collections.singletonList(readOnlyTarget.getControllerId()), myTag.getId())) final List<String> readTargetControllerIdList = Collections.singletonList(readOnlyTargetControllerId);
assertThatThrownBy(() -> targetManagement.assignTag(readTargetControllerIdList, myTagId))
.as("Missing update permissions for target to toggle tag assignment.") .as("Missing update permissions for target to toggle tag assignment.")
.isInstanceOfAny(InsufficientPermissionException.class); .isInstanceOfAny(InsufficientPermissionException.class);
// assignment is denied for readOnlyTarget (read, but no update permissions) // assignment is denied for readOnlyTarget (read, but no update permissions)
assertThatThrownBy(() -> targetManagement.unassignTag(List.of(readOnlyTarget.getControllerId()), myTag.getId())) final List<String> readOnlyTargetControllerIdList = List.of(readOnlyTargetControllerId);
assertThatThrownBy(() -> targetManagement.unassignTag(readOnlyTargetControllerIdList, myTagId))
.as("Missing update permissions for target to toggle tag assignment.") .as("Missing update permissions for target to toggle tag assignment.")
.isInstanceOf(InsufficientPermissionException.class); .isInstanceOf(InsufficientPermissionException.class);
// assignment is denied for hiddenTarget since it's hidden // assignment is denied for hiddenTarget since it's hidden
assertThatThrownBy(() -> targetManagement.assignTag(Collections.singletonList(hiddenTarget.getControllerId()), myTag.getId())) final List<String> hiddenTargetControllerIdList = Collections.singletonList(hiddenTarget.getControllerId());
assertThatThrownBy(() -> targetManagement.assignTag(hiddenTargetControllerIdList, myTagId))
.as("Missing update permissions for target to toggle tag assignment.") .as("Missing update permissions for target to toggle tag assignment.")
.isInstanceOf(InsufficientPermissionException.class); .isInstanceOf(InsufficientPermissionException.class);
// assignment is denied for hiddenTarget since it's hidden // assignment is denied for hiddenTarget since it's hidden
assertThatThrownBy(() -> targetManagement.assignTag(Collections.singletonList(hiddenTarget.getControllerId()), myTag.getId())) assertThatThrownBy(() -> targetManagement.assignTag(hiddenTargetControllerIdList, myTagId))
.as("Missing update permissions for target to toggle tag assignment.") .as("Missing update permissions for target to toggle tag assignment.")
.isInstanceOf(InsufficientPermissionException.class); .isInstanceOf(InsufficientPermissionException.class);
// assignment is denied for hiddenTarget since it's hidden // assignment is denied for hiddenTarget since it's hidden
assertThatThrownBy(() -> targetManagement.unassignTag(List.of(hiddenTarget.getControllerId()), myTag.getId())) assertThatThrownBy(() -> targetManagement.unassignTag(hiddenTargetControllerIdList, myTagId))
.as("Missing update permissions for target to toggle tag assignment.") .as("Missing update permissions for target to toggle tag assignment.")
.isInstanceOf(InsufficientPermissionException.class); .isInstanceOf(InsufficientPermissionException.class);
} }
@@ -206,8 +209,9 @@ class TargetAccessControllerTest extends AbstractAccessControllerTest {
permitAllOperations(AccessController.Operation.READ); permitAllOperations(AccessController.Operation.READ);
permitAllOperations(AccessController.Operation.CREATE); permitAllOperations(AccessController.Operation.CREATE);
permitAllOperations(AccessController.Operation.UPDATE); permitAllOperations(AccessController.Operation.UPDATE);
final DistributionSet ds = testdataFactory.createDistributionSet("myDs");
distributionSetManagement.lock(ds.getId()); final Long dsId = testdataFactory.createDistributionSet("myDs").getId();
distributionSetManagement.lock(dsId);
// entities created - reset rules // entities created - reset rules
testAccessControlManger.deleteAllRules(); testAccessControlManger.deleteAllRules();
@@ -217,8 +221,9 @@ class TargetAccessControllerTest extends AbstractAccessControllerTest {
final Target permittedTarget = targetManagement final Target permittedTarget = targetManagement
.create(entityFactory.target().create().controllerId("device01").status(TargetUpdateStatus.REGISTERED)); .create(entityFactory.target().create().controllerId("device01").status(TargetUpdateStatus.REGISTERED));
final Target hiddenTarget = targetManagement final String hiddenTargetControllerId = targetManagement
.create(entityFactory.target().create().controllerId("device02").status(TargetUpdateStatus.REGISTERED)); .create(entityFactory.target().create().controllerId("device02").status(TargetUpdateStatus.REGISTERED))
.getControllerId();
// define access controlling rule // define access controlling rule
defineAccess(AccessController.Operation.READ, permittedTarget); defineAccess(AccessController.Operation.READ, permittedTarget);
@@ -232,11 +237,9 @@ class TargetAccessControllerTest extends AbstractAccessControllerTest {
TargetSpecifications.hasId(permittedTarget.getId()), TargetSpecifications.hasId(permittedTarget.getId()),
target -> target.getId().equals(permittedTarget.getId())); target -> target.getId().equals(permittedTarget.getId()));
assertThat(assignDistributionSet(ds.getId(), permittedTarget.getControllerId()).getAssigned()).isEqualTo(1); assertThat(assignDistributionSet(dsId, permittedTarget.getControllerId()).getAssigned()).isEqualTo(1);
// assigning of non allowed target behaves as not found // assigning of non allowed target behaves as not found
assertThatThrownBy( assertThatThrownBy(() -> assignDistributionSet(dsId, hiddenTargetControllerId)).isInstanceOf(AssertionError.class);
() -> assignDistributionSet(ds.getId(), hiddenTarget.getControllerId())
).isInstanceOf(AssertionError.class);
// verify targetManagement#findByUpdateStatus(REGISTERED) after assignment // verify targetManagement#findByUpdateStatus(REGISTERED) after assignment
assertThat(targetManagement.findByUpdateStatus(Pageable.unpaged(), TargetUpdateStatus.REGISTERED) assertThat(targetManagement.findByUpdateStatus(Pageable.unpaged(), TargetUpdateStatus.REGISTERED)
@@ -253,8 +256,9 @@ class TargetAccessControllerTest extends AbstractAccessControllerTest {
permitAllOperations(AccessController.Operation.READ); permitAllOperations(AccessController.Operation.READ);
permitAllOperations(AccessController.Operation.CREATE); permitAllOperations(AccessController.Operation.CREATE);
permitAllOperations(AccessController.Operation.UPDATE); permitAllOperations(AccessController.Operation.UPDATE);
final DistributionSet firstDs = testdataFactory.createDistributionSet("myDs");
distributionSetManagement.lock(firstDs.getId()); final Long firstDsId = testdataFactory.createDistributionSet("myDs").getId();
distributionSetManagement.lock(firstDsId);
final DistributionSet secondDs = testdataFactory.createDistributionSet("anotherDs"); final DistributionSet secondDs = testdataFactory.createDistributionSet("anotherDs");
distributionSetManagement.lock(secondDs.getId()); distributionSetManagement.lock(secondDs.getId());
// entities created - reset rules // entities created - reset rules
@@ -275,18 +279,17 @@ class TargetAccessControllerTest extends AbstractAccessControllerTest {
defineAccess(AccessController.Operation.UPDATE, manageableTarget); defineAccess(AccessController.Operation.UPDATE, manageableTarget);
// assignment is permitted for manageableTarget // assignment is permitted for manageableTarget
assertThat(assignDistributionSet(firstDs.getId(), manageableTarget.getControllerId()).getAssigned()) assertThat(assignDistributionSet(firstDsId, manageableTarget.getControllerId()).getAssigned())
.isEqualTo(1); .isEqualTo(1);
// assignment is denied for readOnlyTarget (read, but no update permissions) // assignment is denied for readOnlyTarget (read, but no update permissions)
assertThatThrownBy( final var readOnlyTargetControllerId = readOnlyTarget.getControllerId();
() -> assignDistributionSet(firstDs.getId(), readOnlyTarget.getControllerId()) assertThatThrownBy(() -> assignDistributionSet(firstDsId, readOnlyTargetControllerId)).isInstanceOf(AssertionError.class);
).isInstanceOf(AssertionError.class);
// bunch assignment skips denied denied since at least one target without update // bunch assignment skips denied denied since at least one target without update
// permissions is present // permissions is present
assertThat(assignDistributionSet(secondDs.getId(), assertThat(assignDistributionSet(secondDs.getId(),
Arrays.asList(readOnlyTarget.getControllerId(), manageableTarget.getControllerId()), Arrays.asList(readOnlyTargetControllerId, manageableTarget.getControllerId()),
Action.ActionType.FORCED).getAssigned()).isEqualTo(1); Action.ActionType.FORCED).getAssigned()).isEqualTo(1);
} }

View File

@@ -19,6 +19,8 @@ import io.qameta.allure.Description;
import io.qameta.allure.Feature; import io.qameta.allure.Feature;
import io.qameta.allure.Story; import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.Identifiable; import org.eclipse.hawkbit.repository.Identifiable;
import org.eclipse.hawkbit.repository.builder.TargetTypeCreate;
import org.eclipse.hawkbit.repository.builder.TargetTypeUpdate;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.InsufficientPermissionException; import org.eclipse.hawkbit.repository.exception.InsufficientPermissionException;
import org.eclipse.hawkbit.repository.jpa.acm.AccessController; import org.eclipse.hawkbit.repository.jpa.acm.AccessController;
@@ -74,24 +76,26 @@ class TargetTypeAccessControllerTest extends AbstractAccessControllerTest {
// verify targetTypeManagement#get by id // verify targetTypeManagement#get by id
assertThat(targetTypeManagement.get(permittedTargetType.getId())).isPresent(); assertThat(targetTypeManagement.get(permittedTargetType.getId())).isPresent();
assertThat(targetTypeManagement.get(hiddenTargetType.getId())).isEmpty(); final Long hiddenTargetTypeId = hiddenTargetType.getId();
assertThat(targetTypeManagement.get(hiddenTargetTypeId)).isEmpty();
// verify targetTypeManagement#getByName // verify targetTypeManagement#getByName
assertThat(targetTypeManagement.getByName(permittedTargetType.getName())).isPresent(); assertThat(targetTypeManagement.getByName(permittedTargetType.getName())).isPresent();
assertThat(targetTypeManagement.getByName(hiddenTargetType.getName())).isEmpty(); assertThat(targetTypeManagement.getByName(hiddenTargetType.getName())).isEmpty();
// verify targetTypeManagement#get by ids // verify targetTypeManagement#get by ids
assertThat(targetTypeManagement.get(Arrays.asList(permittedTargetType.getId(), hiddenTargetType.getId())) assertThat(targetTypeManagement.get(Arrays.asList(permittedTargetType.getId(), hiddenTargetTypeId))
.stream().map(Identifiable::getId).toList()).containsOnly(permittedTargetType.getId()); .stream().map(Identifiable::getId).toList()).containsOnly(permittedTargetType.getId());
// verify targetTypeManagement#update is not possible. Assert exception thrown. // verify targetTypeManagement#update is not possible. Assert exception thrown.
assertThatThrownBy(() -> targetTypeManagement.update(entityFactory.targetType().update(hiddenTargetType.getId()) final TargetTypeUpdate targetTypeUpdate = entityFactory.targetType().update(hiddenTargetTypeId)
.name(hiddenTargetType.getName() + "/new").description("newDesc"))) .name(hiddenTargetType.getName() + "/new").description("newDesc");
assertThatThrownBy(() -> targetTypeManagement.update(targetTypeUpdate))
.as("Target type update shouldn't be allowed since the target type is not visible.") .as("Target type update shouldn't be allowed since the target type is not visible.")
.isInstanceOf(EntityNotFoundException.class); .isInstanceOf(EntityNotFoundException.class);
// verify targetTypeManagement#delete is not possible. Assert exception thrown. // verify targetTypeManagement#delete is not possible. Assert exception thrown.
assertThatThrownBy(() -> targetTypeManagement.delete(hiddenTargetType.getId())) assertThatThrownBy(() -> targetTypeManagement.delete(hiddenTargetTypeId))
.as("Target type delete shouldn't be allowed since the target type is not visible.") .as("Target type delete shouldn't be allowed since the target type is not visible.")
.isInstanceOf(EntityNotFoundException.class); .isInstanceOf(EntityNotFoundException.class);
} }
@@ -100,11 +104,9 @@ class TargetTypeAccessControllerTest extends AbstractAccessControllerTest {
@Description("Verifies delete access rules for target types") @Description("Verifies delete access rules for target types")
void verifyTargetTypeDeleteOperations() { void verifyTargetTypeDeleteOperations() {
permitAllOperations(AccessController.Operation.CREATE); permitAllOperations(AccessController.Operation.CREATE);
final TargetType manageableTargetType = targetTypeManagement final TargetType manageableTargetType = targetTypeManagement.create(entityFactory.targetType().create().name("type1"));
.create(entityFactory.targetType().create().name("type1"));
final TargetType readOnlyTargetType = targetTypeManagement final TargetType readOnlyTargetType = targetTypeManagement.create(entityFactory.targetType().create().name("type2"));
.create(entityFactory.targetType().create().name("type2"));
// define access controlling rule to allow reading both types // define access controlling rule to allow reading both types
defineAccess(AccessController.Operation.READ, manageableTargetType, readOnlyTargetType); defineAccess(AccessController.Operation.READ, manageableTargetType, readOnlyTargetType);
@@ -116,7 +118,8 @@ class TargetTypeAccessControllerTest extends AbstractAccessControllerTest {
targetTypeManagement.delete(manageableTargetType.getId()); targetTypeManagement.delete(manageableTargetType.getId());
// verify targetTypeManagement#delete for readOnlyTargetType is not possible // verify targetTypeManagement#delete for readOnlyTargetType is not possible
assertThatThrownBy(() -> targetTypeManagement.delete(readOnlyTargetType.getId())) final Long readOnlyTargetTypeId = readOnlyTargetType.getId();
assertThatThrownBy(() -> targetTypeManagement.delete(readOnlyTargetTypeId))
.isInstanceOfAny(InsufficientPermissionException.class, EntityNotFoundException.class); .isInstanceOfAny(InsufficientPermissionException.class, EntityNotFoundException.class);
} }
@@ -141,9 +144,9 @@ class TargetTypeAccessControllerTest extends AbstractAccessControllerTest {
.name(manageableTargetType.getName() + "/new").description("newDesc")); .name(manageableTargetType.getName() + "/new").description("newDesc"));
// verify targetTypeManagement#update for readOnlyTargetType is not possible // verify targetTypeManagement#update for readOnlyTargetType is not possible
assertThatThrownBy(() -> final TargetTypeUpdate targetTypeUpdate = entityFactory.targetType().update(readOnlyTargetType.getId())
targetTypeManagement.update(entityFactory.targetType().update(readOnlyTargetType.getId()) .name(readOnlyTargetType.getName() + "/new").description("newDesc");
.name(readOnlyTargetType.getName() + "/new").description("newDesc"))) assertThatThrownBy(() -> targetTypeManagement.update(targetTypeUpdate))
.isInstanceOf(InsufficientPermissionException.class); .isInstanceOf(InsufficientPermissionException.class);
} }
@@ -152,7 +155,8 @@ class TargetTypeAccessControllerTest extends AbstractAccessControllerTest {
void verifyTargetTypeCreationBlockedByAccessController() { void verifyTargetTypeCreationBlockedByAccessController() {
defineAccess(AccessController.Operation.CREATE); // allows for none defineAccess(AccessController.Operation.CREATE); // allows for none
// verify targetTypeManagement#create for any type // verify targetTypeManagement#create for any type
assertThatThrownBy(() -> targetTypeManagement.create(entityFactory.targetType().create().name("type1"))) final TargetTypeCreate targetTypeCreate = entityFactory.targetType().create().name("type1");
assertThatThrownBy(() -> targetTypeManagement.create(targetTypeCreate))
.as("Target type create shouldn't be allowed since the target type is not visible.") .as("Target type create shouldn't be allowed since the target type is not visible.")
.isInstanceOf(InsufficientPermissionException.class); .isInstanceOf(InsufficientPermissionException.class);
} }

View File

@@ -88,7 +88,7 @@ class SoftwareModuleTypeManagementTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Create Software Module Types call fails when called for existing entities.") @Description("Create Software Module Types call fails when called for existing entities.")
void _for() { void createModuleTypesCallFailsForExistingTypes() {
final List<SoftwareModuleTypeCreate> created = Arrays.asList( final List<SoftwareModuleTypeCreate> created = Arrays.asList(
entityFactory.softwareModuleType().create().key("test-key").name("test-name"), entityFactory.softwareModuleType().create().key("test-key").name("test-name"),
entityFactory.softwareModuleType().create().key("test-key2").name("test-name2")); entityFactory.softwareModuleType().create().key("test-key2").name("test-name2"));

View File

@@ -31,6 +31,8 @@ import org.assertj.core.api.Assertions;
import org.eclipse.hawkbit.exception.AbstractServerRtException; import org.eclipse.hawkbit.exception.AbstractServerRtException;
import org.eclipse.hawkbit.repository.TargetFilterQueryManagement; import org.eclipse.hawkbit.repository.TargetFilterQueryManagement;
import org.eclipse.hawkbit.repository.builder.AutoAssignDistributionSetUpdate; import org.eclipse.hawkbit.repository.builder.AutoAssignDistributionSetUpdate;
import org.eclipse.hawkbit.repository.builder.TargetFilterQueryCreate;
import org.eclipse.hawkbit.repository.builder.TargetFilterQueryUpdate;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetCreatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleCreatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetCreatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.TargetCreatedEvent;
@@ -64,8 +66,7 @@ import org.springframework.data.domain.Slice;
class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest { class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Verifies that management get access reacts as specfied on calls for non existing entities by means " @Description("Verifies that management get access reacts as specfied on calls for non existing entities by means of Optional not present.")
+ "of Optional not present.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) }) @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
void nonExistingEntityAccessReturnsNotPresent() { void nonExistingEntityAccessReturnsNotPresent() {
assertThat(targetFilterQueryManagement.get(NOT_EXIST_IDL)).isNotPresent(); assertThat(targetFilterQueryManagement.get(NOT_EXIST_IDL)).isNotPresent();
@@ -73,8 +74,7 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
} }
@Test @Test
@Description("Verifies that management queries react as specfied on calls for non existing entities " @Description("Verifies that management queries react as specfied on calls for non existing entities by means of throwing EntityNotFoundException.")
+ " by means of throwing EntityNotFoundException.")
@ExpectEvents({ @ExpectEvents({
@Expect(type = DistributionSetCreatedEvent.class, count = 1), @Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3), @Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@@ -128,9 +128,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
final DistributionSet set = testdataFactory.createDistributionSet(); final DistributionSet set = testdataFactory.createDistributionSet();
// creation is supposed to work as there is no distribution set // creation is supposed to work as there is no distribution set
final TargetFilterQueryCreate targetFilterQueryCreate = entityFactory.targetFilterQuery().create()
.name("testfilter").autoAssignDistributionSet(set.getId()).query("name==target*");
assertThatExceptionOfType(AssignmentQuotaExceededException.class) assertThatExceptionOfType(AssignmentQuotaExceededException.class)
.isThrownBy(() -> targetFilterQueryManagement.create(entityFactory.targetFilterQuery().create() .isThrownBy(() -> targetFilterQueryManagement.create(targetFilterQueryCreate));
.name("testfilter").autoAssignDistributionSet(set.getId()).query("name==target*")));
} }
@Test @Test
@@ -152,45 +153,46 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Test searching a target filter query with an invalid filter.") @Description("Test searching a target filter query with an invalid filter.")
void searchTargetFilterQueryInvalidField() { void searchTargetFilterQueryInvalidField() {
final PageRequest pageRequest = PageRequest.of(0, 10);
Assertions.assertThatExceptionOfType(RSQLParameterUnsupportedFieldException.class) Assertions.assertThatExceptionOfType(RSQLParameterUnsupportedFieldException.class)
.isThrownBy(() -> targetFilterQueryManagement .isThrownBy(() -> targetFilterQueryManagement.findByRsql(pageRequest, "unknownField==testValue"));
.findByRsql(PageRequest.of(0, 10), "unknownField==testValue").getContent());
} }
@Test @Test
@Description("Checks if the EntityAlreadyExistsException is thrown if a targetfilterquery with the same name are created more than once.") @Description("Checks if the EntityAlreadyExistsException is thrown if a targetFilterQuery with the same name are created more than once.")
void createDuplicateTargetFilterQuery() { void createDuplicateTargetFilterQuery() {
final String filterName = "new target filter duplicate"; final String filterName = "new target filter duplicate";
targetFilterQueryManagement final TargetFilterQueryCreate targetFilterQueryCreate = entityFactory.targetFilterQuery().create()
.create(entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001")); .name(filterName).query("name==PendingTargets001");
targetFilterQueryManagement.create(targetFilterQueryCreate);
assertThatExceptionOfType(EntityAlreadyExistsException.class) assertThatExceptionOfType(EntityAlreadyExistsException.class)
.as("should not have worked as query already exists") .as("should not have worked as query already exists")
.isThrownBy(() -> targetFilterQueryManagement.create( .isThrownBy(() -> targetFilterQueryManagement.create(targetFilterQueryCreate));
entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001")));
} }
@Test @Test
@Description("Test deletion of target filter query.") @Description("Test deletion of target filter query.")
void deleteTargetFilterQuery() { void deleteTargetFilterQuery() {
final String filterName = "delete_target_filter_query"; final String filterName = "delete_target_filter_query";
final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement.create(entityFactory.targetFilterQuery()
.create(entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001")); .create().name(filterName).query("name==PendingTargets001"));
targetFilterQueryManagement.delete(targetFilterQuery.getId()); targetFilterQueryManagement.delete(targetFilterQuery.getId());
assertFalse(targetFilterQueryManagement.get(targetFilterQuery.getId()).isPresent(), assertFalse(
targetFilterQueryManagement.get(targetFilterQuery.getId()).isPresent(),
"Returns null as the target filter is deleted"); "Returns null as the target filter is deleted");
} }
@Test @Test
@Description("Test updation of target filter query.") @Description("Test update of a target filter query.")
void updateTargetFilterQuery() { void updateTargetFilterQuery() {
final String filterName = "target_filter_01"; final String filterName = "target_filter_01";
final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement
.create(entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001")); .create(entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001"));
final String newQuery = "status==UNKNOWN"; final String newQuery = "status==UNKNOWN";
targetFilterQueryManagement targetFilterQueryManagement.update(entityFactory.targetFilterQuery().update(targetFilterQuery.getId()).query(newQuery));
.update(entityFactory.targetFilterQuery().update(targetFilterQuery.getId()).query(newQuery));
assertEquals(newQuery, targetFilterQueryManagement.getByName(filterName).get().getQuery(), assertEquals(newQuery, targetFilterQueryManagement.getByName(filterName).get().getQuery(),
"Returns updated target filter query"); "Returns updated target filter query");
} }
@@ -204,22 +206,16 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
final DistributionSet distributionSet = testdataFactory.createDistributionSet(); final DistributionSet distributionSet = testdataFactory.createDistributionSet();
verifyAutoAssignmentWithDefaultActionType(filterName, targetFilterQuery, distributionSet); verifyAutoAssignmentWithDefaultActionType(filterName, targetFilterQuery, distributionSet);
verifyAutoAssignmentWithSoftActionType(filterName, targetFilterQuery, distributionSet); verifyAutoAssignmentWithSoftActionType(filterName, targetFilterQuery, distributionSet);
verifyAutoAssignmentWithDownloadOnlyActionType(filterName, targetFilterQuery, distributionSet); verifyAutoAssignmentWithDownloadOnlyActionType(filterName, targetFilterQuery, distributionSet);
verifyAutoAssignmentWithInvalidActionType(targetFilterQuery, distributionSet); verifyAutoAssignmentWithInvalidActionType(targetFilterQuery, distributionSet);
verifyAutoAssignmentWithIncompleteDs(targetFilterQuery); verifyAutoAssignmentWithIncompleteDs(targetFilterQuery);
verifyAutoAssignmentWithSoftDeletedDs(targetFilterQuery); verifyAutoAssignmentWithSoftDeletedDs(targetFilterQuery);
} }
@Test @Test
@Description("Assigns a distribution set to an existing filter query and verifies that the quota 'max targets per auto assignment' is enforced.") @Description("Assigns a distribution set to an existing filter query and verifies that the quota 'max targets per auto assignment' is enforced.")
void assignDistributionSetToTargetFilterQueryThatExceedsQuota() { void assignDistributionSetToTargetFilterQueryThatExceedsQuota() {
// create targets // create targets
final int maxTargets = quotaManagement.getMaxTargetsPerAutoAssignment(); final int maxTargets = quotaManagement.getMaxTargetsPerAutoAssignment();
testdataFactory.createTargets(maxTargets + 1, "target%s"); testdataFactory.createTargets(maxTargets + 1, "target%s");
@@ -231,10 +227,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
// assigning a distribution set is supposed to fail as the query // assigning a distribution set is supposed to fail as the query
// addresses too many targets // addresses too many targets
final AutoAssignDistributionSetUpdate autoAssignDistributionSetUpdate = entityFactory.targetFilterQuery()
.updateAutoAssign(targetFilterQuery.getId()).ds(distributionSet.getId());
assertThatExceptionOfType(AssignmentQuotaExceededException.class) assertThatExceptionOfType(AssignmentQuotaExceededException.class)
.isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(entityFactory.targetFilterQuery() .isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(autoAssignDistributionSetUpdate));
.updateAutoAssign(targetFilterQuery.getId()).ds(distributionSet.getId())));
} }
@Test @Test
@@ -250,8 +246,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
.create().name("testfilter").autoAssignDistributionSet(set.getId()).query("name==foo")); .create().name("testfilter").autoAssignDistributionSet(set.getId()).query("name==foo"));
// update with a query string that addresses too many targets // update with a query string that addresses too many targets
assertThatExceptionOfType(AssignmentQuotaExceededException.class).isThrownBy(() -> targetFilterQueryManagement final TargetFilterQueryUpdate targetFilterQueryUpdate = entityFactory.targetFilterQuery().update(targetFilterQuery.getId())
.update(entityFactory.targetFilterQuery().update(targetFilterQuery.getId()).query("name==target*"))); .query("name==target*");
assertThatExceptionOfType(AssignmentQuotaExceededException.class)
.isThrownBy(() -> targetFilterQueryManagement.update(targetFilterQueryUpdate));
} }
@Test @Test
@@ -288,8 +286,7 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
final DistributionSet distributionSet = testdataFactory.createDistributionSet("dist_set"); final DistributionSet distributionSet = testdataFactory.createDistributionSet("dist_set");
final Target target = testdataFactory.createTarget(); final Target target = testdataFactory.createTarget();
// Assign the distribution set to an target, to force a soft delete in a // Assign the distribution set to an target, to force a soft delete in a later step
// later step
assignDistributionSet(distributionSet.getId(), target.getControllerId()); assignDistributionSet(distributionSet.getId(), target.getControllerId());
final Long filterId = targetFilterQueryManagement final Long filterId = targetFilterQueryManagement
@@ -307,8 +304,7 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
distributionSetManagement.delete(distributionSet.getId()); distributionSetManagement.delete(distributionSet.getId());
// Check if distribution set is still in the database with deleted flag // Check if distribution set is still in the database with deleted flag
assertTrue(distributionSetManagement.get(distributionSet.getId()).get().isDeleted(), assertTrue(distributionSetManagement.get(distributionSet.getId()).get().isDeleted(), "Distribution set should be deleted");
"Distribution set should be deleted");
// Check if auto assign distribution set is null // Check if auto assign distribution set is null
tfq = targetFilterQueryManagement.getByName(filterName).get(); tfq = targetFilterQueryManagement.getByName(filterName).get();
@@ -327,10 +323,11 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
final DistributionSet distributionSet = testdataFactory.createDistributionSet(); final DistributionSet distributionSet = testdataFactory.createDistributionSet();
final DistributionSet distributionSet2 = testdataFactory.createDistributionSet("2"); final DistributionSet distributionSet2 = testdataFactory.createDistributionSet("2");
final TargetFilterQuery tfq = targetFilterQueryManagement final TargetFilterQuery tfq = targetFilterQueryManagement.create(
.create(entityFactory.targetFilterQuery().create().name("c").query("name==x") entityFactory.targetFilterQuery().create()
.autoAssignDistributionSet(distributionSet).autoAssignActionType(ActionType.SOFT)); .name("c").query("name==x").autoAssignDistributionSet(distributionSet).autoAssignActionType(ActionType.SOFT));
final TargetFilterQuery tfq2 = targetFilterQueryManagement.create(entityFactory.targetFilterQuery().create() final TargetFilterQuery tfq2 = targetFilterQueryManagement.create(
entityFactory.targetFilterQuery().create()
.name(filterName).query("name==z*").autoAssignDistributionSet(distributionSet2)); .name(filterName).query("name==z*").autoAssignDistributionSet(distributionSet2));
assertEquals(4L, targetFilterQueryManagement.count()); assertEquals(4L, targetFilterQueryManagement.count());
@@ -342,10 +339,8 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
// check if find works for two // check if find works for two
verifyFindByDistributionSetAndRsql(distributionSet, null, tfq, tfq2); verifyFindByDistributionSetAndRsql(distributionSet, null, tfq, tfq2);
// check if find works with name filter // check if find works with name filter
verifyFindByDistributionSetAndRsql(distributionSet, "name==" + filterName, tfq2); verifyFindByDistributionSetAndRsql(distributionSet, "name==" + filterName, tfq2);
verifyFindForAllWithAutoAssignDs(tfq, tfq2); verifyFindForAllWithAutoAssignDs(tfq, tfq2);
} }
@@ -354,8 +349,7 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
void weightNotRequiredInMultiAssignmentMode() { void weightNotRequiredInMultiAssignmentMode() {
enableMultiAssignments(); enableMultiAssignments();
final DistributionSet ds = testdataFactory.createDistributionSet(); final DistributionSet ds = testdataFactory.createDistributionSet();
final Long filterId = targetFilterQueryManagement final Long filterId = targetFilterQueryManagement.create(entityFactory.targetFilterQuery().create().name("a").query("name==*")).getId();
.create(entityFactory.targetFilterQuery().create().name("a").query("name==*")).getId();
assertThat( assertThat(
targetFilterQueryManagement.create( targetFilterQueryManagement.create(
@@ -371,8 +365,7 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
@Description("Creating or updating a target filter query with autoassignment with a weight causes an error when multi assignment in disabled.") @Description("Creating or updating a target filter query with autoassignment with a weight causes an error when multi assignment in disabled.")
void weightAllowedWhenMultiAssignmentModeNotEnabled() { void weightAllowedWhenMultiAssignmentModeNotEnabled() {
final DistributionSet ds = testdataFactory.createDistributionSet(); final DistributionSet ds = testdataFactory.createDistributionSet();
final Long filterId = targetFilterQueryManagement final Long filterId = targetFilterQueryManagement.create(entityFactory.targetFilterQuery().create().name("a").query("name==*")).getId();
.create(entityFactory.targetFilterQuery().create().name("a").query("name==*")).getId();
assertThat( assertThat(
targetFilterQueryManagement.create( targetFilterQueryManagement.create(
@@ -390,12 +383,11 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
void removeDsFromFilterWhenMultiAssignmentModeNotEnabled() { void removeDsFromFilterWhenMultiAssignmentModeNotEnabled() {
enableMultiAssignments(); enableMultiAssignments();
final DistributionSet ds = testdataFactory.createDistributionSet(); final DistributionSet ds = testdataFactory.createDistributionSet();
final Long filterId = targetFilterQueryManagement final Long filterId = targetFilterQueryManagement.create(
.create(entityFactory.targetFilterQuery().create().name("a") entityFactory.targetFilterQuery().create().name("a")
.query("name==*").autoAssignDistributionSet(ds).autoAssignWeight(23)).getId(); .query("name==*").autoAssignDistributionSet(ds).autoAssignWeight(23)).getId();
assertThat( assertThat(targetFilterQueryManagement.updateAutoAssignDS(
targetFilterQueryManagement entityFactory.targetFilterQuery().updateAutoAssign(filterId).ds(null).weight(null)))
.updateAutoAssignDS(entityFactory.targetFilterQuery().updateAutoAssign(filterId).ds(null).weight(null)))
.isNotNull(); .isNotNull();
} }
@@ -405,20 +397,23 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
enableMultiAssignments(); enableMultiAssignments();
final DistributionSet ds = testdataFactory.createDistributionSet(); final DistributionSet ds = testdataFactory.createDistributionSet();
final TargetFilterQueryCreate targetFilterQueryCreate = entityFactory.targetFilterQuery().create().name("a")
.query("name==*").autoAssignDistributionSet(ds).autoAssignWeight(Action.WEIGHT_MAX + 1);
Assertions.assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy( Assertions.assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(
() -> targetFilterQueryManagement.create(entityFactory.targetFilterQuery().create().name("a") () -> targetFilterQueryManagement.create(targetFilterQueryCreate));
.query("name==*").autoAssignDistributionSet(ds).autoAssignWeight(Action.WEIGHT_MAX + 1)));
final Long filterId = targetFilterQueryManagement.create(entityFactory.targetFilterQuery().create().name("a") final Long filterId = targetFilterQueryManagement.create(entityFactory.targetFilterQuery().create().name("a")
.query("name==*").autoAssignDistributionSet(ds).autoAssignWeight(Action.WEIGHT_MAX)).getId(); .query("name==*").autoAssignDistributionSet(ds).autoAssignWeight(Action.WEIGHT_MAX)).getId();
assertThat(targetFilterQueryManagement.get(filterId).get().getAutoAssignWeight()).contains(Action.WEIGHT_MAX); assertThat(targetFilterQueryManagement.get(filterId).get().getAutoAssignWeight()).contains(Action.WEIGHT_MAX);
final AutoAssignDistributionSetUpdate autoAssignDistributionSetUpdate = entityFactory.targetFilterQuery().updateAutoAssign(filterId)
.ds(ds.getId()).weight(Action.WEIGHT_MAX + 1);
Assertions.assertThatExceptionOfType(ConstraintViolationException.class) Assertions.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(entityFactory.targetFilterQuery() .isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(autoAssignDistributionSetUpdate));
.updateAutoAssign(filterId).ds(ds.getId()).weight(Action.WEIGHT_MAX + 1))); final AutoAssignDistributionSetUpdate autoAssignDistributionSetUpdate2 = entityFactory.targetFilterQuery()
.updateAutoAssign(filterId).ds(ds.getId()).weight(Action.WEIGHT_MIN - 1);
Assertions.assertThatExceptionOfType(ConstraintViolationException.class) Assertions.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(entityFactory.targetFilterQuery() .isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(autoAssignDistributionSetUpdate2));
.updateAutoAssign(filterId).ds(ds.getId()).weight(Action.WEIGHT_MIN - 1)));
targetFilterQueryManagement.updateAutoAssignDS( targetFilterQueryManagement.updateAutoAssignDS(
entityFactory.targetFilterQuery().updateAutoAssign(filterId).ds(ds.getId()).weight(Action.WEIGHT_MAX)); entityFactory.targetFilterQuery().updateAutoAssign(filterId).ds(ds.getId()).weight(Action.WEIGHT_MAX));
targetFilterQueryManagement.updateAutoAssignDS( targetFilterQueryManagement.updateAutoAssignDS(
@@ -431,11 +426,11 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
void createTargetFilterWithInvalidDistributionSet() { void createTargetFilterWithInvalidDistributionSet() {
final DistributionSet distributionSet = testdataFactory.createAndInvalidateDistributionSet(); final DistributionSet distributionSet = testdataFactory.createAndInvalidateDistributionSet();
final TargetFilterQueryCreate targetFilterQueryCreate = entityFactory.targetFilterQuery().create()
.name("createTargetFilterWithInvalidDistributionSet").query("name==*").autoAssignDistributionSet(distributionSet);
assertThatExceptionOfType(InvalidDistributionSetException.class) assertThatExceptionOfType(InvalidDistributionSetException.class)
.as("Invalid distributionSet should throw an exception") .as("Invalid distributionSet should throw an exception")
.isThrownBy(() -> targetFilterQueryManagement.create( .isThrownBy(() -> targetFilterQueryManagement.create(targetFilterQueryCreate));
entityFactory.targetFilterQuery().create().name("createTargetFilterWithInvalidDistributionSet")
.query("name==*").autoAssignDistributionSet(distributionSet)));
} }
@Test @Test
@@ -443,11 +438,12 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
void createTargetFilterWithIncompleteDistributionSet() { void createTargetFilterWithIncompleteDistributionSet() {
final DistributionSet distributionSet = testdataFactory.createIncompleteDistributionSet(); final DistributionSet distributionSet = testdataFactory.createIncompleteDistributionSet();
final TargetFilterQueryCreate targetFilterQueryCreate = entityFactory.targetFilterQuery().create()
.name("createTargetFilterWithIncompleteDistributionSet").query("name==*")
.autoAssignDistributionSet(distributionSet);
assertThatExceptionOfType(IncompleteDistributionSetException.class) assertThatExceptionOfType(IncompleteDistributionSetException.class)
.as("Incomplete distributionSet should throw an exception") .as("Incomplete distributionSet should throw an exception")
.isThrownBy(() -> targetFilterQueryManagement.create(entityFactory.targetFilterQuery().create() .isThrownBy(() -> targetFilterQueryManagement.create(targetFilterQueryCreate));
.name("createTargetFilterWithIncompleteDistributionSet").query("name==*")
.autoAssignDistributionSet(distributionSet)));
} }
@Test @Test
@@ -459,11 +455,11 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
.query("name==*").autoAssignDistributionSet(distributionSet)); .query("name==*").autoAssignDistributionSet(distributionSet));
final DistributionSet invalidDistributionSet = testdataFactory.createAndInvalidateDistributionSet(); final DistributionSet invalidDistributionSet = testdataFactory.createAndInvalidateDistributionSet();
final AutoAssignDistributionSetUpdate autoAssignDistributionSetUpdate = new AutoAssignDistributionSetUpdate(targetFilterQuery.getId())
.ds(invalidDistributionSet.getId());
assertThatExceptionOfType(InvalidDistributionSetException.class) assertThatExceptionOfType(InvalidDistributionSetException.class)
.as("Invalid distributionSet should throw an exception") .as("Invalid distributionSet should throw an exception")
.isThrownBy(() -> targetFilterQueryManagement .isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(autoAssignDistributionSetUpdate));
.updateAutoAssignDS(new AutoAssignDistributionSetUpdate(targetFilterQuery.getId())
.ds(invalidDistributionSet.getId())));
} }
@Test @Test
@@ -475,11 +471,11 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
.query("name==*").autoAssignDistributionSet(distributionSet)); .query("name==*").autoAssignDistributionSet(distributionSet));
final DistributionSet incompleteDistributionSet = testdataFactory.createIncompleteDistributionSet(); final DistributionSet incompleteDistributionSet = testdataFactory.createIncompleteDistributionSet();
final AutoAssignDistributionSetUpdate autoAssignDistributionSetUpdate = new AutoAssignDistributionSetUpdate(targetFilterQuery.getId())
.ds(incompleteDistributionSet.getId());
assertThatExceptionOfType(IncompleteDistributionSetException.class) assertThatExceptionOfType(IncompleteDistributionSetException.class)
.as("Incomplete distributionSet should throw an exception") .as("Incomplete distributionSet should throw an exception")
.isThrownBy(() -> targetFilterQueryManagement .isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(autoAssignDistributionSetUpdate));
.updateAutoAssignDS(new AutoAssignDistributionSetUpdate(targetFilterQuery.getId())
.ds(incompleteDistributionSet.getId())));
} }
@Test @Test
@@ -501,13 +497,13 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
} }
} }
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> final JpaTargetFilterQuery jpaTargetFilterQuery = (JpaTargetFilterQuery) targetFilterQueryManagement.create(
((JpaTargetFilterQuery) targetFilterQueryManagement.create(
entityFactory.targetFilterQuery() entityFactory.targetFilterQuery()
.create() .create()
.name("testAutoAssignActionTypeConvert") .name("testAutoAssignActionTypeConvert")
.query("name==*"))) .query("name==*"));
.setAutoAssignActionType(ActionType.TIMEFORCED)); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() ->
jpaTargetFilterQuery.setAutoAssignActionType(ActionType.TIMEFORCED));
} }
@Step @Step
@@ -541,10 +537,12 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
final DistributionSet distributionSet) { final DistributionSet distributionSet) {
// assigning a distribution set with TIMEFORCED action is supposed to // assigning a distribution set with TIMEFORCED action is supposed to
// fail as only FORCED and SOFT action types are allowed // fail as only FORCED and SOFT action types are allowed
final AutoAssignDistributionSetUpdate autoAssignDistributionSetUpdate = entityFactory.targetFilterQuery()
.updateAutoAssign(targetFilterQuery.getId())
.ds(distributionSet.getId())
.actionType(ActionType.TIMEFORCED);
assertThatExceptionOfType(InvalidAutoAssignActionTypeException.class) assertThatExceptionOfType(InvalidAutoAssignActionTypeException.class)
.isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS( .isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(autoAssignDistributionSetUpdate));
entityFactory.targetFilterQuery().updateAutoAssign(targetFilterQuery.getId())
.ds(distributionSet.getId()).actionType(ActionType.TIMEFORCED)));
} }
@Step @Step
@@ -553,9 +551,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
.create(entityFactory.distributionSet().create().name("incomplete").version("1") .create(entityFactory.distributionSet().create().name("incomplete").version("1")
.type(testdataFactory.findOrCreateDefaultTestDsType())); .type(testdataFactory.findOrCreateDefaultTestDsType()));
final AutoAssignDistributionSetUpdate autoAssignDistributionSetUpdate = entityFactory.targetFilterQuery()
.updateAutoAssign(targetFilterQuery.getId()).ds(incompleteDistributionSet.getId());
assertThatExceptionOfType(IncompleteDistributionSetException.class) assertThatExceptionOfType(IncompleteDistributionSetException.class)
.isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(entityFactory.targetFilterQuery() .isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(autoAssignDistributionSetUpdate));
.updateAutoAssign(targetFilterQuery.getId()).ds(incompleteDistributionSet.getId())));
} }
@Step @Step
@@ -564,9 +563,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
assignDistributionSet(softDeletedDs, testdataFactory.createTarget("forSoftDeletedDs")); assignDistributionSet(softDeletedDs, testdataFactory.createTarget("forSoftDeletedDs"));
distributionSetManagement.delete(softDeletedDs.getId()); distributionSetManagement.delete(softDeletedDs.getId());
final AutoAssignDistributionSetUpdate autoAssignDistributionSetUpdate = entityFactory.targetFilterQuery()
.updateAutoAssign(targetFilterQuery.getId()).ds(softDeletedDs.getId());
assertThatExceptionOfType(DeletedException.class) assertThatExceptionOfType(DeletedException.class)
.isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(entityFactory.targetFilterQuery() .isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(autoAssignDistributionSetUpdate));
.updateAutoAssign(targetFilterQuery.getId()).ds(softDeletedDs.getId())));
} }
@Step @Step

View File

@@ -23,7 +23,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Collectors;
import jakarta.validation.ConstraintViolationException; import jakarta.validation.ConstraintViolationException;
@@ -36,6 +35,7 @@ import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.im.authentication.SpRole; import org.eclipse.hawkbit.im.authentication.SpRole;
import org.eclipse.hawkbit.repository.FilterParams; import org.eclipse.hawkbit.repository.FilterParams;
import org.eclipse.hawkbit.repository.Identifiable; import org.eclipse.hawkbit.repository.Identifiable;
import org.eclipse.hawkbit.repository.builder.TargetCreate;
import org.eclipse.hawkbit.repository.builder.TargetUpdate; import org.eclipse.hawkbit.repository.builder.TargetUpdate;
import org.eclipse.hawkbit.repository.event.remote.TargetAssignDistributionSetEvent; import org.eclipse.hawkbit.repository.event.remote.TargetAssignDistributionSetEvent;
import org.eclipse.hawkbit.repository.event.remote.TargetAttributesRequestedEvent; import org.eclipse.hawkbit.repository.event.remote.TargetAttributesRequestedEvent;
@@ -219,10 +219,11 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
@Description("Verify that a target with same controller ID than another device cannot be created.") @Description("Verify that a target with same controller ID than another device cannot be created.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1) }) @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1) })
void createTargetThatViolatesUniqueConstraintFails() { void createTargetThatViolatesUniqueConstraintFails() {
targetManagement.create(entityFactory.target().create().controllerId("123")); final TargetCreate targetCreate = entityFactory.target().create().controllerId("123");
targetManagement.create(targetCreate);
assertThatExceptionOfType(EntityAlreadyExistsException.class) assertThatExceptionOfType(EntityAlreadyExistsException.class)
.isThrownBy(() -> targetManagement.create(entityFactory.target().create().controllerId("123"))); .isThrownBy(() -> targetManagement.create(targetCreate));
} }
@Test @Test
@@ -248,14 +249,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
@Expect(type = TargetUpdatedEvent.class, count = 5) }) @Expect(type = TargetUpdatedEvent.class, count = 5) })
void assignAndUnassignTargetsToTag() { void assignAndUnassignTargetsToTag() {
final List<String> assignTarget = new ArrayList<>(); final List<String> assignTarget = new ArrayList<>();
assignTarget.add( assignTarget.add(targetManagement.create(entityFactory.target().create().controllerId("targetId123")).getControllerId());
targetManagement.create(entityFactory.target().create().controllerId("targetId123")).getControllerId()); assignTarget.add(targetManagement.create(entityFactory.target().create().controllerId("targetId1234")).getControllerId());
assignTarget.add(targetManagement.create(entityFactory.target().create().controllerId("targetId1234")) assignTarget.add(targetManagement.create(entityFactory.target().create().controllerId("targetId1235")).getControllerId());
.getControllerId()); assignTarget.add(targetManagement.create(entityFactory.target().create().controllerId("targetId1236")).getControllerId());
assignTarget.add(targetManagement.create(entityFactory.target().create().controllerId("targetId1235"))
.getControllerId());
assignTarget.add(targetManagement.create(entityFactory.target().create().controllerId("targetId1236"))
.getControllerId());
final TargetTag targetTag = targetTagManagement.create(entityFactory.tag().create().name("Tag1")); final TargetTag targetTag = targetTagManagement.create(entityFactory.tag().create().name("Tag1"));
@@ -385,24 +382,20 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 5) }) @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 5) })
void createMultipleTargetsDuplicate() { void createMultipleTargetsDuplicate() {
testdataFactory.createTargets(5, "mySimpleTargs", "my simple targets"); testdataFactory.createTargets(5, "mySimpleTargs", "my simple targets");
try { assertThatExceptionOfType(EntityAlreadyExistsException.class)
testdataFactory.createTargets(5, "mySimpleTargs", "my simple targets"); .as("Targets already exists")
fail("Targets already exists"); .isThrownBy(() -> testdataFactory.createTargets(5, "mySimpleTargs", "my simple targets"));
} catch (final EntityAlreadyExistsException e) {
}
} }
@Test @Test
@Description("Checks if the EntityAlreadyExistsException is thrown if a single target with the same controller ID are created twice.") @Description("Checks if the EntityAlreadyExistsException is thrown if a single target with the same controller ID are created twice.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1) }) @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1) })
void createTargetDuplicate() { void createTargetDuplicate() {
targetManagement.create(entityFactory.target().create().controllerId("4711")); final TargetCreate targetCreate = entityFactory.target().create().controllerId("4711");
try { targetManagement.create(targetCreate);
targetManagement.create(entityFactory.target().create().controllerId("4711")); assertThatExceptionOfType(EntityAlreadyExistsException.class)
fail("Target already exists"); .as("Target already exists")
} catch (final EntityAlreadyExistsException e) { .isThrownBy(() -> targetManagement.create(targetCreate));
}
} }
@Test @Test
@@ -468,7 +461,7 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
firstList = firstList.stream() firstList = firstList.stream()
.map(t -> targetManagement.update( .map(t -> targetManagement.update(
entityFactory.target().update(t.getControllerId()).name(t.getName().concat("\tchanged")))) entityFactory.target().update(t.getControllerId()).name(t.getName().concat("\tchanged"))))
.collect(Collectors.toList()); .toList();
// verify that all entries are found // verify that all entries are found
_founds: _founds:
@@ -500,7 +493,7 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
final int numberToDelete = 50; final int numberToDelete = 50;
final Collection<Target> targetsToDelete = firstList.subList(0, numberToDelete); final Collection<Target> targetsToDelete = firstList.subList(0, numberToDelete);
final Target[] deletedTargets = toArray(targetsToDelete, Target.class); final Target[] deletedTargets = toArray(targetsToDelete, Target.class);
final List<Long> targetsIdsToDelete = targetsToDelete.stream().map(Target::getId).collect(Collectors.toList()); final List<Long> targetsIdsToDelete = targetsToDelete.stream().map(Target::getId).toList();
targetManagement.delete(targetsIdsToDelete); targetManagement.delete(targetsIdsToDelete);
@@ -720,7 +713,7 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
final String rsqlFilter = "tag==Targ-A-Tag,id==target-id-B-00001,id==target-id-B-00008"; final String rsqlFilter = "tag==Targ-A-Tag,id==target-id-B-00001,id==target-id-B-00008";
final TargetTag targTagA = targetTagManagement.create(entityFactory.tag().create().name("Targ-A-Tag")); final TargetTag targTagA = targetTagManagement.create(entityFactory.tag().create().name("Targ-A-Tag"));
final List<String> targAs = testdataFactory.createTargets(25, "target-id-A", "first description").stream() final List<String> targAs = testdataFactory.createTargets(25, "target-id-A", "first description").stream()
.map(Target::getControllerId).collect(Collectors.toList()); .map(Target::getControllerId).toList();
targetManagement.assignTag(targAs, targTagA.getId()); targetManagement.assignTag(targAs, targTagA.getId());
testdataFactory.createTargets(25, "target-id-B", "first description"); testdataFactory.createTargets(25, "target-id-B", "first description");
@@ -747,7 +740,7 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
assertThat(foundDs).hasSize(3); assertThat(foundDs).hasSize(3);
final List<Long> collect = foundDs.stream().map(Target::getId).collect(Collectors.toList()); final List<Long> collect = foundDs.stream().map(Target::getId).toList();
assertThat(collect).containsAll(searchIds); assertThat(collect).containsAll(searchIds);
} }
@@ -806,8 +799,9 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
metaData2.add(new JpaTargetMetadata("k" + i, "v" + i, target2)); metaData2.add(new JpaTargetMetadata("k" + i, "v" + i, target2));
} }
// verify quota is exceeded // verify quota is exceeded
final String target2ControllerId = target2.getControllerId();
assertThatExceptionOfType(AssignmentQuotaExceededException.class) assertThatExceptionOfType(AssignmentQuotaExceededException.class)
.isThrownBy(() -> targetManagement.createMetaData(target2.getControllerId(), metaData2)); .isThrownBy(() -> targetManagement.createMetaData(target2ControllerId, metaData2));
// add some meta data entries // add some meta data entries
final Target target3 = testdataFactory.createTarget("target3"); final Target target3 = testdataFactory.createTarget("target3");
@@ -822,8 +816,9 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
metaData3.add(new JpaTargetMetadata("kk" + i, "vv" + i, target3)); metaData3.add(new JpaTargetMetadata("kk" + i, "vv" + i, target3));
} }
// verify quota is exceeded // verify quota is exceeded
final String target3ControllerId = target3.getControllerId();
assertThatExceptionOfType(AssignmentQuotaExceededException.class) assertThatExceptionOfType(AssignmentQuotaExceededException.class)
.isThrownBy(() -> targetManagement.createMetaData(target3.getControllerId(), metaData3)); .isThrownBy(() -> targetManagement.createMetaData(target3ControllerId, metaData3));
} }
@@ -1001,12 +996,14 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetFound.get().getTargetType()).isNull(); assertThat(targetFound.get().getTargetType()).isNull();
// assign target type to target // assign target type to target
assertThatExceptionOfType(ConstraintViolationException.class).as("target type with id=null cannot be assigned") final String controllerId = targetFound.get().getControllerId();
.isThrownBy(() -> targetManagement.assignType(targetFound.get().getControllerId(), null)); assertThatExceptionOfType(ConstraintViolationException.class)
.as("target type with id=null cannot be assigned")
.isThrownBy(() -> targetManagement.assignType(controllerId, null));
assertThatExceptionOfType(EntityNotFoundException.class) assertThatExceptionOfType(EntityNotFoundException.class)
.as("target type with id that does not exists cannot be assigned") .as("target type with id that does not exists cannot be assigned")
.isThrownBy(() -> targetManagement.assignType(targetFound.get().getControllerId(), 114L)); .isThrownBy(() -> targetManagement.assignType(controllerId, 114L));
// opt lock revision is not changed // opt lock revision is not changed
final Optional<JpaTarget> targetFound1 = targetRepository.findById(target.getId()); final Optional<JpaTarget> targetFound1 = targetRepository.findById(target.getId());
@@ -1221,131 +1218,151 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
@Step @Step
private void createAndUpdateTargetWithInvalidDescription(final Target target) { private void createAndUpdateTargetWithInvalidDescription(final Target target) {
final TargetCreate targetCreateTooLong = entityFactory.target().create().controllerId("a")
.description(randomString(513));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("target with too long description should not be created") .as("target with too long description should not be created")
.isThrownBy(() -> targetManagement.create(entityFactory.target().create().controllerId("a") .isThrownBy(() -> targetManagement.create(targetCreateTooLong));
.description(randomString(513))));
final TargetCreate targetCreateInvalidHtml = entityFactory.target().create().controllerId("a").description(INVALID_TEXT_HTML);
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("target with invalid description should not be created").isThrownBy(() -> targetManagement .as("target with invalid description should not be created")
.create(entityFactory.target().create().controllerId("a").description(INVALID_TEXT_HTML))); .isThrownBy(() -> targetManagement.create(targetCreateInvalidHtml));
final TargetUpdate targetUpdateTooLong = entityFactory.target().update(target.getControllerId())
.description(randomString(513));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("target with too long description should not be updated") .as("target with too long description should not be updated")
.isThrownBy(() -> targetManagement.update(entityFactory.target().update(target.getControllerId()) .isThrownBy(() -> targetManagement.update(targetUpdateTooLong));
.description(randomString(513))));
final TargetUpdate targetUpdateInvalidHtml = entityFactory.target().update(target.getControllerId()).description(INVALID_TEXT_HTML);
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("target with invalid description should not be updated").isThrownBy(() -> targetManagement.update( .as("target with invalid description should not be updated")
entityFactory.target().update(target.getControllerId()).description(INVALID_TEXT_HTML))); .isThrownBy(() -> targetManagement.update(targetUpdateInvalidHtml));
} }
@Step @Step
private void createAndUpdateTargetWithInvalidName(final Target target) { private void createAndUpdateTargetWithInvalidName(final Target target) {
final TargetCreate targetCreateTooLong = entityFactory.target().create().controllerId("a")
.name(randomString(NamedEntity.NAME_MAX_SIZE + 1));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("target with too long name should not be created") .as("target with too long name should not be created")
.isThrownBy(() -> targetManagement.create(entityFactory.target().create().controllerId("a") .isThrownBy(() -> targetManagement.create(targetCreateTooLong));
.name(randomString(NamedEntity.NAME_MAX_SIZE + 1))));
final TargetCreate targetCreateInvalidHtml = entityFactory.target().create().controllerId("a").name(INVALID_TEXT_HTML);
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("target with invalid name should not be created").isThrownBy(() -> targetManagement .as("target with invalid name should not be created")
.create(entityFactory.target().create().controllerId("a").name(INVALID_TEXT_HTML))); .isThrownBy(() -> targetManagement.create(targetCreateInvalidHtml));
final TargetUpdate targetUpdateTooLong = entityFactory.target().update(target.getControllerId())
.name(randomString(NamedEntity.NAME_MAX_SIZE + 1));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("target with too long name should not be updated") .as("target with too long name should not be updated")
.isThrownBy(() -> targetManagement.update(entityFactory.target().update(target.getControllerId()) .isThrownBy(() -> targetManagement.update(targetUpdateTooLong));
.name(randomString(NamedEntity.NAME_MAX_SIZE + 1))));
final TargetUpdate targetUpdateInvalidHtml = entityFactory.target().update(target.getControllerId()).name(INVALID_TEXT_HTML);
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("target with invalid name should not be updated").isThrownBy(() -> targetManagement .as("target with invalid name should not be updated")
.update(entityFactory.target().update(target.getControllerId()).name(INVALID_TEXT_HTML))); .isThrownBy(() -> targetManagement.update(targetUpdateInvalidHtml));
final TargetUpdate targetUpdateEmpty = entityFactory.target().update(target.getControllerId()).name("");
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("target with too short name should not be updated").isThrownBy(() -> targetManagement .as("target with too short name should not be updated")
.update(entityFactory.target().update(target.getControllerId()).name(""))); .isThrownBy(() -> targetManagement.update(targetUpdateEmpty));
} }
@Step @Step
private void createAndUpdateTargetWithInvalidSecurityToken(final Target target) { private void createAndUpdateTargetWithInvalidSecurityToken(final Target target) {
final TargetCreate targetCreateTooLong = entityFactory.target().create().controllerId("a")
.securityToken(randomString(Target.SECURITY_TOKEN_MAX_SIZE + 1));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("target with too long token should not be created") .as("target with too long token should not be created")
.isThrownBy(() -> targetManagement.create(entityFactory.target().create().controllerId("a") .isThrownBy(() -> targetManagement.create(targetCreateTooLong));
.securityToken(randomString(Target.SECURITY_TOKEN_MAX_SIZE + 1))));
final TargetCreate targetCreateInvalidTextHtml = entityFactory.target().create().controllerId("a").securityToken(INVALID_TEXT_HTML);
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("target with invalid token should not be created").isThrownBy(() -> targetManagement .as("target with invalid token should not be created")
.create(entityFactory.target().create().controllerId("a").securityToken(INVALID_TEXT_HTML))); .isThrownBy(() -> targetManagement.create(targetCreateInvalidTextHtml));
final TargetUpdate targetUpdateTooLong = entityFactory.target().update(target.getControllerId())
.securityToken(randomString(Target.SECURITY_TOKEN_MAX_SIZE + 1));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("target with too long token should not be updated") .as("target with too long token should not be updated")
.isThrownBy(() -> targetManagement.update(entityFactory.target().update(target.getControllerId()) .isThrownBy(() -> targetManagement.update(targetUpdateTooLong));
.securityToken(randomString(Target.SECURITY_TOKEN_MAX_SIZE + 1))));
final TargetUpdate targetUpdateInvalidHtml = entityFactory.target().update(target.getControllerId()).securityToken(INVALID_TEXT_HTML);
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("target with invalid token should not be updated").isThrownBy(() -> targetManagement.update( .as("target with invalid token should not be updated")
entityFactory.target().update(target.getControllerId()).securityToken(INVALID_TEXT_HTML))); .isThrownBy(() -> targetManagement.update(targetUpdateInvalidHtml));
final TargetUpdate targetUpdateEmpty = entityFactory.target().update(target.getControllerId()).securityToken("");
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("target with too short token should not be updated").isThrownBy(() -> targetManagement .as("target with too short token should not be updated")
.update(entityFactory.target().update(target.getControllerId()).securityToken(""))); .isThrownBy(() -> targetManagement.update(targetUpdateEmpty));
} }
@Step @Step
private void createAndUpdateTargetWithInvalidAddress(final Target target) { private void createAndUpdateTargetWithInvalidAddress(final Target target) {
final TargetCreate targetCreate = entityFactory.target().create().controllerId("a").address(randomString(513));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("target with too long address should not be created") .as("target with too long address should not be created")
.isThrownBy(() -> targetManagement.create(entityFactory.target().create().controllerId("a") .isThrownBy(() -> targetManagement.create(targetCreate));
.address(randomString(513))));
assertThatExceptionOfType(InvalidTargetAddressException.class).as("target with invalid should not be created") final TargetCreate targetCreate2 = entityFactory.target().create().controllerId("a");
.isThrownBy(() -> targetManagement assertThatExceptionOfType(InvalidTargetAddressException.class)
.create(entityFactory.target().create().controllerId("a").address(INVALID_TEXT_HTML))); .as("target with invalid should not be created")
.isThrownBy(() -> targetCreate2.address(INVALID_TEXT_HTML));
final TargetUpdate targetUpdate = entityFactory.target().update(target.getControllerId()).address(randomString(513));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("target with too long address should not be updated") .as("target with too long address should not be updated")
.isThrownBy(() -> targetManagement.update(entityFactory.target().update(target.getControllerId()) .isThrownBy(() -> targetManagement.update(targetUpdate));
.address(randomString(513))));
final TargetUpdate targetUpdate2 = entityFactory.target().update(target.getControllerId());
assertThatExceptionOfType(InvalidTargetAddressException.class) assertThatExceptionOfType(InvalidTargetAddressException.class)
.as("target with invalid address should not be updated").isThrownBy(() -> targetManagement .as("target with invalid address should not be updated")
.update(entityFactory.target().update(target.getControllerId()).address(INVALID_TEXT_HTML))); .isThrownBy(() -> targetUpdate2.address(INVALID_TEXT_HTML));
} }
@Step @Step
private void createTargetWithInvalidControllerId() { private void createTargetWithInvalidControllerId() {
final TargetCreate targetCreateEmpty = entityFactory.target().create().controllerId("");
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("target with empty controller id should not be created") .as("target with empty controller id should not be created")
.isThrownBy(() -> targetManagement.create(entityFactory.target().create().controllerId(""))); .isThrownBy(() -> targetManagement.create(targetCreateEmpty));
final TargetCreate targetCreateNull = entityFactory.target().create().controllerId(null);
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("target with null controller id should not be created") .as("target with null controller id should not be created")
.isThrownBy(() -> targetManagement.create(entityFactory.target().create().controllerId(null))); .isThrownBy(() -> targetManagement.create(targetCreateNull));
final TargetCreate targetCreateTooLongControllerId = entityFactory.target().create()
.controllerId(randomString(Target.CONTROLLER_ID_MAX_SIZE + 1));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("target with too long controller id should not be created") .as("target with too long controller id should not be created")
.isThrownBy(() -> targetManagement.create(entityFactory.target().create() .isThrownBy(() -> targetManagement.create(targetCreateTooLongControllerId));
.controllerId(randomString(Target.CONTROLLER_ID_MAX_SIZE + 1))));
final TargetCreate targetCreateInvaidTextHtml = entityFactory.target().create().controllerId(INVALID_TEXT_HTML);
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("target with invalid controller id should not be created").isThrownBy( .as("target with invalid controller id should not be created")
() -> targetManagement.create(entityFactory.target().create().controllerId(INVALID_TEXT_HTML))); .isThrownBy(() -> targetManagement.create(targetCreateInvaidTextHtml));
final TargetCreate targetCreateEmptyTrim = entityFactory.target().create().controllerId(" ");
assertThatExceptionOfType(ConstraintViolationException.class).as(WHITESPACE_ERROR) assertThatExceptionOfType(ConstraintViolationException.class).as(WHITESPACE_ERROR)
.isThrownBy(() -> targetManagement.create(entityFactory.target().create().controllerId(" "))); .isThrownBy(() -> targetManagement.create(targetCreateEmptyTrim));
final TargetCreate targetCreateContainingSpace = entityFactory.target().create().controllerId("a b");
assertThatExceptionOfType(ConstraintViolationException.class).as(WHITESPACE_ERROR) assertThatExceptionOfType(ConstraintViolationException.class).as(WHITESPACE_ERROR)
.isThrownBy(() -> targetManagement.create(entityFactory.target().create().controllerId("a b"))); .isThrownBy(() -> targetManagement.create(targetCreateContainingSpace));
final TargetCreate targetCreateEmptyTrim2 = entityFactory.target().create().controllerId(" ");
assertThatExceptionOfType(ConstraintViolationException.class).as(WHITESPACE_ERROR) assertThatExceptionOfType(ConstraintViolationException.class).as(WHITESPACE_ERROR)
.isThrownBy(() -> targetManagement.create(entityFactory.target().create().controllerId(" "))); .isThrownBy(() -> targetManagement.create(targetCreateEmptyTrim2));
final TargetCreate targetCreateContainingSpaces = entityFactory.target().create().controllerId("aaa bbb");
assertThatExceptionOfType(ConstraintViolationException.class).as(WHITESPACE_ERROR) assertThatExceptionOfType(ConstraintViolationException.class).as(WHITESPACE_ERROR)
.isThrownBy(() -> targetManagement.create(entityFactory.target().create().controllerId("aaa bbb"))); .isThrownBy(() -> targetManagement.create(targetCreateContainingSpaces));
} }

View File

@@ -27,6 +27,8 @@ import io.qameta.allure.Feature;
import io.qameta.allure.Step; import io.qameta.allure.Step;
import io.qameta.allure.Story; import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.TargetTagManagement; import org.eclipse.hawkbit.repository.TargetTagManagement;
import org.eclipse.hawkbit.repository.builder.TagCreate;
import org.eclipse.hawkbit.repository.builder.TagUpdate;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetTagUpdatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetTagUpdatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetCreatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.TargetCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetTagUpdatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.TargetTagUpdatedEvent;
@@ -217,9 +219,9 @@ class TargetTagManagementTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Ensures that a tag cannot be created if one exists already with that name (expects EntityAlreadyExistsException).") @Description("Ensures that a tag cannot be created if one exists already with that name (expects EntityAlreadyExistsException).")
void failedDuplicateTargetTagNameException() { void failedDuplicateTargetTagNameException() {
targetTagManagement.create(entityFactory.tag().create().name("A")); final TagCreate tagCreate = entityFactory.tag().create().name("A");
assertThatExceptionOfType(EntityAlreadyExistsException.class) targetTagManagement.create(tagCreate);
.isThrownBy(() -> targetTagManagement.create(entityFactory.tag().create().name("A"))); assertThatExceptionOfType(EntityAlreadyExistsException.class).isThrownBy(() -> targetTagManagement.create(tagCreate));
} }
@Test @Test
@@ -228,67 +230,72 @@ class TargetTagManagementTest extends AbstractJpaIntegrationTest {
targetTagManagement.create(entityFactory.tag().create().name("A")); targetTagManagement.create(entityFactory.tag().create().name("A"));
final TargetTag tag = targetTagManagement.create(entityFactory.tag().create().name("B")); final TargetTag tag = targetTagManagement.create(entityFactory.tag().create().name("B"));
assertThatExceptionOfType(EntityAlreadyExistsException.class) final TagUpdate tagUpdate = entityFactory.tag().update(tag.getId()).name("A");
.isThrownBy(() -> targetTagManagement.update(entityFactory.tag().update(tag.getId()).name("A"))); assertThatExceptionOfType(EntityAlreadyExistsException.class).isThrownBy(() -> targetTagManagement.update(tagUpdate));
} }
@Step @Step
private void createAndUpdateTagWithInvalidDescription(final Tag tag) { private void createAndUpdateTagWithInvalidDescription(final Tag tag) {
final TagCreate tagCraeteTooLong = entityFactory.tag().create().name("a").description(randomString(513));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("tag with too long description should not be created") .as("tag with too long description should not be created")
.isThrownBy(() -> targetTagManagement.create( .isThrownBy(() -> targetTagManagement.create(tagCraeteTooLong));
entityFactory.tag().create().name("a").description(randomString(513)))); final TagCreate tagCreateInvalidHtml = entityFactory.tag().create().name("a").description(INVALID_TEXT_HTML);
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("tag with invalid description should not be created").isThrownBy(() -> targetTagManagement .as("tag with invalid description should not be created")
.create(entityFactory.tag().create().name("a").description(INVALID_TEXT_HTML))); .isThrownBy(() -> targetTagManagement.create(tagCreateInvalidHtml));
final TagUpdate tagUpdateTooLong = entityFactory.tag().update(tag.getId()).description(randomString(513));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("tag with too long description should not be updated") .as("tag with too long description should not be updated")
.isThrownBy(() -> targetTagManagement.update( .isThrownBy(() -> targetTagManagement.update(tagUpdateTooLong));
entityFactory.tag().update(tag.getId()) final TagUpdate tagUpdateInvalidHtml = entityFactory.tag().update(tag.getId()).description(INVALID_TEXT_HTML);
.description(randomString(513))));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("tag with invalid description should not be updated") .as("tag with invalid description should not be updated")
.isThrownBy(() -> targetTagManagement .isThrownBy(() -> targetTagManagement.update(tagUpdateInvalidHtml));
.update(entityFactory.tag().update(tag.getId()).description(INVALID_TEXT_HTML)));
} }
@Step @Step
private void createAndUpdateTagWithInvalidColour(final Tag tag) { private void createAndUpdateTagWithInvalidColour(final Tag tag) {
final TagCreate tagCreateTooLong = entityFactory.tag().create().name("a").colour(randomString(17));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("tag with too long colour should not be created") .as("tag with too long colour should not be created")
.isThrownBy(() -> targetTagManagement.create( .isThrownBy(() -> targetTagManagement.create(tagCreateTooLong));
entityFactory.tag().create().name("a").colour(randomString(17)))); final TagCreate tagCraeteInvalidHtml = entityFactory.tag().create().name("a").colour(INVALID_TEXT_HTML);
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("tag with invalid colour should not be created").isThrownBy(() -> targetTagManagement .as("tag with invalid colour should not be created")
.create(entityFactory.tag().create().name("a").colour(INVALID_TEXT_HTML))); .isThrownBy(() -> targetTagManagement.create(tagCraeteInvalidHtml));
final TagUpdate tagUpdateTooLong = entityFactory.tag().update(tag.getId()).colour(randomString(17));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("tag with too long colour should not be updated") .as("tag with too long colour should not be updated")
.isThrownBy(() -> targetTagManagement.update( .isThrownBy(() -> targetTagManagement.update(tagUpdateTooLong));
entityFactory.tag().update(tag.getId()).colour(randomString(17)))); final TagUpdate tagUpdateInvalidHtml = entityFactory.tag().update(tag.getId()).colour(INVALID_TEXT_HTML);
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("tag with invalid colour should not be updated").isThrownBy(() -> targetTagManagement .as("tag with invalid colour should not be updated")
.update(entityFactory.tag().update(tag.getId()).colour(INVALID_TEXT_HTML))); .isThrownBy(() -> targetTagManagement
.update(tagUpdateInvalidHtml));
} }
@Step @Step
private void createAndUpdateTagWithInvalidName(final Tag tag) { private void createAndUpdateTagWithInvalidName(final Tag tag) {
final TagCreate tagCreateTooLong = entityFactory.tag().create().name(randomString(NamedEntity.NAME_MAX_SIZE + 1));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("tag with too long name should not be created") .as("tag with too long name should not be created")
.isThrownBy(() -> targetTagManagement .isThrownBy(() -> targetTagManagement.create(tagCreateTooLong));
.create(entityFactory.tag().create().name(randomString(NamedEntity.NAME_MAX_SIZE + 1)))); final TagCreate tagCreateInvalidHtml = entityFactory.tag().create().name(INVALID_TEXT_HTML);
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("tag with invalid name should not be created") .as("tag with invalid name should not be created")
.isThrownBy(() -> targetTagManagement.create(entityFactory.tag().create().name(INVALID_TEXT_HTML))); .isThrownBy(() -> targetTagManagement.create(tagCreateInvalidHtml));
final TagUpdate tagUpdateTooLong = entityFactory.tag().update(tag.getId()).name(randomString(NamedEntity.NAME_MAX_SIZE + 1));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("tag with too long name should not be updated") .as("tag with too long name should not be updated")
.isThrownBy(() -> targetTagManagement .isThrownBy(() -> targetTagManagement.update(tagUpdateTooLong));
.update(entityFactory.tag().update(tag.getId()).name(randomString(NamedEntity.NAME_MAX_SIZE + 1)))); final TagUpdate tagUpdateInvalidHtml = entityFactory.tag().update(tag.getId()).name(INVALID_TEXT_HTML);
assertThatExceptionOfType(ConstraintViolationException.class).as("tag with invalid name should not be updated") assertThatExceptionOfType(ConstraintViolationException.class).as("tag with invalid name should not be updated")
.isThrownBy(() -> targetTagManagement .isThrownBy(() -> targetTagManagement.update(tagUpdateInvalidHtml));
.update(entityFactory.tag().update(tag.getId()).name(INVALID_TEXT_HTML))); final TagUpdate tagUpdateEmpty = entityFactory.tag().update(tag.getId()).name("");
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("tag with too short name should not be updated") .as("tag with too short name should not be updated")
.isThrownBy(() -> targetTagManagement.update(entityFactory.tag().update(tag.getId()).name(""))); .isThrownBy(() -> targetTagManagement.update(tagUpdateEmpty));
} }
@SafeVarargs @SafeVarargs

View File

@@ -23,7 +23,7 @@ import org.junit.jupiter.api.Test;
@Slf4j @Slf4j
@Feature("SecurityTests - TargetTypeManagement") @Feature("SecurityTests - TargetTypeManagement")
@Story("SecurityTests TargetTypeManagement") @Story("SecurityTests TargetTypeManagement")
public class TargetTypeManagementSecurityTest extends AbstractJpaIntegrationTest { class TargetTypeManagementSecurityTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.") @Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")

View File

@@ -22,6 +22,8 @@ import io.qameta.allure.Description;
import io.qameta.allure.Feature; import io.qameta.allure.Feature;
import io.qameta.allure.Step; import io.qameta.allure.Step;
import io.qameta.allure.Story; import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.builder.TargetTypeCreate;
import org.eclipse.hawkbit.repository.builder.TargetTypeUpdate;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetTypeCreatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.TargetTypeCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetTypeUpdatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.TargetTypeUpdatedEvent;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
@@ -74,24 +76,26 @@ class TargetTypeManagementTest extends AbstractJpaIntegrationTest {
@Step @Step
void createAndUpdateTargetTypeWithInvalidDescription(final TargetType targetType) { void createAndUpdateTargetTypeWithInvalidDescription(final TargetType targetType) {
final TargetTypeCreate targetTypeCreateTooLong = entityFactory.targetType().create().name("a").description(randomString(TargetType.DESCRIPTION_MAX_SIZE + 1));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("targetType with too long description should not be created") .as("targetType with too long description should not be created")
.isThrownBy(() -> targetTypeManagement.create( .isThrownBy(() -> targetTypeManagement.create(targetTypeCreateTooLong));
entityFactory.targetType().create().name("a").description(randomString(TargetType.DESCRIPTION_MAX_SIZE + 1))));
final TargetTypeCreate targetTypeCreateInvalidHtml = entityFactory.targetType().create().name("a").description(INVALID_TEXT_HTML);
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("targetType with invalid description should not be created").isThrownBy(() -> targetTypeManagement .as("targetType with invalid description should not be created")
.create(entityFactory.targetType().create().name("a").description(INVALID_TEXT_HTML))); .isThrownBy(() -> targetTypeManagement.create(targetTypeCreateInvalidHtml));
final TargetTypeUpdate targetTypeUpdateTooLong = entityFactory.targetType().update(targetType.getId())
.description(randomString(TargetType.DESCRIPTION_MAX_SIZE + 1));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("targetType with too long description should not be updated") .as("targetType with too long description should not be updated")
.isThrownBy(() -> targetTypeManagement.update( .isThrownBy(() -> targetTypeManagement.update(targetTypeUpdateTooLong));
entityFactory.targetType().update(targetType.getId()).description(randomString(TargetType.DESCRIPTION_MAX_SIZE + 1))));
final TargetTypeUpdate targetTypeUpdateInvalidHtml = entityFactory.targetType().update(targetType.getId()).description(INVALID_TEXT_HTML);
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("targetType with invalid description should not be updated") .as("targetType with invalid description should not be updated")
.isThrownBy(() -> targetTypeManagement .isThrownBy(() -> targetTypeManagement.update(targetTypeUpdateInvalidHtml));
.update(entityFactory.targetType().update(targetType.getId()).description(INVALID_TEXT_HTML)));
} }
@Test @Test
@@ -191,9 +195,9 @@ class TargetTypeManagementTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Ensures that a target type cannot be created if one exists already with that name (expects EntityAlreadyExistsException).") @Description("Ensures that a target type cannot be created if one exists already with that name (expects EntityAlreadyExistsException).")
void failedDuplicateTargetTypeNameException() { void failedDuplicateTargetTypeNameException() {
targetTypeManagement.create(entityFactory.targetType().create().name("targettype123")); final TargetTypeCreate targetTypeCreate = entityFactory.targetType().create().name("targettype123");
assertThrows(EntityAlreadyExistsException.class, targetTypeManagement.create(targetTypeCreate);
() -> targetTypeManagement.create(entityFactory.targetType().create().name("targettype123"))); assertThrows(EntityAlreadyExistsException.class, () -> targetTypeManagement.create(targetTypeCreate));
} }
@Test @Test
@@ -207,59 +211,67 @@ class TargetTypeManagementTest extends AbstractJpaIntegrationTest {
@Step @Step
private void createAndUpdateTargetTypeWithInvalidColour(final TargetType targetType) { private void createAndUpdateTargetTypeWithInvalidColour(final TargetType targetType) {
final TargetTypeCreate targetTypeCreateTooLong = entityFactory.targetType().create().name("a").colour(randomString(Type.COLOUR_MAX_SIZE + 1));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("targetType with too long colour should not be created") .as("targetType with too long colour should not be created")
.isThrownBy(() -> targetTypeManagement.create( .isThrownBy(() -> targetTypeManagement.create(targetTypeCreateTooLong));
entityFactory.targetType().create().name("a").colour(randomString(Type.COLOUR_MAX_SIZE + 1))));
final TargetTypeCreate targetTypeCreateInvalidHtml = entityFactory.targetType().create().name("a").colour(INVALID_TEXT_HTML);
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("targetType with invalid colour should not be created").isThrownBy(() -> targetTypeManagement .as("targetType with invalid colour should not be created")
.create(entityFactory.targetType().create().name("a").colour(INVALID_TEXT_HTML))); .isThrownBy(() -> targetTypeManagement.create(targetTypeCreateInvalidHtml));
final TargetTypeUpdate targetTypeUpdateTooLong = entityFactory.targetType().update(targetType.getId()).colour(randomString(Type.COLOUR_MAX_SIZE + 1));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("targetType with too long colour should not be updated") .as("targetType with too long colour should not be updated")
.isThrownBy(() -> targetTypeManagement.update( .isThrownBy(() -> targetTypeManagement.update(targetTypeUpdateTooLong));
entityFactory.targetType().update(targetType.getId()).colour(randomString(Type.COLOUR_MAX_SIZE + 1))));
final TargetTypeUpdate targetTypeUpdateInvalidHtml = entityFactory.targetType().update(targetType.getId()).colour(INVALID_TEXT_HTML);
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("targetType with invalid colour should not be updated").isThrownBy(() -> targetTypeManagement .as("targetType with invalid colour should not be updated")
.update(entityFactory.targetType().update(targetType.getId()).colour(INVALID_TEXT_HTML))); .isThrownBy(() -> targetTypeManagement.update(targetTypeUpdateInvalidHtml));
} }
@Step @Step
private void createTargetTypeWithInvalidKey() { private void createTargetTypeWithInvalidKey() {
final TargetTypeCreate targetTypeCreateTooLong = entityFactory.targetType().create().name(randomString(Type.KEY_MAX_SIZE + 1));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("targetType with too long key should not be created") .as("targetType with too long key should not be created")
.isThrownBy(() -> targetTypeManagement.create(entityFactory.targetType().create().name(randomString(Type.KEY_MAX_SIZE + 1)))); .isThrownBy(() -> targetTypeManagement.create(targetTypeCreateTooLong));
final TargetTypeCreate targetTypeCreateInvalidHtmle = entityFactory.targetType().create().name(INVALID_TEXT_HTML);
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("targetType with invalid key should not be created").isThrownBy( .as("targetType with invalid key should not be created")
() -> targetTypeManagement.create(entityFactory.targetType().create().name(INVALID_TEXT_HTML))); .isThrownBy(() -> targetTypeManagement.create(targetTypeCreateInvalidHtmle));
} }
@Step @Step
private void createAndUpdateTargetTypeWithInvalidName(final TargetType targetType) { private void createAndUpdateTargetTypeWithInvalidName(final TargetType targetType) {
final TargetTypeCreate targetTypeCreateTooLong = entityFactory.targetType().create().name(randomString(NamedEntity.NAME_MAX_SIZE + 1));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("targetType with too long name should not be created") .as("targetType with too long name should not be created")
.isThrownBy(() -> targetTypeManagement .isThrownBy(() -> targetTypeManagement
.create(entityFactory.targetType().create().name(randomString(NamedEntity.NAME_MAX_SIZE + 1)))); .create(targetTypeCreateTooLong));
final TargetTypeCreate targetTypeCreateInvalidHtml = entityFactory.targetType().create().name(INVALID_TEXT_HTML);
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("targetType with invalid name should not be created").isThrownBy( .as("targetType with invalid name should not be created")
() -> targetTypeManagement.create(entityFactory.targetType().create().name(INVALID_TEXT_HTML))); .isThrownBy(() -> targetTypeManagement.create(targetTypeCreateInvalidHtml));
final TargetTypeUpdate targetTypeUpdateTooLong = entityFactory.targetType().update(targetType.getId()).name(randomString(NamedEntity.NAME_MAX_SIZE + 1));
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("targetType with too long name should not be updated") .as("targetType with too long name should not be updated")
.isThrownBy(() -> targetTypeManagement .isThrownBy(() -> targetTypeManagement.update(targetTypeUpdateTooLong));
.update(entityFactory.targetType().update(targetType.getId()).name(randomString(NamedEntity.NAME_MAX_SIZE + 1))));
final TargetTypeUpdate targetTypeUpdateInvalidHtml = entityFactory.targetType().update(targetType.getId()).name(INVALID_TEXT_HTML);
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("targetType with invalid name should not be updated").isThrownBy(() -> targetTypeManagement .as("targetType with invalid name should not be updated")
.update(entityFactory.targetType().update(targetType.getId()).name(INVALID_TEXT_HTML))); .isThrownBy(() -> targetTypeManagement.update(targetTypeUpdateInvalidHtml));
final TargetTypeUpdate targetTypeUpdateEmpty = entityFactory.targetType().update(targetType.getId()).name("");
assertThatExceptionOfType(ConstraintViolationException.class) assertThatExceptionOfType(ConstraintViolationException.class)
.as("targetType with too short name should not be updated").isThrownBy(() -> targetTypeManagement .as("targetType with too short name should not be updated")
.update(entityFactory.targetType().update(targetType.getId()).name(""))); .isThrownBy(() -> targetTypeManagement.update(targetTypeUpdateEmpty));
} }

View File

@@ -23,7 +23,7 @@ import org.junit.jupiter.api.Test;
@Slf4j @Slf4j
@Feature("SecurityTests - TargetManagement") @Feature("SecurityTests - TargetManagement")
@Story("SecurityTests TargetManagement") @Story("SecurityTests TargetManagement")
public class TenantConfigurationManagementSecurityTest extends AbstractJpaIntegrationTest { class TenantConfigurationManagementSecurityTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.") @Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")

View File

@@ -45,15 +45,14 @@ class TenantConfigurationManagementTest extends AbstractJpaIntegrationTest imple
@Test @Test
@Description("Tests that tenant specific configuration can be persisted and in case the tenant does not have specific configuration the default from environment is used instead.") @Description("Tests that tenant specific configuration can be persisted and in case the tenant does not have specific configuration the default from environment is used instead.")
void storeTenantSpecificConfigurationAsString() { void storeTenantSpecificConfigurationAsString() {
final String envPropertyDefault = environment final String envPropertyDefault = environment.getProperty("hawkbit.server.ddi.security.authentication.gatewaytoken.key");
.getProperty("hawkbit.server.ddi.security.authentication.gatewaytoken.key");
assertThat(envPropertyDefault).isNotNull(); assertThat(envPropertyDefault).isNotNull();
// get the configuration from the system management // get the configuration from the system management
final TenantConfigurationValue<String> defaultConfigValue = tenantConfigurationManagement.getConfigurationValue( final TenantConfigurationValue<String> defaultConfigValue = tenantConfigurationManagement.getConfigurationValue(
TenantConfigurationKey.AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY, String.class); TenantConfigurationKey.AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY, String.class);
assertThat(defaultConfigValue.isGlobal()).isEqualTo(true); assertThat(defaultConfigValue.isGlobal()).isTrue();
assertThat(defaultConfigValue.getValue()).isEqualTo(envPropertyDefault); assertThat(defaultConfigValue.getValue()).isEqualTo(envPropertyDefault);
// update the tenant specific configuration // update the tenant specific configuration
@@ -66,7 +65,7 @@ class TenantConfigurationManagementTest extends AbstractJpaIntegrationTest imple
final TenantConfigurationValue<String> updatedConfigurationValue = tenantConfigurationManagement final TenantConfigurationValue<String> updatedConfigurationValue = tenantConfigurationManagement
.getConfigurationValue(TenantConfigurationKey.AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY, String.class); .getConfigurationValue(TenantConfigurationKey.AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY, String.class);
assertThat(updatedConfigurationValue.isGlobal()).isEqualTo(false); assertThat(updatedConfigurationValue.isGlobal()).isFalse();
assertThat(updatedConfigurationValue.getValue()).isEqualTo(newConfigurationValue); assertThat(updatedConfigurationValue.getValue()).isEqualTo(newConfigurationValue);
// assertThat(tenantConfigurationManagement.getTenantConfigurations()).hasSize(1); // assertThat(tenantConfigurationManagement.getTenantConfigurations()).hasSize(1);
} }
@@ -257,9 +256,9 @@ class TenantConfigurationManagementTest extends AbstractJpaIntegrationTest imple
void verifyThatAllKeysAreDifferent() { void verifyThatAllKeysAreDifferent() {
final Map<String, Void> keyNames = new HashMap<>(); final Map<String, Void> keyNames = new HashMap<>();
tenantConfigurationProperties.getConfigurationKeys().forEach(key -> { tenantConfigurationProperties.getConfigurationKeys().forEach(key -> {
if (keyNames.containsKey(key.getKeyName())) { assertThat(keyNames)
throw new IllegalStateException("The key names are not unique"); .as("The key names are not unique")
} .doesNotContainKey(key.getKeyName());
keyNames.put(key.getKeyName(), null); keyNames.put(key.getKeyName(), null);
}); });
} }

View File

@@ -22,7 +22,6 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.UUID; import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
@@ -85,6 +84,7 @@ import org.springframework.util.ObjectUtils;
/** /**
* Data generator utility for tests. * Data generator utility for tests.
*/ */
@SuppressWarnings("java:S107")
public class TestdataFactory { public class TestdataFactory {
public static final String VISIBLE_SM_MD_KEY = "visibleMetdataKey"; public static final String VISIBLE_SM_MD_KEY = "visibleMetdataKey";
@@ -1157,7 +1157,7 @@ public class TestdataFactory {
public TargetType createTargetType(final String targetTypeName, final List<DistributionSetType> compatibleDsTypes) { public TargetType createTargetType(final String targetTypeName, final List<DistributionSetType> compatibleDsTypes) {
return targetTypeManagement.create(entityFactory.targetType().create().name(targetTypeName) return targetTypeManagement.create(entityFactory.targetType().create().name(targetTypeName)
.description(targetTypeName + SPACE_AND_DESCRIPTION).colour(DEFAULT_COLOUR) .description(targetTypeName + SPACE_AND_DESCRIPTION).colour(DEFAULT_COLOUR)
.compatible(compatibleDsTypes.stream().map(DistributionSetType::getId).collect(Collectors.toList()))); .compatible(compatibleDsTypes.stream().map(DistributionSetType::getId).toList()));
} }
/** /**

View File

@@ -127,10 +127,8 @@ public interface UpdateHandler {
new UpdateStatus( new UpdateStatus(
UpdateStatus.Status.DOWNLOAD, UpdateStatus.Status.DOWNLOAD,
modules.stream().flatMap(mod -> mod.getArtifacts().stream()) modules.stream().flatMap(mod -> mod.getArtifacts().stream())
.map(art -> "Download start for: " + art.getFilename() + .map(art -> "Download start for: " + art.getFilename() + " with size " + art.getSize() + " and hashes " + art.getHashes() + " ...")
" with size " + art.getSize() + .toList()));
" and hashes " + art.getHashes() + " ...")
.collect(Collectors.toList())));
log.info(LOG_PREFIX + "Start download", ddiController.getTenantId(), ddiController.getControllerId()); log.info(LOG_PREFIX + "Start download", ddiController.getTenantId(), ddiController.getControllerId());

View File

@@ -23,7 +23,6 @@ import java.util.HexFormat;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.classic.methods.HttpGet;
@@ -133,7 +132,7 @@ public interface UpdateHandler {
.map(art -> "Download start for: " + art.getFilename() + .map(art -> "Download start for: " + art.getFilename() +
" with size " + art.getSize() + " with size " + art.getSize() +
" and hashes " + art.getHashes() + " ...") " and hashes " + art.getHashes() + " ...")
.collect(Collectors.toList()))); .toList()));
log.info(LOG_PREFIX + "Start download", dmfController.getTenantId(), dmfController.getControllerId()); log.info(LOG_PREFIX + "Start download", dmfController.getTenantId(), dmfController.getControllerId());

View File

@@ -135,10 +135,8 @@ public class VHost extends DmfSender implements MessageListener {
} }
protected void handleCancelDownloadAction(final Message message, final String thingId) { protected void handleCancelDownloadAction(final Message message, final String thingId) {
final String tenant = getTenant(message);
final Long actionId = extractActionIdFrom(message); final Long actionId = extractActionIdFrom(message);
processCancelDownloadAction(thingId, actionId);
processCancelDownloadAction(thingId, tenant, actionId);
} }
protected void handleUpdateProcess(final Message message, final String controllerId, final EventTopic actionType) { protected void handleUpdateProcess(final Message message, final String controllerId, final EventTopic actionType) {
@@ -193,7 +191,7 @@ public class VHost extends DmfSender implements MessageListener {
@SuppressWarnings({ "squid:S2259" }) final EventTopic eventTopic = EventTopic.valueOf(eventHeader.toString()); @SuppressWarnings({ "squid:S2259" }) final EventTopic eventTopic = EventTopic.valueOf(eventHeader.toString());
switch (eventTopic) { switch (eventTopic) {
case CONFIRM: case CONFIRM:
handleConfirmation(message, thingId); handleConfirmation(thingId);
break; break;
case DOWNLOAD_AND_INSTALL, DOWNLOAD: case DOWNLOAD_AND_INSTALL, DOWNLOAD:
handleUpdateProcess(message, thingId, eventTopic); handleUpdateProcess(message, thingId, eventTopic);
@@ -213,7 +211,7 @@ public class VHost extends DmfSender implements MessageListener {
} }
} }
private void handleConfirmation(final Message message, final String controllerId) { private void handleConfirmation(final String controllerId) {
log.warn("Handle confirmed received for {}! Skip it!", controllerId); log.warn("Handle confirmed received for {}! Skip it!", controllerId);
} }
@@ -241,14 +239,13 @@ public class VHost extends DmfSender implements MessageListener {
openActions.add(actionId); openActions.add(actionId);
switch (eventTopic) { switch (eventTopic) {
case DOWNLOAD: case DOWNLOAD, DOWNLOAD_AND_INSTALL:
case DOWNLOAD_AND_INSTALL: if (action instanceof DmfDownloadAndUpdateRequest dmfDownloadAndUpdateRequest) {
if (action instanceof DmfDownloadAndUpdateRequest) { processUpdate(tenant, controllerId, eventTopic, dmfDownloadAndUpdateRequest);
processUpdate(tenant, controllerId, eventTopic, (DmfDownloadAndUpdateRequest) action);
} }
break; break;
case CANCEL_DOWNLOAD: case CANCEL_DOWNLOAD:
processCancelDownloadAction(controllerId, tenant, action.getActionId()); processCancelDownloadAction(controllerId, action.getActionId());
break; break;
default: default:
openActions.remove(actionId); openActions.remove(actionId);
@@ -257,7 +254,7 @@ public class VHost extends DmfSender implements MessageListener {
} }
} }
private void processCancelDownloadAction(final String thingId, final String tenant, final Long actionId) { private void processCancelDownloadAction(final String thingId, final Long actionId) {
finishUpdateProcess(thingId, actionId, Collections.singletonList("Simulation canceled")); finishUpdateProcess(thingId, actionId, Collections.singletonList("Simulation canceled"));
openActions.remove(actionId); openActions.remove(actionId);
} }

View File

@@ -74,6 +74,7 @@ public class Utils {
return numberField; return numberField;
} }
@SuppressWarnings("java:S119") // better readability
public static <T, ID> HorizontalLayout addRemoveControls( public static <T, ID> HorizontalLayout addRemoveControls(
final Function<SelectionGrid<T, ID>, CompletionStage<Void>> addHandler, final Function<SelectionGrid<T, ID>, CompletionStage<Void>> addHandler,
final Function<SelectionGrid<T, ID>, CompletionStage<Void>> removeHandler, final Function<SelectionGrid<T, ID>, CompletionStage<Void>> removeHandler,