Signed-off-by: Avgustin Marinov <Avgustin.Marinov@bosch.com>
This commit is contained in:
Avgustin Marinov
2025-01-24 20:10:28 +02:00
committed by GitHub
parent ef4c0c6d18
commit bbb2193d74
37 changed files with 227 additions and 239 deletions

View File

@@ -26,7 +26,7 @@ import org.springframework.data.domain.Sort.Order;
@Feature("Component Tests - Management API") @Feature("Component Tests - Management API")
@Story("Sorting parameter") @Story("Sorting parameter")
public class SortUtilityTest { class SortUtilityTest {
private static final String SORT_PARAM_1 = "NAME:ASC"; private static final String SORT_PARAM_1 = "NAME:ASC";
private static final String SORT_PARAM_2 = "NAME:ASC, DESCRIPTION:DESC"; private static final String SORT_PARAM_2 = "NAME:ASC, DESCRIPTION:DESC";
@@ -38,42 +38,43 @@ public class SortUtilityTest {
@Test @Test
@Description("Ascending sorting based on name.") @Description("Ascending sorting based on name.")
public void parseSortParam1() { void parseSortParam1() {
final List<Order> parse = SortUtility.parse(TargetFields.class, SORT_PARAM_1); final List<Order> parse = SortUtility.parse(TargetFields.class, SORT_PARAM_1);
assertThat(parse).as("Count of parsing parameter").hasSize(1); assertThat(parse).as("Count of parsing parameter").hasSize(1);
} }
@Test @Test
@Description("Ascending sorting based on name and descending sorting based on description.") @Description("Ascending sorting based on name and descending sorting based on description.")
public void parseSortParam2() { void parseSortParam2() {
final List<Order> parse = SortUtility.parse(TargetFields.class, SORT_PARAM_2); final List<Order> parse = SortUtility.parse(TargetFields.class, SORT_PARAM_2);
assertThat(parse).as("Count of parsing parameter").hasSize(2); assertThat(parse).as("Count of parsing parameter").hasSize(2);
} }
@Test @Test
@Description("Sorting with wrong syntax leads to SortParameterSyntaxErrorException.") @Description("Sorting with wrong syntax leads to SortParameterSyntaxErrorException.")
public void parseWrongSyntaxParam() { void parseWrongSyntaxParam() {
assertThrows(SortParameterSyntaxErrorException.class, assertThrows(SortParameterSyntaxErrorException.class,
() -> SortUtility.parse(TargetFields.class, SYNTAX_FAILURE_SORT_PARAM)); () -> SortUtility.parse(TargetFields.class, SYNTAX_FAILURE_SORT_PARAM));
} }
@Test @Test
@Description("Sorting based on name with case sensitive is possible.") @Description("Sorting based on name with case sensitive is possible.")
public void parsingIsNotCaseSensitive() { @SuppressWarnings("squid:S2699") // assert no error
void parsingIsNotCaseSensitive() {
SortUtility.parse(TargetFields.class, CASE_INSENSITIVE_DIRECTION_PARAM); SortUtility.parse(TargetFields.class, CASE_INSENSITIVE_DIRECTION_PARAM);
SortUtility.parse(TargetFields.class, CASE_INSENSITIVE_DIRECTION_PARAM_1); SortUtility.parse(TargetFields.class, CASE_INSENSITIVE_DIRECTION_PARAM_1);
} }
@Test @Test
@Description("Sorting with unknown direction order leads to SortParameterUnsupportedDirectionException.") @Description("Sorting with unknown direction order leads to SortParameterUnsupportedDirectionException.")
public void parseWrongDirectionParam() { void parseWrongDirectionParam() {
assertThrows(SortParameterUnsupportedDirectionException.class, assertThrows(SortParameterUnsupportedDirectionException.class,
() -> SortUtility.parse(TargetFields.class, WRONG_DIRECTION_PARAM)); () -> SortUtility.parse(TargetFields.class, WRONG_DIRECTION_PARAM));
} }
@Test @Test
@Description("Sorting with unknown field leads to SortParameterUnsupportedFieldException.") @Description("Sorting with unknown field leads to SortParameterUnsupportedFieldException.")
public void parseWrongFieldParam() { void parseWrongFieldParam() {
assertThrows(SortParameterUnsupportedFieldException.class, assertThrows(SortParameterUnsupportedFieldException.class,
() -> SortUtility.parse(TargetFields.class, WRONG_FIELD_PARAM)); () -> SortUtility.parse(TargetFields.class, WRONG_FIELD_PARAM));
} }

View File

@@ -9,8 +9,6 @@
*/ */
package org.eclipse.hawkbit.repository.builder; package org.eclipse.hawkbit.repository.builder;
import java.util.Optional;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size; import jakarta.validation.constraints.Size;
@@ -62,8 +60,8 @@ public interface SoftwareModuleCreate {
* @param type for {@link SoftwareModule#getType()} * @param type for {@link SoftwareModule#getType()}
* @return updated builder instance * @return updated builder instance
*/ */
default SoftwareModuleCreate type(final SoftwareModuleType type) { default SoftwareModuleCreate type(@NotNull final SoftwareModuleType type) {
return type(Optional.ofNullable(type).map(SoftwareModuleType::getKey).orElse(null)); return type(type.getKey());
} }
/** /**

View File

@@ -12,7 +12,6 @@ package org.eclipse.hawkbit.repository.event.remote;
import java.io.Serial; import java.io.Serial;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
@@ -47,8 +46,7 @@ public class TargetAssignDistributionSetEvent extends AbstractAssignmentEvent {
public TargetAssignDistributionSetEvent(final String tenant, final long distributionSetId, final List<Action> a, public TargetAssignDistributionSetEvent(final String tenant, final long distributionSetId, final List<Action> a,
final String applicationId, final boolean maintenanceWindowAvailable) { final String applicationId, final boolean maintenanceWindowAvailable) {
super(distributionSetId, tenant, super(distributionSetId, tenant,
a.stream().filter(action -> action.getDistributionSet().getId().longValue() == distributionSetId) a.stream().filter(action -> action.getDistributionSet().getId().longValue() == distributionSetId).toList(),
.collect(Collectors.toList()),
applicationId); applicationId);
this.distributionSetId = distributionSetId; this.distributionSetId = distributionSetId;
this.maintenanceWindowAvailable = maintenanceWindowAvailable; this.maintenanceWindowAvailable = maintenanceWindowAvailable;

View File

@@ -11,12 +11,14 @@ package org.eclipse.hawkbit.repository.exception;
import static org.eclipse.hawkbit.repository.SizeConversionHelper.byteValueToReadableString; import static org.eclipse.hawkbit.repository.SizeConversionHelper.byteValueToReadableString;
import lombok.EqualsAndHashCode;
import org.eclipse.hawkbit.exception.AbstractServerRtException; import org.eclipse.hawkbit.exception.AbstractServerRtException;
import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.SpServerError;
/** /**
* Thrown if storage quota is exceeded * Thrown if storage quota is exceeded
*/ */
@EqualsAndHashCode(callSuper = true)
public class StorageQuotaExceededException extends AbstractServerRtException { public class StorageQuotaExceededException extends AbstractServerRtException {
private static final String MAX_ARTIFACT_SIZE_TOTAL_EXCEEDED = "Storage quota exceeded, %s left."; private static final String MAX_ARTIFACT_SIZE_TOTAL_EXCEEDED = "Storage quota exceeded, %s left.";

View File

@@ -13,9 +13,12 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import lombok.EqualsAndHashCode;
/** /**
* Bean for holding the system usage stats including tenant specific data. * Bean for holding the system usage stats including tenant specific data.
*/ */
@EqualsAndHashCode(callSuper = true)
public class SystemUsageReportWithTenants extends SystemUsageReport { public class SystemUsageReportWithTenants extends SystemUsageReport {
private final List<TenantUsage> tenants = new ArrayList<>(); private final List<TenantUsage> tenants = new ArrayList<>();

View File

@@ -13,7 +13,6 @@ import io.micrometer.core.instrument.MeterRegistry;
import lombok.AccessLevel; import lombok.AccessLevel;
import lombok.Getter; import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;

View File

@@ -306,8 +306,8 @@ public class RepositoryApplicationConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
SystemManagementCacheKeyGenerator systemManagementCacheKeyGenerator() { SystemManagementCacheKeyGenerator systemManagementCacheKeyGenerator(final TenantAware tenantAware) {
return new SystemManagementCacheKeyGenerator(); return new SystemManagementCacheKeyGenerator(tenantAware);
} }
@Bean @Bean

View File

@@ -27,8 +27,11 @@ import org.springframework.context.annotation.Bean;
public class SystemManagementCacheKeyGenerator implements CurrentTenantCacheKeyGenerator { public class SystemManagementCacheKeyGenerator implements CurrentTenantCacheKeyGenerator {
private final ThreadLocal<String> createInitialTenant = new ThreadLocal<>(); private final ThreadLocal<String> createInitialTenant = new ThreadLocal<>();
@Autowired private final TenantAware tenantAware;
private TenantAware tenantAware;
public SystemManagementCacheKeyGenerator(final TenantAware tenantAware) {
this.tenantAware = tenantAware;
}
@Override @Override
@Bean @Bean

View File

@@ -11,7 +11,6 @@ package org.eclipse.hawkbit.repository.jpa.model;
import java.io.Serial; import java.io.Serial;
import java.io.Serializable; import java.io.Serializable;
import java.util.Objects;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;

View File

@@ -11,10 +11,11 @@ package org.eclipse.hawkbit.repository.jpa.specifications;
import jakarta.persistence.criteria.ListJoin; import jakarta.persistence.criteria.ListJoin;
import org.eclipse.hawkbit.repository.jpa.model.AbstractJpaBaseEntity_;
import org.eclipse.hawkbit.repository.jpa.model.AbstractJpaNamedEntity_;
import org.eclipse.hawkbit.repository.jpa.model.AbstractJpaNamedVersionedEntity_;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet_;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule; import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModuleType_;
import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule_; import org.eclipse.hawkbit.repository.jpa.model.JpaSoftwareModule_;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModule;
@@ -38,13 +39,13 @@ public final class SoftwareModuleSpecification {
* @return the {@link SoftwareModule} {@link Specification} * @return the {@link SoftwareModule} {@link Specification}
*/ */
public static Specification<JpaSoftwareModule> byId(final Long swModuleId) { public static Specification<JpaSoftwareModule> byId(final Long swModuleId) {
return (swRoot, query, cb) -> cb.equal(swRoot.get(JpaSoftwareModule_.id), swModuleId); return (swRoot, query, cb) -> cb.equal(swRoot.get(AbstractJpaBaseEntity_.id), swModuleId);
} }
public static Specification<JpaSoftwareModule> byAssignedToDs(final Long dsId) { public static Specification<JpaSoftwareModule> byAssignedToDs(final Long dsId) {
return (swRoot, query, cb) -> { return (swRoot, query, cb) -> {
final ListJoin<JpaSoftwareModule, JpaDistributionSet> join = swRoot.join(JpaSoftwareModule_.assignedTo); final ListJoin<JpaSoftwareModule, JpaDistributionSet> join = swRoot.join(JpaSoftwareModule_.assignedTo);
return cb.equal(join.get(JpaDistributionSet_.ID), dsId); return cb.equal(join.get(AbstractJpaBaseEntity_.ID), dsId);
}; };
} }
@@ -68,8 +69,8 @@ public final class SoftwareModuleSpecification {
*/ */
public static Specification<JpaSoftwareModule> likeNameAndVersion(final String name, final String version) { public static Specification<JpaSoftwareModule> likeNameAndVersion(final String name, final String version) {
return (smRoot, query, cb) -> cb.and( return (smRoot, query, cb) -> cb.and(
cb.like(cb.lower(smRoot.get(JpaSoftwareModule_.name)), name.toLowerCase()), cb.like(cb.lower(smRoot.get(AbstractJpaNamedEntity_.name)), name.toLowerCase()),
cb.like(cb.lower(smRoot.get(JpaSoftwareModule_.version)), version.toLowerCase())); cb.like(cb.lower(smRoot.get(AbstractJpaNamedVersionedEntity_.version)), version.toLowerCase()));
} }
/** /**
@@ -81,7 +82,7 @@ public final class SoftwareModuleSpecification {
*/ */
public static Specification<JpaSoftwareModule> equalType(final Long type) { public static Specification<JpaSoftwareModule> equalType(final Long type) {
return (smRoot, query, cb) -> cb.equal( return (smRoot, query, cb) -> cb.equal(
smRoot.get(JpaSoftwareModule_.type).get(JpaSoftwareModuleType_.id), type); smRoot.get(JpaSoftwareModule_.type).get(AbstractJpaBaseEntity_.id), type);
} }
/** /**

View File

@@ -13,10 +13,10 @@ import jakarta.persistence.criteria.Join;
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.JpaDistributionSet; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag_; import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetTag_;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet_;
import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.domain.Specification;
@@ -42,8 +42,7 @@ public final class TagSpecification {
query.distinct(true); query.distinct(true);
return criteriaBuilder.equal(tagJoin.get(JpaDistributionSet_.id), dsId); return criteriaBuilder.equal(tagJoin.get(AbstractJpaBaseEntity_.id), dsId);
}; };
} }
} }

View File

@@ -26,16 +26,12 @@ import jakarta.validation.constraints.NotNull;
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.JpaAction; import org.eclipse.hawkbit.repository.jpa.model.JpaAction;
import org.eclipse.hawkbit.repository.jpa.model.JpaAction_; import org.eclipse.hawkbit.repository.jpa.model.JpaAction_;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSetType_;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet_;
import org.eclipse.hawkbit.repository.jpa.model.JpaRolloutGroup_;
import org.eclipse.hawkbit.repository.jpa.model.JpaRollout_;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget; import org.eclipse.hawkbit.repository.jpa.model.JpaTarget;
import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag; import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag;
import org.eclipse.hawkbit.repository.jpa.model.JpaTargetTag_;
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.jpa.model.JpaTarget_; import org.eclipse.hawkbit.repository.jpa.model.JpaTarget_;
@@ -99,7 +95,7 @@ public final class TargetSpecifications {
* @return the {@link Target} {@link Specification} * @return the {@link Target} {@link Specification}
*/ */
public static Specification<JpaTarget> hasId(final Long id) { public static Specification<JpaTarget> hasId(final Long id) {
return (targetRoot, query, cb) -> cb.equal(targetRoot.get(JpaTarget_.id), id); return (targetRoot, query, cb) -> cb.equal(targetRoot.get(AbstractJpaBaseEntity_.id), id);
} }
/** /**
@@ -109,7 +105,7 @@ public final class TargetSpecifications {
* @return the {@link Target} {@link Specification} * @return the {@link Target} {@link Specification}
*/ */
public static Specification<JpaTarget> hasIdIn(final Collection<Long> ids) { public static Specification<JpaTarget> hasIdIn(final Collection<Long> ids) {
return (targetRoot, query, cb) -> targetRoot.get(JpaTarget_.id).in(ids); return (targetRoot, query, cb) -> targetRoot.get(AbstractJpaBaseEntity_.id).in(ids);
} }
/** /**
@@ -201,7 +197,7 @@ public final class TargetSpecifications {
return (targetRoot, query, cb) -> { return (targetRoot, query, cb) -> {
final String searchTextToLower = searchText.toLowerCase(); final String searchTextToLower = searchText.toLowerCase();
return cb.or(cb.like(cb.lower(targetRoot.get(JpaTarget_.controllerId)), searchTextToLower), return cb.or(cb.like(cb.lower(targetRoot.get(JpaTarget_.controllerId)), searchTextToLower),
cb.like(cb.lower(targetRoot.get(JpaTarget_.name)), searchTextToLower)); cb.like(cb.lower(targetRoot.get(AbstractJpaNamedEntity_.name)), searchTextToLower));
}; };
} }
@@ -227,8 +223,8 @@ public final class TargetSpecifications {
@NotNull final Long distributionId) { @NotNull final Long distributionId) {
return (targetRoot, query, cb) -> cb.and(targetRoot.get(JpaTarget_.controllerId).in(tIDs), return (targetRoot, query, cb) -> cb.and(targetRoot.get(JpaTarget_.controllerId).in(tIDs),
cb.or( cb.or(
cb.notEqual(targetRoot.get(JpaTarget_.assignedDistributionSet).get(JpaDistributionSet_.id), distributionId), cb.notEqual(targetRoot.get(JpaTarget_.assignedDistributionSet).get(AbstractJpaBaseEntity_.id), distributionId),
cb.isNull(targetRoot.<JpaDistributionSet> get(JpaTarget_.assignedDistributionSet)))); cb.isNull(targetRoot.get(JpaTarget_.assignedDistributionSet))));
} }
/** /**
@@ -241,7 +237,7 @@ public final class TargetSpecifications {
public static Specification<JpaTarget> hasTagName(final String tagName) { public static Specification<JpaTarget> hasTagName(final String tagName) {
return (targetRoot, query, cb) -> { return (targetRoot, query, cb) -> {
final SetJoin<JpaTarget, JpaTargetTag> join = targetRoot.join(JpaTarget_.tags); final SetJoin<JpaTarget, JpaTargetTag> join = targetRoot.join(JpaTarget_.tags);
return cb.equal(join.get(JpaTargetTag_.name), tagName); return cb.equal(join.get(AbstractJpaNamedEntity_.name), tagName);
}; };
} }
@@ -270,7 +266,7 @@ public final class TargetSpecifications {
*/ */
public static Specification<JpaTarget> hasAssignedDistributionSet(final Long distributionSetId) { public static Specification<JpaTarget> hasAssignedDistributionSet(final Long distributionSetId) {
return (targetRoot, query, cb) -> cb.equal( return (targetRoot, query, cb) -> cb.equal(
targetRoot.get(JpaTarget_.assignedDistributionSet).get(JpaDistributionSet_.id), distributionSetId); targetRoot.get(JpaTarget_.assignedDistributionSet).get(AbstractJpaBaseEntity_.id), distributionSetId);
} }
/** /**
@@ -283,8 +279,8 @@ public final class TargetSpecifications {
public static Specification<JpaTarget> hasNotDistributionSetInActions(final Long distributionSetId) { public static Specification<JpaTarget> hasNotDistributionSetInActions(final Long distributionSetId) {
return (targetRoot, query, cb) -> { return (targetRoot, query, cb) -> {
final ListJoin<JpaTarget, JpaAction> actionsJoin = targetRoot.join(JpaTarget_.actions, JoinType.LEFT); final ListJoin<JpaTarget, JpaAction> actionsJoin = targetRoot.join(JpaTarget_.actions, JoinType.LEFT);
actionsJoin.on(cb.equal(actionsJoin.get(JpaAction_.distributionSet).get(JpaDistributionSet_.id), distributionSetId)); actionsJoin.on(cb.equal(actionsJoin.get(JpaAction_.distributionSet).get(AbstractJpaBaseEntity_.id), distributionSetId));
return cb.isNull(actionsJoin.get(JpaAction_.id)); return cb.isNull(actionsJoin.get(AbstractJpaBaseEntity_.id));
}; };
} }
@@ -323,9 +319,9 @@ public final class TargetSpecifications {
final Subquery<Long> compatibilitySubQuery = query.subquery(Long.class); final Subquery<Long> compatibilitySubQuery = query.subquery(Long.class);
final Root<JpaTarget> subQueryTargetRoot = compatibilitySubQuery.from(JpaTarget.class); final Root<JpaTarget> subQueryTargetRoot = compatibilitySubQuery.from(JpaTarget.class);
compatibilitySubQuery.select(subQueryTargetRoot.get(JpaTarget_.id)) compatibilitySubQuery.select(subQueryTargetRoot.get(AbstractJpaBaseEntity_.id))
.where(cb.and( .where(cb.and(
cb.equal(targetRoot.get(JpaTarget_.id), subQueryTargetRoot.get(JpaTarget_.id)), cb.equal(targetRoot.get(AbstractJpaBaseEntity_.id), subQueryTargetRoot.get(AbstractJpaBaseEntity_.id)),
cb.equal(getDsTypeIdPath(subQueryTargetRoot), distributionSetTypeId))); cb.equal(getDsTypeIdPath(subQueryTargetRoot), distributionSetTypeId)));
return cb.and(targetTypeNotNull, cb.not(cb.exists(compatibilitySubQuery))); return cb.and(targetTypeNotNull, cb.not(cb.exists(compatibilitySubQuery)));
@@ -343,7 +339,7 @@ public final class TargetSpecifications {
return (targetRoot, query, cb) -> { return (targetRoot, query, cb) -> {
final ListJoin<JpaTarget, RolloutTargetGroup> targetGroupJoin = targetRoot final ListJoin<JpaTarget, RolloutTargetGroup> targetGroupJoin = targetRoot
.join(JpaTarget_.rolloutTargetGroup); .join(JpaTarget_.rolloutTargetGroup);
return cb.equal(targetGroupJoin.get(RolloutTargetGroup_.rolloutGroup).get(JpaRolloutGroup_.id), group); return cb.equal(targetGroupJoin.get(RolloutTargetGroup_.rolloutGroup).get(AbstractJpaBaseEntity_.id), group);
}; };
} }
@@ -357,7 +353,7 @@ public final class TargetSpecifications {
public static Specification<JpaTarget> isInActionRolloutGroup(final Long group) { public static Specification<JpaTarget> isInActionRolloutGroup(final Long group) {
return (targetRoot, query, cb) -> { return (targetRoot, query, cb) -> {
final ListJoin<JpaTarget, JpaAction> targetActionJoin = targetRoot.join(JpaTarget_.actions); final ListJoin<JpaTarget, JpaAction> targetActionJoin = targetRoot.join(JpaTarget_.actions);
return cb.equal(targetActionJoin.get(JpaAction_.rolloutGroup).get(JpaRolloutGroup_.id), group); return cb.equal(targetActionJoin.get(JpaAction_.rolloutGroup).get(AbstractJpaBaseEntity_.id), group);
}; };
} }
@@ -373,7 +369,7 @@ public final class TargetSpecifications {
final ListJoin<JpaTarget, RolloutTargetGroup> rolloutTargetJoin = targetRoot final ListJoin<JpaTarget, RolloutTargetGroup> rolloutTargetJoin = targetRoot
.join(JpaTarget_.rolloutTargetGroup, JoinType.LEFT); .join(JpaTarget_.rolloutTargetGroup, JoinType.LEFT);
rolloutTargetJoin.on(rolloutTargetJoin.get(RolloutTargetGroup_.rolloutGroup) rolloutTargetJoin.on(rolloutTargetJoin.get(RolloutTargetGroup_.rolloutGroup)
.get(JpaRolloutGroup_.id).in(groups)); .get(AbstractJpaBaseEntity_.id).in(groups));
return cb.isNull(rolloutTargetJoin.get(RolloutTargetGroup_.target)); return cb.isNull(rolloutTargetJoin.get(RolloutTargetGroup_.target));
}; };
} }
@@ -389,7 +385,7 @@ public final class TargetSpecifications {
final ListJoin<JpaTarget, RolloutTargetGroup> rolloutTargetJoin = targetRoot final ListJoin<JpaTarget, RolloutTargetGroup> rolloutTargetJoin = targetRoot
.join(JpaTarget_.rolloutTargetGroup, JoinType.LEFT); .join(JpaTarget_.rolloutTargetGroup, JoinType.LEFT);
rolloutTargetJoin.on(cb.ge(rolloutTargetJoin.get(RolloutTargetGroup_.rolloutGroup) rolloutTargetJoin.on(cb.ge(rolloutTargetJoin.get(RolloutTargetGroup_.rolloutGroup)
.get(JpaRolloutGroup_.id), groupId)); .get(AbstractJpaBaseEntity_.id), groupId));
return cb.isNull(rolloutTargetJoin.get(RolloutTargetGroup_.target)); return cb.isNull(rolloutTargetJoin.get(RolloutTargetGroup_.target));
}; };
} }
@@ -406,12 +402,12 @@ public final class TargetSpecifications {
final ListJoin<JpaTarget, RolloutTargetGroup> rolloutTargetJoin = targetRoot final ListJoin<JpaTarget, RolloutTargetGroup> rolloutTargetJoin = targetRoot
.join(JpaTarget_.rolloutTargetGroup, JoinType.INNER); .join(JpaTarget_.rolloutTargetGroup, JoinType.INNER);
rolloutTargetJoin.on( rolloutTargetJoin.on(
cb.equal(rolloutTargetJoin.get(RolloutTargetGroup_.rolloutGroup).get(JpaRolloutGroup_.id), group)); cb.equal(rolloutTargetJoin.get(RolloutTargetGroup_.rolloutGroup).get(AbstractJpaBaseEntity_.id), group));
final ListJoin<JpaTarget, JpaAction> actionsJoin = targetRoot.join(JpaTarget_.actions, JoinType.LEFT); final ListJoin<JpaTarget, JpaAction> actionsJoin = targetRoot.join(JpaTarget_.actions, JoinType.LEFT);
actionsJoin.on(cb.equal(actionsJoin.get(JpaAction_.rolloutGroup).get(JpaRolloutGroup_.id), group)); actionsJoin.on(cb.equal(actionsJoin.get(JpaAction_.rolloutGroup).get(AbstractJpaBaseEntity_.id), group));
return cb.isNull(actionsJoin.get(JpaAction_.id)); return cb.isNull(actionsJoin.get(AbstractJpaBaseEntity_.id));
}; };
} }
@@ -424,7 +420,7 @@ public final class TargetSpecifications {
*/ */
public static Specification<JpaTarget> hasInstalledDistributionSet(final Long distributionSetId) { public static Specification<JpaTarget> hasInstalledDistributionSet(final Long distributionSetId) {
return (targetRoot, query, cb) -> cb.equal( return (targetRoot, query, cb) -> cb.equal(
targetRoot.get(JpaTarget_.installedDistributionSet).get(JpaDistributionSet_.id), distributionSetId); targetRoot.get(JpaTarget_.installedDistributionSet).get(AbstractJpaBaseEntity_.id), distributionSetId);
} }
/** /**
@@ -437,7 +433,7 @@ public final class TargetSpecifications {
return (targetRoot, query, cb) -> { return (targetRoot, query, cb) -> {
final SetJoin<JpaTarget, JpaTargetTag> tags = targetRoot.join(JpaTarget_.tags, JoinType.LEFT); final SetJoin<JpaTarget, JpaTargetTag> tags = targetRoot.join(JpaTarget_.tags, JoinType.LEFT);
return cb.equal(tags.get(JpaTargetTag_.id), tagId); return cb.equal(tags.get(AbstractJpaBaseEntity_.id), tagId);
}; };
} }
@@ -448,8 +444,7 @@ public final class TargetSpecifications {
* @return the {@link Target} {@link Specification} * @return the {@link Target} {@link Specification}
*/ */
public static Specification<JpaTarget> hasTargetType(final long typeId) { public static Specification<JpaTarget> hasTargetType(final long typeId) {
return (targetRoot, query, cb) -> cb.equal(targetRoot.get(JpaTarget_.targetType).get(JpaTargetType_.id), return (targetRoot, query, cb) -> cb.equal(targetRoot.get(JpaTarget_.targetType).get(AbstractJpaBaseEntity_.id), typeId);
typeId);
} }
/** /**
@@ -471,7 +466,7 @@ public final class TargetSpecifications {
*/ */
public static Specification<JpaTarget> hasTargetTypeNot(final Long typeId) { public static Specification<JpaTarget> hasTargetTypeNot(final Long typeId) {
return (targetRoot, query, cb) -> cb.or(getTargetTypeIsNullPredicate(targetRoot), return (targetRoot, query, cb) -> cb.or(getTargetTypeIsNullPredicate(targetRoot),
cb.notEqual(targetRoot.get(JpaTarget_.targetType).get(JpaTargetType_.id), typeId)); cb.notEqual(targetRoot.get(JpaTarget_.targetType).get(AbstractJpaBaseEntity_.id), typeId));
} }
public static Specification<JpaTarget> failedActionsForRollout(final String rolloutId) { public static Specification<JpaTarget> failedActionsForRollout(final String rolloutId) {
@@ -500,28 +495,28 @@ public final class TargetSpecifications {
cb.gt(actionsJoin.get(JpaAction_.weight), weight), cb.gt(actionsJoin.get(JpaAction_.weight), weight),
cb.and( cb.and(
cb.equal(actionsJoin.get(JpaAction_.weight), weight), cb.equal(actionsJoin.get(JpaAction_.weight), weight),
cb.ge(actionsJoin.get(JpaAction_.ROLLOUT).get(JpaRollout_.ID), rolloutId)))); cb.ge(actionsJoin.get(JpaAction_.ROLLOUT).get(AbstractJpaBaseEntity_.ID), rolloutId))));
// another, but probably heavier variant // another, but probably heavier variant
// actionsJoin.on( // actionsJoin.on(
// cb.or( // cb.or(
// // in rollout // // in rollout
// cb.equal(actionsJoin.get(JpaAction_.ROLLOUT).get(JpaRollout_.ID), rolloutId), // cb.equal(actionsJoin.get(JpaAction_.ROLLOUT).get(AbstractJpaBaseEntity_.ID), rolloutId),
// // or, in newer rollout with greater or equal weight // // or, in newer rollout with greater or equal weight
// cb.and( // cb.and(
// cb.gt(actionsJoin.get(JpaAction_.ROLLOUT).get(JpaRollout_.ID), rolloutId), // cb.gt(actionsJoin.get(JpaAction_.ROLLOUT).get(AbstractJpaBaseEntity_.ID), rolloutId),
// cb.ge(actionsJoin.get(JpaAction_.weight), weight)), // cb.ge(actionsJoin.get(JpaAction_.weight), weight)),
// // or, in older with greater status // // or, in older with greater status
// cb.and( // cb.and(
// cb.lt(actionsJoin.get(JpaAction_.ROLLOUT).get(JpaRollout_.ID), rolloutId), // cb.lt(actionsJoin.get(JpaAction_.ROLLOUT).get(AbstractJpaBaseEntity_.ID), rolloutId),
// cb.gt(actionsJoin.get(JpaAction_.weight), weight)))); // cb.gt(actionsJoin.get(JpaAction_.weight), weight))));
return cb.isNull(actionsJoin.get(JpaAction_.id)); return cb.isNull(actionsJoin.get(AbstractJpaBaseEntity_.id));
}; };
} }
private static Predicate getHasTagsPredicate(final Root<JpaTarget> targetRoot, final CriteriaBuilder cb, private static Predicate getHasTagsPredicate(final Root<JpaTarget> targetRoot, final CriteriaBuilder cb,
final Boolean selectTargetWithNoTag, final String[] tagNames) { final Boolean selectTargetWithNoTag, final String[] tagNames) {
final SetJoin<JpaTarget, JpaTargetTag> tags = targetRoot.join(JpaTarget_.tags, JoinType.LEFT); final SetJoin<JpaTarget, JpaTargetTag> tags = targetRoot.join(JpaTarget_.tags, JoinType.LEFT);
final Path<String> exp = tags.get(JpaTargetTag_.name); final Path<String> exp = tags.get(AbstractJpaNamedEntity_.name);
final List<Predicate> hasTagsPredicates = new ArrayList<>(); final List<Predicate> hasTagsPredicates = new ArrayList<>();
if (isNoTagActive(selectTargetWithNoTag)) { if (isNoTagActive(selectTargetWithNoTag)) {
@@ -549,6 +544,6 @@ public final class TargetSpecifications {
private static Path<Long> getDsTypeIdPath(final Root<JpaTarget> root) { private static Path<Long> getDsTypeIdPath(final Root<JpaTarget> root) {
final Join<JpaTarget, JpaTargetType> targetTypeJoin = root.join(JpaTarget_.targetType, JoinType.LEFT); final Join<JpaTarget, JpaTargetType> targetTypeJoin = root.join(JpaTarget_.targetType, JoinType.LEFT);
return targetTypeJoin.join(JpaTargetType_.distributionSetTypes, JoinType.LEFT).get(JpaDistributionSetType_.id); return targetTypeJoin.join(JpaTargetType_.distributionSetTypes, JoinType.LEFT).get(AbstractJpaBaseEntity_.id);
} }
} }

View File

@@ -31,6 +31,7 @@ import org.springframework.util.ObjectUtils;
@NoArgsConstructor(access = AccessLevel.PRIVATE) @NoArgsConstructor(access = AccessLevel.PRIVATE)
public class StatisticsUtils { public class StatisticsUtils {
@SuppressWarnings("java:S5164") // intentionally don't call remove. should always keep the last reported
private static final ThreadLocal<Map<String, Double>> LAST_COUNTERS = ThreadLocal.withInitial(MapUFToString::new); private static final ThreadLocal<Map<String, Double>> LAST_COUNTERS = ThreadLocal.withInitial(MapUFToString::new);
// for test purposes we may want to flush the statistics and to get diff from the last get int THIS thread // for test purposes we may want to flush the statistics and to get diff from the last get int THIS thread

View File

@@ -20,17 +20,17 @@ import org.junit.jupiter.api.Test;
*/ */
@Feature("Component Tests - Repository") @Feature("Component Tests - Repository")
@Story("Test TargetCreatedEvent, TargetUpdatedEvent and CancelTargetAssignmentEvent") @Story("Test TargetCreatedEvent, TargetUpdatedEvent and CancelTargetAssignmentEvent")
public class TargetEventTest extends AbstractRemoteEntityEventTest<Target> { class TargetEventTest extends AbstractRemoteEntityEventTest<Target> {
@Test @Test
@Description("Verifies that the target entity reloading by remote created event works") @Description("Verifies that the target entity reloading by remote created event works")
public void testTargetCreatedEvent() { void testTargetCreatedEvent() {
assertAndCreateRemoteEvent(TargetCreatedEvent.class); assertAndCreateRemoteEvent(TargetCreatedEvent.class);
} }
@Test @Test
@Description("Verifies that the target entity reloading by remote updated event works") @Description("Verifies that the target entity reloading by remote updated event works")
public void testTargetUpdatedEvent() { void testTargetUpdatedEvent() {
assertAndCreateRemoteEvent(TargetUpdatedEvent.class); assertAndCreateRemoteEvent(TargetUpdatedEvent.class);
} }

View File

@@ -20,17 +20,17 @@ import org.junit.jupiter.api.Test;
*/ */
@Feature("Component Tests - Repository") @Feature("Component Tests - Repository")
@Story("Test TargetTagCreatedEvent and TargetTagUpdateEvent") @Story("Test TargetTagCreatedEvent and TargetTagUpdateEvent")
public class TargetTagEventTest extends AbstractRemoteEntityEventTest<TargetTag> { class TargetTagEventTest extends AbstractRemoteEntityEventTest<TargetTag> {
@Test @Test
@Description("Verifies that the target tag entity reloading by remote created event works") @Description("Verifies that the target tag entity reloading by remote created event works")
public void testTargetTagCreatedEvent() { void testTargetTagCreatedEvent() {
assertAndCreateRemoteEvent(TargetTagCreatedEvent.class); assertAndCreateRemoteEvent(TargetTagCreatedEvent.class);
} }
@Test @Test
@Description("Verifies that the target tag entity reloading by remote updated event works") @Description("Verifies that the target tag entity reloading by remote updated event works")
public void testTargetTagUpdateEventt() { void testTargetTagUpdateEventt() {
assertAndCreateRemoteEvent(TargetTagUpdatedEvent.class); assertAndCreateRemoteEvent(TargetTagUpdatedEvent.class);
} }

View File

@@ -24,7 +24,7 @@ import org.junit.jupiter.api.Test;
@Feature("SecurityTests - SoftwareManagement") @Feature("SecurityTests - SoftwareManagement")
@Story("SecurityTests SoftwareManagement") @Story("SecurityTests SoftwareManagement")
public class SoftwareManagementSecurityTest class SoftwareManagementSecurityTest
extends AbstractRepositoryManagementSecurityTest<SoftwareModule, SoftwareModuleCreate, SoftwareModuleUpdate> { extends AbstractRepositoryManagementSecurityTest<SoftwareModule, SoftwareModuleCreate, SoftwareModuleUpdate> {
@Override @Override

View File

@@ -25,7 +25,6 @@ import java.util.Set;
import io.qameta.allure.Description; 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.apache.commons.lang3.RandomUtils;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleMetadataCreate; import org.eclipse.hawkbit.repository.builder.SoftwareModuleMetadataCreate;
import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleCreatedEvent; import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleCreatedEvent;
import org.eclipse.hawkbit.repository.exception.AssignmentQuotaExceededException; import org.eclipse.hawkbit.repository.exception.AssignmentQuotaExceededException;
@@ -358,7 +357,7 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
// Init artifact binary data, target and DistributionSets // Init artifact binary data, target and DistributionSets
final int artifactSize = 1024; final int artifactSize = 1024;
final byte[] source = RandomUtils.nextBytes(artifactSize); final byte[] source = randomBytes(artifactSize);
// [STEP1]: Create SoftwareModuleX and add a new ArtifactX // [STEP1]: Create SoftwareModuleX and add a new ArtifactX
SoftwareModule moduleX = createSoftwareModuleWithArtifacts(osType, "modulex", "v1.0", 0); SoftwareModule moduleX = createSoftwareModuleWithArtifacts(osType, "modulex", "v1.0", 0);
@@ -403,7 +402,7 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
void deleteMultipleSoftwareModulesWhichShareAnArtifact() { void deleteMultipleSoftwareModulesWhichShareAnArtifact() {
// Init artifact binary data, target and DistributionSets // Init artifact binary data, target and DistributionSets
final int artifactSize = 1024; final int artifactSize = 1024;
final byte[] source = RandomUtils.nextBytes(artifactSize); final byte[] source = randomBytes(artifactSize);
final Target target = testdataFactory.createTarget(); final Target target = testdataFactory.createTarget();
// [STEP1]: Create SoftwareModuleX and add a new ArtifactX // [STEP1]: Create SoftwareModuleX and add a new ArtifactX
@@ -533,9 +532,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
} }
// quota exceeded // quota exceeded
final SoftwareModuleMetadataCreate metadata = entityFactory.softwareModuleMetadata().create(module.getId())
.key("k" + maxMetaData).value("v" + maxMetaData);
assertThatExceptionOfType(AssignmentQuotaExceededException.class) assertThatExceptionOfType(AssignmentQuotaExceededException.class)
.isThrownBy(() -> softwareModuleManagement.updateMetaData(entityFactory.softwareModuleMetadata() .isThrownBy(() -> softwareModuleManagement.updateMetaData(metadata));
.create(module.getId()).key("k" + maxMetaData).value("v" + maxMetaData)));
// add multiple meta data entries at once // add multiple meta data entries at once
final SoftwareModule module2 = testdataFactory.createSoftwareModuleApp("m2"); final SoftwareModule module2 = testdataFactory.createSoftwareModuleApp("m2");
@@ -574,12 +574,12 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
final String knownValue1 = "myKnownValue1"; final String knownValue1 = "myKnownValue1";
final SoftwareModule ah = testdataFactory.createSoftwareModuleApp(); final SoftwareModule ah = testdataFactory.createSoftwareModuleApp();
softwareModuleManagement.updateMetaData(entityFactory.softwareModuleMetadata().create(ah.getId()).key(knownKey1) final SoftwareModuleMetadataCreate metadata = entityFactory.softwareModuleMetadata()
.value(knownValue1).targetVisible(true)); .create(ah.getId()).key(knownKey1).value(knownValue1).targetVisible(true);
softwareModuleManagement.updateMetaData(metadata);
assertThatExceptionOfType(EntityAlreadyExistsException.class) assertThatExceptionOfType(EntityAlreadyExistsException.class)
.isThrownBy(() -> softwareModuleManagement.updateMetaData(entityFactory.softwareModuleMetadata() .isThrownBy(() -> softwareModuleManagement.updateMetaData(metadata))
.create(ah.getId()).key(knownKey1).value(knownValue1).targetVisible(true)))
.withMessageContaining("Metadata").withMessageContaining(knownKey1); .withMessageContaining("Metadata").withMessageContaining(knownKey1);
final String knownKey2 = "myKnownKey2"; final String knownKey2 = "myKnownKey2";
@@ -587,9 +587,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
softwareModuleManagement.updateMetaData(entityFactory.softwareModuleMetadata().create(ah.getId()).key(knownKey2) softwareModuleManagement.updateMetaData(entityFactory.softwareModuleMetadata().create(ah.getId()).key(knownKey2)
.value(knownValue1).targetVisible(false)); .value(knownValue1).targetVisible(false));
final SoftwareModuleMetadataCreate metadata2 = entityFactory.softwareModuleMetadata().create(ah.getId())
.key(knownKey2).value(knownValue1).targetVisible(true);
assertThatExceptionOfType(EntityAlreadyExistsException.class) assertThatExceptionOfType(EntityAlreadyExistsException.class)
.isThrownBy(() -> softwareModuleManagement.updateMetaData(entityFactory.softwareModuleMetadata() .isThrownBy(() -> softwareModuleManagement.updateMetaData(metadata2))
.create(ah.getId()).key(knownKey2).value(knownValue1).targetVisible(true)))
.withMessageContaining("Metadata").withMessageContaining(knownKey2); .withMessageContaining("Metadata").withMessageContaining(knownKey2);
} }
@@ -746,36 +747,32 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Artifacts of a locked SM can't be modified. Expected behaviour is to throw an exception and to do not modify them.") @Description("Artifacts of a locked SM can't be modified. Expected behaviour is to throw an exception and to do not modify them.")
void lockSoftwareModuleApplied() { void lockSoftwareModuleApplied() {
final SoftwareModule softwareModule = testdataFactory.createSoftwareModule("sm-1"); final Long softwareModuleId = testdataFactory.createSoftwareModule("sm-1").getId();
artifactManagement.create( artifactManagement.create(
new ArtifactUpload(new ByteArrayInputStream(new byte[] { 1 }), softwareModule.getId(), new ArtifactUpload(new ByteArrayInputStream(new byte[] { 1 }), softwareModuleId, "artifact1", false, 1));
"artifact1", false, 1)); final int artifactCount = softwareModuleManagement.get(softwareModuleId).get().getArtifacts().size();
final int artifactCount = softwareModuleManagement.get(softwareModule.getId()).get().getArtifacts().size(); assertThat(artifactCount).isNotZero();
assertThat(artifactCount).isNotEqualTo(0); softwareModuleManagement.lock(softwareModuleId);
softwareModuleManagement.lock(softwareModule.getId()); assertThat(softwareModuleManagement.get(softwareModuleId).map(SoftwareModule::isLocked).orElse(false))
assertThat(
softwareModuleManagement.get(softwareModule.getId()).map(SoftwareModule::isLocked).orElse(false))
.isTrue(); .isTrue();
// try add // try add
final ArtifactUpload artifactUpload = new ArtifactUpload(new ByteArrayInputStream(new byte[] { 2 }), softwareModuleId, "artifact2", false, 1);
assertThatExceptionOfType(LockedException.class) assertThatExceptionOfType(LockedException.class)
.as("Attempt to modify a locked SM artifacts should throw an exception") .as("Attempt to modify a locked SM artifacts should throw an exception")
.isThrownBy(() -> artifactManagement.create( .isThrownBy(() -> artifactManagement.create(artifactUpload));
new ArtifactUpload(new ByteArrayInputStream(new byte[] { 2 }), softwareModule.getId(), assertThat(softwareModuleManagement.get(softwareModuleId).get().getArtifacts())
"artifact2", false, 1)));
assertThat(softwareModuleManagement.get(softwareModule.getId()).get().getArtifacts().size())
.as("Artifacts shall not be added to a locked SM.") .as("Artifacts shall not be added to a locked SM.")
.isEqualTo(artifactCount); .hasSize(artifactCount);
// try remove // try remove
final long artifactId = softwareModuleManagement.get(softwareModule.getId()).get() final long artifactId = softwareModuleManagement.get(softwareModuleId).get().getArtifacts().stream().findFirst().get().getId();
.getArtifacts().stream().findFirst().get().getId();
assertThatExceptionOfType(LockedException.class) assertThatExceptionOfType(LockedException.class)
.as("Attempt to modify a locked SM artifacts should throw an exception") .as("Attempt to modify a locked SM artifacts should throw an exception")
.isThrownBy(() -> artifactManagement.delete(artifactId)); .isThrownBy(() -> artifactManagement.delete(artifactId));
assertThat(softwareModuleManagement.get(softwareModule.getId()).get().getArtifacts().size()) assertThat(softwareModuleManagement.get(softwareModuleId).get().getArtifacts())
.as("Artifact shall not be removed from a locked SM.") .as("Artifact shall not be removed from a locked SM.")
.isEqualTo(artifactCount); .hasSize(artifactCount);
assertThat(artifactManagement.get(artifactId)) assertThat(artifactManagement.get(artifactId))
.as("Artifact shall not be removed if belongs to a locked SM.") .as("Artifact shall not be removed if belongs to a locked SM.")
.isPresent(); .isPresent();
@@ -786,7 +783,7 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
void lockedContainingDistributionSetApplied() { void lockedContainingDistributionSetApplied() {
final DistributionSet distributionSet = testdataFactory.createDistributionSet("ds-1"); final DistributionSet distributionSet = testdataFactory.createDistributionSet("ds-1");
final List<SoftwareModule> modules = distributionSet.getModules().stream().toList(); final List<SoftwareModule> modules = distributionSet.getModules().stream().toList();
assertThat(modules.size()).isGreaterThan(1); assertThat(modules).hasSizeGreaterThan(1);
// try delete while DS is not locked // try delete while DS is not locked
softwareModuleManagement.delete(modules.get(0).getId()); softwareModuleManagement.delete(modules.get(0).getId());
@@ -797,9 +794,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
.isTrue(); .isTrue();
// try delete SM of a locked DS // try delete SM of a locked DS
final Long moduleId = modules.get(1).getId();
assertThatExceptionOfType(LockedException.class) assertThatExceptionOfType(LockedException.class)
.as("Attempt to delete a software module of a locked DS should throw an exception") .as("Attempt to delete a software module of a locked DS should throw an exception")
.isThrownBy(() -> softwareModuleManagement.delete(modules.get(1).getId())); .isThrownBy(() -> softwareModuleManagement.delete(moduleId));
} }
private Action assignSet(final JpaTarget target, final JpaDistributionSet ds) { private Action assignSet(final JpaTarget target, final JpaDistributionSet ds) {
@@ -817,7 +815,6 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
cb.equal(root.get(JpaAction_.target).get(JpaTarget_.id), target.getId()), cb.equal(root.get(JpaAction_.target).get(JpaTarget_.id), target.getId()),
cb.equal(root.get(JpaAction_.distributionSet).get(JpaDistributionSet_.id), ds.getId())), cb.equal(root.get(JpaAction_.distributionSet).get(JpaDistributionSet_.id), ds.getId())),
PAGE).getContent().get(0); PAGE).getContent().get(0);
;
assertThat(action).isNotNull(); assertThat(action).isNotNull();
return action; return action;
} }

View File

@@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test;
@Feature("SecurityTests - SoftwareModuleTypeManagement") @Feature("SecurityTests - SoftwareModuleTypeManagement")
@Story("SecurityTests SoftwareModuleTypeManagement") @Story("SecurityTests SoftwareModuleTypeManagement")
public class SoftwareModuleTypeManagementSecurityTest class SoftwareModuleTypeManagementSecurityTest
extends AbstractRepositoryManagementSecurityTest<SoftwareModuleType, SoftwareModuleTypeCreate, SoftwareModuleTypeUpdate> { extends AbstractRepositoryManagementSecurityTest<SoftwareModuleType, SoftwareModuleTypeCreate, SoftwareModuleTypeUpdate> {
@Override @Override

View File

@@ -10,7 +10,7 @@
package org.eclipse.hawkbit.repository.jpa.management; package org.eclipse.hawkbit.repository.jpa.management;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@@ -32,13 +32,13 @@ import org.junit.jupiter.api.Test;
@Feature("Component Tests - Repository") @Feature("Component Tests - Repository")
@Story("Software Module Management") @Story("Software Module Management")
public class SoftwareModuleTypeManagementTest extends AbstractJpaIntegrationTest { class SoftwareModuleTypeManagementTest 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 = SoftwareModuleCreatedEvent.class, count = 0) }) @ExpectEvents({ @Expect(type = SoftwareModuleCreatedEvent.class, count = 0) })
public void nonExistingEntityAccessReturnsNotPresent() { void nonExistingEntityAccessReturnsNotPresent() {
assertThat(softwareModuleTypeManagement.get(NOT_EXIST_IDL)).isNotPresent(); assertThat(softwareModuleTypeManagement.get(NOT_EXIST_IDL)).isNotPresent();
assertThat(softwareModuleTypeManagement.findByKey(NOT_EXIST_ID)).isNotPresent(); assertThat(softwareModuleTypeManagement.findByKey(NOT_EXIST_ID)).isNotPresent();
@@ -49,7 +49,7 @@ public class SoftwareModuleTypeManagementTest extends AbstractJpaIntegrationTest
@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({ @Expect(type = SoftwareModuleCreatedEvent.class, count = 0) }) @ExpectEvents({ @Expect(type = SoftwareModuleCreatedEvent.class, count = 0) })
public void entityQueriesReferringToNotExistingEntitiesThrowsException() { void entityQueriesReferringToNotExistingEntitiesThrowsException() {
verifyThrownExceptionBy(() -> softwareModuleTypeManagement.delete(NOT_EXIST_IDL), "SoftwareModuleType"); verifyThrownExceptionBy(() -> softwareModuleTypeManagement.delete(NOT_EXIST_IDL), "SoftwareModuleType");
verifyThrownExceptionBy( verifyThrownExceptionBy(
@@ -59,7 +59,7 @@ public class SoftwareModuleTypeManagementTest extends AbstractJpaIntegrationTest
@Test @Test
@Description("Calling update without changing fields results in no recorded change in the repository including unchanged audit fields.") @Description("Calling update without changing fields results in no recorded change in the repository including unchanged audit fields.")
public void updateNothingResultsInUnchangedRepositoryForType() { void updateNothingResultsInUnchangedRepositoryForType() {
final SoftwareModuleType created = softwareModuleTypeManagement final SoftwareModuleType created = softwareModuleTypeManagement
.create(entityFactory.softwareModuleType().create().key("test-key").name("test-name")); .create(entityFactory.softwareModuleType().create().key("test-key").name("test-name"));
@@ -73,7 +73,7 @@ public class SoftwareModuleTypeManagementTest extends AbstractJpaIntegrationTest
@Test @Test
@Description("Calling update for changed fields results in change in the repository.") @Description("Calling update for changed fields results in change in the repository.")
public void updateSoftwareModuleTypeFieldsToNewValue() { void updateSoftwareModuleTypeFieldsToNewValue() {
final SoftwareModuleType created = softwareModuleTypeManagement final SoftwareModuleType created = softwareModuleTypeManagement
.create(entityFactory.softwareModuleType().create().key("test-key").name("test-name")); .create(entityFactory.softwareModuleType().create().key("test-key").name("test-name"));
@@ -88,23 +88,19 @@ public 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.")
public void createModuleTypesCallFailsForExistingTypes() { void _for() {
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"));
softwareModuleTypeManagement.create(created); softwareModuleTypeManagement.create(created);
try { assertThatExceptionOfType(EntityAlreadyExistsException.class)
softwareModuleTypeManagement.create(created); .as("should not have worked as module type already exists")
fail("Should not have worked as module already exists."); .isThrownBy(() -> softwareModuleTypeManagement.create(created));
} catch (final EntityAlreadyExistsException e) {
}
} }
@Test @Test
@Description("Tests the successfull deletion of software module types. Both unused (hard delete) and used ones (soft delete).") @Description("Tests the successfull deletion of software module types. Both unused (hard delete) and used ones (soft delete).")
public void deleteAssignedAndUnassignedSoftwareModuleTypes() { void deleteAssignedAndUnassignedSoftwareModuleTypes() {
assertThat(softwareModuleTypeManagement.findAll(PAGE)).hasSize(3).contains(osType, runtimeType, appType); assertThat(softwareModuleTypeManagement.findAll(PAGE)).hasSize(3).contains(osType, runtimeType, appType);
SoftwareModuleType type = softwareModuleTypeManagement SoftwareModuleType type = softwareModuleTypeManagement
@@ -140,64 +136,56 @@ public class SoftwareModuleTypeManagementTest extends AbstractJpaIntegrationTest
@Test @Test
@Description("Checks that software module typeis found based on given name.") @Description("Checks that software module typeis found based on given name.")
public void findSoftwareModuleTypeByName() { void findSoftwareModuleTypeByName() {
testdataFactory.createSoftwareModuleOs(); testdataFactory.createSoftwareModuleOs();
final SoftwareModuleType found = softwareModuleTypeManagement final SoftwareModuleType found = softwareModuleTypeManagement
.create(entityFactory.softwareModuleType().create().key("thetype").name("thename")); .create(entityFactory.softwareModuleType().create().key("thetype").name("thename"));
softwareModuleTypeManagement softwareModuleTypeManagement
.create(entityFactory.softwareModuleType().create().key("thetype2").name("anothername")); .create(entityFactory.softwareModuleType().create().key("thetype2").name("anothername"));
assertThat(softwareModuleTypeManagement.findByName("thename").get()).as("Type with given name").isEqualTo(found); assertThat(softwareModuleTypeManagement.findByName("thename")).as("Type with given name").contains(found);
} }
@Test @Test
@Description("Verifies that it is not possible to create a type that alrady exists.") @Description("Verifies that it is not possible to create a type that alrady exists.")
public void createSoftwareModuleTypeFailsWithExistingEntity() { void createSoftwareModuleTypeFailsWithExistingEntity() {
softwareModuleTypeManagement.create(entityFactory.softwareModuleType().create().key("thetype").name("thename")); final SoftwareModuleTypeCreate create = entityFactory.softwareModuleType().create().key("thetype").name("thename");
try { softwareModuleTypeManagement.create(create);
softwareModuleTypeManagement assertThatExceptionOfType(EntityAlreadyExistsException.class)
.create(entityFactory.softwareModuleType().create().key("thetype").name("thename")); .as("should not have worked as module type already exists")
fail("should not have worked as module type already exists"); .isThrownBy(() -> softwareModuleTypeManagement
} catch (final EntityAlreadyExistsException e) { .create(create));
}
} }
@Test @Test
@Description("Verifies that it is not possible to create a list of types where one already exists.") @Description("Verifies that it is not possible to create a list of types where one already exists.")
public void createSoftwareModuleTypesFailsWithExistingEntity() { void createSoftwareModuleTypesFailsWithExistingEntity() {
softwareModuleTypeManagement.create(entityFactory.softwareModuleType().create().key("thetype").name("thename")); softwareModuleTypeManagement.create(entityFactory.softwareModuleType().create().key("thetype").name("thename"));
try { final List<SoftwareModuleTypeCreate> creates = List.of(
softwareModuleTypeManagement entityFactory.softwareModuleType().create().key("thetype").name("thename"),
.create(Arrays.asList(entityFactory.softwareModuleType().create().key("thetype").name("thename"), entityFactory.softwareModuleType().create().key("anothertype").name("anothername"));
entityFactory.softwareModuleType().create().key("anothertype").name("anothername"))); assertThatExceptionOfType(EntityAlreadyExistsException.class)
fail("should not have worked as module type already exists"); .as("should not have worked as module type already exists")
} catch (final EntityAlreadyExistsException e) { .isThrownBy(() -> softwareModuleTypeManagement.create(creates));
}
} }
@Test @Test
@Description("Verifies that the creation of a softwareModuleType is failing because of invalid max assignment") @Description("Verifies that the creation of a softwareModuleType is failing because of invalid max assignment")
public void createSoftwareModuleTypesFailsWithInvalidMaxAssignment() { void createSoftwareModuleTypesFailsWithInvalidMaxAssignment() {
try { final SoftwareModuleTypeCreate create = entityFactory.softwareModuleType().create().key("type").name("name").maxAssignments(0);
softwareModuleTypeManagement assertThatExceptionOfType(ConstraintViolationException.class)
.create(entityFactory.softwareModuleType().create().key("type").name("name").maxAssignments(0)); .as("should not have worked as max assignment is invalid. Should be greater than 0")
fail("should not have worked as max assignment is invalid. Should be greater than 0."); .isThrownBy(() -> softwareModuleTypeManagement.create(create));
} catch (final ConstraintViolationException e) {
}
} }
@Test @Test
@Description("Verifies that multiple types are created as requested.") @Description("Verifies that multiple types are created as requested.")
public void createMultipleSoftwareModuleTypes() { void createMultipleSoftwareModuleTypes() {
final List<SoftwareModuleType> created = softwareModuleTypeManagement final List<SoftwareModuleType> created = softwareModuleTypeManagement
.create(Arrays.asList(entityFactory.softwareModuleType().create().key("thetype").name("thename"), .create(Arrays.asList(entityFactory.softwareModuleType().create().key("thetype").name("thename"),
entityFactory.softwareModuleType().create().key("thetype2").name("thename2"))); entityFactory.softwareModuleType().create().key("thetype2").name("thename2")));
assertThat(created.size()).as("Number of created types").isEqualTo(2); assertThat(created).as("Number of created types").hasSize(2);
assertThat(softwareModuleTypeManagement.count()).as("Number of types in repository").isEqualTo(5); assertThat(softwareModuleTypeManagement.count()).as("Number of types in repository").isEqualTo(5);
} }

View File

@@ -22,7 +22,7 @@ import org.junit.jupiter.api.Test;
@Slf4j @Slf4j
@Feature("SecurityTests - SystemManagement") @Feature("SecurityTests - SystemManagement")
@Story("SecurityTests SystemManagement") @Story("SecurityTests SystemManagement")
public class SystemManagementSecurityTest extends AbstractJpaIntegrationTest { class SystemManagementSecurityTest 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

@@ -87,7 +87,7 @@ class SystemManagementTest extends AbstractJpaIntegrationTest {
// overall data // overall data
assertThat(systemManagement.getSystemUsageStatistics().getOverallTargets()).isEqualTo(200); assertThat(systemManagement.getSystemUsageStatistics().getOverallTargets()).isEqualTo(200);
assertThat(systemManagement.getSystemUsageStatistics().getOverallActions()).isEqualTo(0); assertThat(systemManagement.getSystemUsageStatistics().getOverallActions()).isZero();
// per tenant data // per tenant data
final List<TenantUsage> tenants = systemManagement.getSystemUsageStatisticsWithTenants().getTenants(); final List<TenantUsage> tenants = systemManagement.getSystemUsageStatisticsWithTenants().getTenants();
@@ -123,7 +123,7 @@ class SystemManagementTest extends AbstractJpaIntegrationTest {
private byte[] createTestTenantsForSystemStatistics(final int tenants, final int artifactSize, final int targets, private byte[] createTestTenantsForSystemStatistics(final int tenants, final int artifactSize, final int targets,
final int updates) throws Exception { final int updates) throws Exception {
final Random randomgen = new Random(); final Random randomgen = new Random();
final byte random[] = new byte[artifactSize]; final byte[] random = new byte[artifactSize];
randomgen.nextBytes(random); randomgen.nextBytes(random);
for (int i = 0; i < tenants; i++) { for (int i = 0; i < tenants; i++) {

View File

@@ -21,7 +21,7 @@ import org.junit.jupiter.api.Test;
@Feature("SecurityTests - TargetFilterQueryManagement") @Feature("SecurityTests - TargetFilterQueryManagement")
@Story("SecurityTests TargetFilterQueryManagement") @Story("SecurityTests TargetFilterQueryManagement")
public class TargetFilterQueryManagementSecurityTest extends AbstractJpaIntegrationTest { class TargetFilterQueryManagementSecurityTest 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

@@ -61,13 +61,13 @@ import org.springframework.data.domain.Slice;
*/ */
@Feature("Component Tests - Repository") @Feature("Component Tests - Repository")
@Story("Target Filter Query Management") @Story("Target Filter Query Management")
public 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) })
public void nonExistingEntityAccessReturnsNotPresent() { void nonExistingEntityAccessReturnsNotPresent() {
assertThat(targetFilterQueryManagement.get(NOT_EXIST_IDL)).isNotPresent(); assertThat(targetFilterQueryManagement.get(NOT_EXIST_IDL)).isNotPresent();
assertThat(targetFilterQueryManagement.getByName(NOT_EXIST_ID)).isNotPresent(); assertThat(targetFilterQueryManagement.getByName(NOT_EXIST_ID)).isNotPresent();
} }
@@ -79,7 +79,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
@Expect(type = DistributionSetCreatedEvent.class, count = 1), @Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3), @Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = TargetFilterQueryCreatedEvent.class, count = 1) }) @Expect(type = TargetFilterQueryCreatedEvent.class, count = 1) })
public void entityQueriesReferringToNotExistingEntitiesThrowsException() { void entityQueriesReferringToNotExistingEntitiesThrowsException() {
final DistributionSet set = testdataFactory.createDistributionSet(); final DistributionSet set = testdataFactory.createDistributionSet();
final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement.create( final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement.create(
entityFactory.targetFilterQuery().create().name("test filter").query("name==PendingTargets001")); entityFactory.targetFilterQuery().create().name("test filter").query("name==PendingTargets001"));
@@ -110,7 +110,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
@Test @Test
@Description("Test creation of target filter query.") @Description("Test creation of target filter query.")
public void createTargetFilterQuery() { void createTargetFilterQuery() {
final String filterName = "new target filter"; final String filterName = "new target filter";
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"));
@@ -120,7 +120,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
@Test @Test
@Description("Create a target filter query with an auto-assign distribution set and a query string that addresses too many targets.") @Description("Create a target filter query with an auto-assign distribution set and a query string that addresses too many targets.")
public void createTargetFilterQueryThatExceedsQuota() { void createTargetFilterQueryThatExceedsQuota() {
// create targets // create targets
final int maxTargets = quotaManagement.getMaxTargetsPerAutoAssignment(); final int maxTargets = quotaManagement.getMaxTargetsPerAutoAssignment();
@@ -135,7 +135,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
@Test @Test
@Description("Test searching a target filter query.") @Description("Test searching a target filter query.")
public void searchTargetFilterQuery() { void searchTargetFilterQuery() {
final String filterName = "targetFilterQueryName"; final String filterName = "targetFilterQueryName";
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"));
@@ -151,7 +151,7 @@ public 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.")
public void searchTargetFilterQueryInvalidField() { void searchTargetFilterQueryInvalidField() {
Assertions.assertThatExceptionOfType(RSQLParameterUnsupportedFieldException.class) Assertions.assertThatExceptionOfType(RSQLParameterUnsupportedFieldException.class)
.isThrownBy(() -> targetFilterQueryManagement .isThrownBy(() -> targetFilterQueryManagement
.findByRsql(PageRequest.of(0, 10), "unknownField==testValue").getContent()); .findByRsql(PageRequest.of(0, 10), "unknownField==testValue").getContent());
@@ -159,7 +159,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
@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.")
public void createDuplicateTargetFilterQuery() { void createDuplicateTargetFilterQuery() {
final String filterName = "new target filter duplicate"; final String filterName = "new target filter duplicate";
targetFilterQueryManagement targetFilterQueryManagement
.create(entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001")); .create(entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001"));
@@ -172,7 +172,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
@Test @Test
@Description("Test deletion of target filter query.") @Description("Test deletion of target filter query.")
public 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().name(filterName).query("name==PendingTargets001")); .create(entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001"));
@@ -183,7 +183,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
@Test @Test
@Description("Test updation of target filter query.") @Description("Test updation of target filter query.")
public 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"));
@@ -197,7 +197,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
@Test @Test
@Description("Test assigning a distribution set for auto assignment with different action types") @Description("Test assigning a distribution set for auto assignment with different action types")
public void assignDistributionSet() { void assignDistributionSet() {
final String filterName = "target_filter_02"; final String filterName = "target_filter_02";
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"));
@@ -218,7 +218,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
@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.")
public void assignDistributionSetToTargetFilterQueryThatExceedsQuota() { void assignDistributionSetToTargetFilterQueryThatExceedsQuota() {
// create targets // create targets
final int maxTargets = quotaManagement.getMaxTargetsPerAutoAssignment(); final int maxTargets = quotaManagement.getMaxTargetsPerAutoAssignment();
@@ -239,7 +239,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
@Test @Test
@Description("Updates an existing filter query with a query string that addresses too many targets.") @Description("Updates an existing filter query with a query string that addresses too many targets.")
public void updateTargetFilterQueryWithQueryThatExceedsQuota() { void updateTargetFilterQueryWithQueryThatExceedsQuota() {
// 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");
@@ -256,7 +256,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
@Test @Test
@Description("Test removing distribution set while it has a relation to a target filter query") @Description("Test removing distribution set while it has a relation to a target filter query")
public void removeAssignDistributionSet() { void removeAssignDistributionSet() {
final String filterName = "target_filter_03"; final String filterName = "target_filter_03";
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"));
@@ -283,7 +283,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
@Test @Test
@Description("Test to implicitly remove the auto assign distribution set when the ds is soft deleted") @Description("Test to implicitly remove the auto assign distribution set when the ds is soft deleted")
public void implicitlyRemoveAssignDistributionSet() { void implicitlyRemoveAssignDistributionSet() {
final String filterName = "target_filter_03"; final String filterName = "target_filter_03";
final DistributionSet distributionSet = testdataFactory.createDistributionSet("dist_set"); final DistributionSet distributionSet = testdataFactory.createDistributionSet("dist_set");
final Target target = testdataFactory.createTarget(); final Target target = testdataFactory.createTarget();
@@ -319,7 +319,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
@Test @Test
@Description("Test finding and auto assign distribution set") @Description("Test finding and auto assign distribution set")
public void findFiltersWithDistributionSet() { void findFiltersWithDistributionSet() {
final String filterName = "d"; final String filterName = "d";
assertEquals(0L, targetFilterQueryManagement.count()); assertEquals(0L, targetFilterQueryManagement.count());
targetFilterQueryManagement.create(entityFactory.targetFilterQuery().create().name("a").query("name==*")); targetFilterQueryManagement.create(entityFactory.targetFilterQuery().create().name("a").query("name==*"));
@@ -351,7 +351,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
@Test @Test
@Description("Creating or updating a target filter query with autoassignment and no-value weight when multi assignment in enabled.") @Description("Creating or updating a target filter query with autoassignment and no-value weight when multi assignment in enabled.")
public void weightNotRequiredInMultiAssignmentMode() { void weightNotRequiredInMultiAssignmentMode() {
enableMultiAssignments(); enableMultiAssignments();
final DistributionSet ds = testdataFactory.createDistributionSet(); final DistributionSet ds = testdataFactory.createDistributionSet();
final Long filterId = targetFilterQueryManagement final Long filterId = targetFilterQueryManagement
@@ -369,7 +369,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
@Test @Test
@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.")
public 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();
@@ -387,7 +387,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
@Test @Test
@Description("Auto assignment can be removed from filter when multi assignment in enabled.") @Description("Auto assignment can be removed from filter when multi assignment in enabled.")
public void removeDsFromFilterWhenMultiAssignmentModeNotEnabled() { void removeDsFromFilterWhenMultiAssignmentModeNotEnabled() {
enableMultiAssignments(); enableMultiAssignments();
final DistributionSet ds = testdataFactory.createDistributionSet(); final DistributionSet ds = testdataFactory.createDistributionSet();
final Long filterId = targetFilterQueryManagement final Long filterId = targetFilterQueryManagement
@@ -401,7 +401,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
@Test @Test
@Description("Weight is validated and saved to the Filter.") @Description("Weight is validated and saved to the Filter.")
public void weightValidatedAndSaved() { void weightValidatedAndSaved() {
enableMultiAssignments(); enableMultiAssignments();
final DistributionSet ds = testdataFactory.createDistributionSet(); final DistributionSet ds = testdataFactory.createDistributionSet();
@@ -411,8 +411,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
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().get()) assertThat(targetFilterQueryManagement.get(filterId).get().getAutoAssignWeight()).contains(Action.WEIGHT_MAX);
.isEqualTo(Action.WEIGHT_MAX);
Assertions.assertThatExceptionOfType(ConstraintViolationException.class) Assertions.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(entityFactory.targetFilterQuery() .isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(entityFactory.targetFilterQuery()
@@ -424,13 +423,12 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
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(
entityFactory.targetFilterQuery().updateAutoAssign(filterId).ds(ds.getId()).weight(Action.WEIGHT_MIN)); entityFactory.targetFilterQuery().updateAutoAssign(filterId).ds(ds.getId()).weight(Action.WEIGHT_MIN));
assertThat(targetFilterQueryManagement.get(filterId).get().getAutoAssignWeight().get()) assertThat(targetFilterQueryManagement.get(filterId).get().getAutoAssignWeight()).contains(Action.WEIGHT_MIN);
.isEqualTo(Action.WEIGHT_MIN);
} }
@Test @Test
@Description("Verifies that an exception is thrown when trying to create a target filter with an invalidated distribution set.") @Description("Verifies that an exception is thrown when trying to create a target filter with an invalidated distribution set.")
public void createTargetFilterWithInvalidDistributionSet() { void createTargetFilterWithInvalidDistributionSet() {
final DistributionSet distributionSet = testdataFactory.createAndInvalidateDistributionSet(); final DistributionSet distributionSet = testdataFactory.createAndInvalidateDistributionSet();
assertThatExceptionOfType(InvalidDistributionSetException.class) assertThatExceptionOfType(InvalidDistributionSetException.class)
@@ -442,7 +440,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
@Test @Test
@Description("Verifies that an exception is thrown when trying to create a target filter with an incomplete distribution set.") @Description("Verifies that an exception is thrown when trying to create a target filter with an incomplete distribution set.")
public void createTargetFilterWithIncompleteDistributionSet() { void createTargetFilterWithIncompleteDistributionSet() {
final DistributionSet distributionSet = testdataFactory.createIncompleteDistributionSet(); final DistributionSet distributionSet = testdataFactory.createIncompleteDistributionSet();
assertThatExceptionOfType(IncompleteDistributionSetException.class) assertThatExceptionOfType(IncompleteDistributionSetException.class)
@@ -454,7 +452,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
@Test @Test
@Description("Verifies that an exception is thrown when trying to update a target filter with an invalidated distribution set.") @Description("Verifies that an exception is thrown when trying to update a target filter with an invalidated distribution set.")
public void updateAutoAssignDsWithInvalidDistributionSet() { void updateAutoAssignDsWithInvalidDistributionSet() {
final DistributionSet distributionSet = testdataFactory.createDistributionSet(); final DistributionSet distributionSet = testdataFactory.createDistributionSet();
final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement
.create(entityFactory.targetFilterQuery().create().name("updateAutoAssignDsWithInvalidDistributionSet") .create(entityFactory.targetFilterQuery().create().name("updateAutoAssignDsWithInvalidDistributionSet")
@@ -470,7 +468,7 @@ public class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest
@Test @Test
@Description("Verifies that an exception is thrown when trying to update a target filter with an incomplete distribution set.") @Description("Verifies that an exception is thrown when trying to update a target filter with an incomplete distribution set.")
public void updateAutoAssignDsWithIncompleteDistributionSet() { void updateAutoAssignDsWithIncompleteDistributionSet() {
final DistributionSet distributionSet = testdataFactory.createDistributionSet(); final DistributionSet distributionSet = testdataFactory.createDistributionSet();
final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement.create( final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement.create(
entityFactory.targetFilterQuery().create().name("updateAutoAssignDsWithIncompleteDistributionSet") entityFactory.targetFilterQuery().create().name("updateAutoAssignDsWithIncompleteDistributionSet")

View File

@@ -41,7 +41,7 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
@Test @Test
@Description("Verifies that targets with given target type are returned from repository.") @Description("Verifies that targets with given target type are returned from repository.")
public void findTargetByTargetType() { void findTargetByTargetType() {
final TargetType testType = testdataFactory.createTargetType("testType", final TargetType testType = testdataFactory.createTargetType("testType",
Collections.singletonList(standardDsType)); Collections.singletonList(standardDsType));
final List<Target> unassigned = testdataFactory.createTargets(9, "unassigned"); final List<Target> unassigned = testdataFactory.createTargets(9, "unassigned");
@@ -451,12 +451,12 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
+ setA.getName() + ")"; + setA.getName() + ")";
assertThat(targetManagement.findByFilters(PAGE, filterParams).getContent()) assertThat(targetManagement.findByFilters(PAGE, filterParams).getContent())
.as("has number of elements")
.hasSize(0)
.as("that number is also returned by count query") .as("that number is also returned by count query")
.hasSize((int) targetManagement.countByFilters(filterParams)) .hasSize((int) targetManagement.countByFilters(filterParams))
.as("and filter query returns the same result") .as("and filter query returns the same result")
.hasSize(targetManagement.findByRsql(PAGE, query).getContent().size()); .hasSize(targetManagement.findByRsql(PAGE, query).getContent().size())
.as("has number of elements")
.isEmpty();
} }
@Step @Step
@@ -537,11 +537,13 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
targTagX.getName()); targTagX.getName());
final String query = "(name==*targ-C* or description==*targ-C*) and tag==" + targTagX.getName() final String query = "(name==*targ-C* or description==*targ-C*) and tag==" + targTagX.getName()
+ " and (assignedds.name==" + setA.getName() + " or installedds.name==" + setA.getName() + ")"; + " and (assignedds.name==" + setA.getName() + " or installedds.name==" + setA.getName() + ")";
assertThat(targetManagement.findByFilters(PAGE, filterParams).getContent()).as("has number of elements") assertThat(targetManagement.findByFilters(PAGE, filterParams).getContent())
.hasSize(0).as("that number is also returned by count query") .as("that number is also returned by count query")
.hasSize((int) targetManagement.countByFilters(filterParams)) .hasSize((int) targetManagement.countByFilters(filterParams))
.as("and filter query returns the same result") .as("and filter query returns the same result")
.hasSize(targetManagement.findByRsql(PAGE, query).getContent().size()); .hasSize(targetManagement.findByRsql(PAGE, query).getContent().size())
.as("has number of elements")
.isEmpty();
} }
@Step @Step
@@ -550,11 +552,12 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
targTagW.getName()); targTagW.getName());
final String query = "(name==*targ-A* or description==*targ-A*) and tag==" + targTagW.getName() final String query = "(name==*targ-A* or description==*targ-A*) and tag==" + targTagW.getName()
+ " and (assignedds.name==" + setA.getName() + " or installedds.name==" + setA.getName() + ")"; + " and (assignedds.name==" + setA.getName() + " or installedds.name==" + setA.getName() + ")";
assertThat(targetManagement.findByFilters(PAGE, filterParams).getContent()).as("has number of elements") assertThat(targetManagement.findByFilters(PAGE, filterParams).getContent())
.hasSize(0).as("that number is also returned by count query")
.hasSize((int) targetManagement.countByFilters(filterParams)) .hasSize((int) targetManagement.countByFilters(filterParams))
.as("and filter query returns the same result") .as("and filter query returns the same result")
.hasSize(targetManagement.findByRsql(PAGE, query).getContent().size()); .hasSize(targetManagement.findByRsql(PAGE, query).getContent().size())
.as("has number of elements")
.isEmpty();
} }
@Step @Step

View File

@@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test;
@Slf4j @Slf4j
@Feature("SecurityTests - TargetManagement") @Feature("SecurityTests - TargetManagement")
@Story("SecurityTests TargetManagement") @Story("SecurityTests TargetManagement")
public class TargetManagementSecurityTest extends AbstractJpaIntegrationTest { class TargetManagementSecurityTest 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

@@ -260,13 +260,12 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
final TargetTag targetTag = targetTagManagement.create(entityFactory.tag().create().name("Tag1")); final TargetTag targetTag = targetTagManagement.create(entityFactory.tag().create().name("Tag1"));
final List<Target> assignedTargets = targetManagement.assignTag(assignTarget, targetTag.getId()); final List<Target> assignedTargets = targetManagement.assignTag(assignTarget, targetTag.getId());
assertThat(assignedTargets.size()).as("Assigned targets are wrong").isEqualTo(4); assertThat(assignedTargets).as("Assigned targets are wrong").hasSize(4);
assignedTargets.forEach(target -> assertThat( assignedTargets.forEach(target -> assertThat(getTargetTags(target.getControllerId())).hasSize(1));
getTargetTags(target.getControllerId()).size()).isEqualTo(1));
final TargetTag findTargetTag = targetTagManagement.getByName("Tag1").orElseThrow(IllegalStateException::new); final TargetTag findTargetTag = targetTagManagement.getByName("Tag1").orElseThrow(IllegalStateException::new);
assertThat(assignedTargets.size()).as("Assigned targets are wrong") assertThat(assignedTargets).as("Assigned targets are wrong")
.isEqualTo(targetManagement.findByTag(PAGE, targetTag.getId()).getNumberOfElements()); .hasSize(targetManagement.findByTag(PAGE, targetTag.getId()).getNumberOfElements());
final Target unAssignTarget = targetManagement.unassignTag(List.of("targetId123"), findTargetTag.getId()).get(0); final Target unAssignTarget = targetManagement.unassignTag(List.of("targetId123"), findTargetTag.getId()).get(0);
assertThat(unAssignTarget.getControllerId()).as("Controller id is wrong").isEqualTo("targetId123"); assertThat(unAssignTarget.getControllerId()).as("Controller id is wrong").isEqualTo("targetId123");
@@ -692,7 +691,7 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
.findByFilters(PAGE, new FilterParams(null, null, null, null, Boolean.TRUE, tagNames)).getContent(); .findByFilters(PAGE, new FilterParams(null, null, null, null, Boolean.TRUE, tagNames)).getContent();
assertThat(targetManagement.count()).as("Total targets").isEqualTo(50L); assertThat(targetManagement.count()).as("Total targets").isEqualTo(50L);
assertThat(targetsListWithNoTag.size()).as("Targets with no tag").isEqualTo(25); assertThat(targetsListWithNoTag).as("Targets with no tag").hasSize(25);
} }
@@ -1412,7 +1411,7 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
private void checkTargetsHaveType(final List<Target> targets, final TargetType type) { private void checkTargetsHaveType(final List<Target> targets, final TargetType type) {
final List<JpaTarget> foundTargets = targetRepository final List<JpaTarget> foundTargets = targetRepository
.findAllById(targets.stream().map(Identifiable::getId).collect(Collectors.toList())); .findAllById(targets.stream().map(Identifiable::getId).toList());
for (final Target target : foundTargets) { for (final Target target : foundTargets) {
if (!type.getName().equals(type.getName())) { if (!type.getName().equals(type.getName())) {
fail(String.format("Target %s is not of type %s.", target, type)); fail(String.format("Target %s is not of type %s.", target, type));

View File

@@ -22,7 +22,7 @@ import org.junit.jupiter.api.Test;
@Slf4j @Slf4j
@Feature("SecurityTests - TargetTagManagement") @Feature("SecurityTests - TargetTagManagement")
@Story("SecurityTests TargetTagManagement") @Story("SecurityTests TargetTagManagement")
public class TargetTagManagementSecurityTest extends AbstractJpaIntegrationTest { class TargetTagManagementSecurityTest 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

@@ -19,7 +19,6 @@ import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Random; import java.util.Random;
import java.util.stream.Collectors;
import jakarta.validation.ConstraintViolationException; import jakarta.validation.ConstraintViolationException;
@@ -58,7 +57,7 @@ class TargetTagManagementTest extends AbstractJpaIntegrationTest {
void failOnMissingDs() { void failOnMissingDs() {
final Collection<String> group = testdataFactory.createTargets(5).stream() final Collection<String> group = testdataFactory.createTargets(5).stream()
.map(Target::getControllerId) .map(Target::getControllerId)
.collect(Collectors.toList()); .toList();
final TargetTag tag = targetTagManagement.create(entityFactory.tag().create().name("tag1").description("tagdesc1")); final TargetTag tag = targetTagManagement.create(entityFactory.tag().create().name("tag1").description("tagdesc1"));
final List<String> missing = new ArrayList<>(); final List<String> missing = new ArrayList<>();
@@ -75,13 +74,11 @@ class TargetTagManagementTest extends AbstractJpaIntegrationTest {
final Collection<String> withMissing = concat(group, missing); final Collection<String> withMissing = concat(group, missing);
assertThatThrownBy(() -> targetManagement.assignTag(withMissing, tag.getId())) assertThatThrownBy(() -> targetManagement.assignTag(withMissing, tag.getId()))
.matches(e -> { .matches(e -> {
if (e instanceof EntityNotFoundException enfe) { if (e instanceof EntityNotFoundException enfe
if (enfe.getInfo().get(EntityNotFoundException.TYPE).equals(Target.class.getSimpleName())) { && enfe.getInfo().get(EntityNotFoundException.TYPE).equals(Target.class.getSimpleName())
if (enfe.getInfo().get(EntityNotFoundException.ENTITY_ID) instanceof Collection entityId) { && enfe.getInfo().get(EntityNotFoundException.ENTITY_ID) instanceof Collection entityId) {
return entityId.stream().sorted().toList().equals(missing); return entityId.stream().sorted().toList().equals(missing);
} }
}
}
return false; return false;
}); });
} }
@@ -126,9 +123,10 @@ class TargetTagManagementTest extends AbstractJpaIntegrationTest {
// toggle A only -> A is now assigned // toggle A only -> A is now assigned
List<Target> result = assignTag(groupA, tag); List<Target> result = assignTag(groupA, tag);
assertThat(result).size().isEqualTo(20); assertThat(result)
assertThat(result).containsAll( .containsAll(
targetManagement.getByControllerID(groupA.stream().map(Target::getControllerId).collect(Collectors.toList()))); targetManagement.getByControllerID(groupA.stream().map(Target::getControllerId).toList()))
.size().isEqualTo(20);
assertThat(targetManagement.findByTag(Pageable.unpaged(), tag.getId()).getContent().stream().map(Target::getControllerId).sorted() assertThat(targetManagement.findByTag(Pageable.unpaged(), tag.getId()).getContent().stream().map(Target::getControllerId).sorted()
.toList()) .toList())
.isEqualTo(groupA.stream().map(Target::getControllerId).sorted().toList()); .isEqualTo(groupA.stream().map(Target::getControllerId).sorted().toList());
@@ -136,18 +134,19 @@ class TargetTagManagementTest extends AbstractJpaIntegrationTest {
// toggle A+B -> A is still assigned and B is assigned as well // toggle A+B -> A is still assigned and B is assigned as well
final Collection<Target> groupAB = concat(groupA, groupB); final Collection<Target> groupAB = concat(groupA, groupB);
result = assignTag(groupAB, tag); result = assignTag(groupAB, tag);
assertThat(result).size().isEqualTo(40); assertThat(result)
assertThat(result).containsAll( .containsAll(
targetManagement.getByControllerID(groupAB.stream().map(Target::getControllerId).collect(Collectors.toList()))); targetManagement.getByControllerID(groupAB.stream().map(Target::getControllerId).toList()))
.size().isEqualTo(40);
assertThat(targetManagement.findByTag(Pageable.unpaged(), tag.getId()).getContent().stream().map(Target::getControllerId).sorted() assertThat(targetManagement.findByTag(Pageable.unpaged(), tag.getId()).getContent().stream().map(Target::getControllerId).sorted()
.toList()) .toList())
.isEqualTo(groupAB.stream().map(Target::getControllerId).sorted().toList()); .isEqualTo(groupAB.stream().map(Target::getControllerId).sorted().toList());
// toggle A+B -> both unassigned // toggle A+B -> both unassigned
result = unassignTag(groupAB, tag); result = unassignTag(groupAB, tag);
assertThat(result).size().isEqualTo(40); assertThat(result)
assertThat(result).containsAll( .containsAll(targetManagement.getByControllerID(groupAB.stream().map(Target::getControllerId).toList()))
targetManagement.getByControllerID(groupAB.stream().map(Target::getControllerId).collect(Collectors.toList()))); .size().isEqualTo(40);
assertThat(targetManagement.findByTag(Pageable.unpaged(), tag.getId()).getContent()).isEmpty(); assertThat(targetManagement.findByTag(Pageable.unpaged(), tag.getId()).getContent()).isEmpty();
} }

View File

@@ -35,18 +35,18 @@ import org.springframework.data.jpa.domain.Specification;
@Feature("Unit Tests - Repository") @Feature("Unit Tests - Repository")
@Story("Specifications builder") @Story("Specifications builder")
public class SpecificationsBuilderTest { class SpecificationsBuilderTest {
@Test @Test
@Description("Test the combination of specs on an empty list which returns null") @Description("Test the combination of specs on an empty list which returns null")
public void combineWithAndEmptyList() { void combineWithAndEmptyList() {
final List<Specification<Object>> specList = Collections.emptyList(); final List<Specification<Object>> specList = Collections.emptyList();
assertThat(SpecificationsBuilder.combineWithAnd(specList)).isNull(); assertThat(SpecificationsBuilder.combineWithAnd(specList)).isNull();
} }
@Test @Test
@Description("Test the combination of specs on an immutable list with one entry") @Description("Test the combination of specs on an immutable list with one entry")
public void combineWithAndSingleImmutableList() { void combineWithAndSingleImmutableList() {
final Specification<Object> spec = (root, query, cb) -> cb.equal(root.get("field1"), "testValue"); final Specification<Object> spec = (root, query, cb) -> cb.equal(root.get("field1"), "testValue");
final List<Specification<Object>> specList = Collections.singletonList(spec); final List<Specification<Object>> specList = Collections.singletonList(spec);
final Specification<Object> specifications = SpecificationsBuilder.combineWithAnd(specList); final Specification<Object> specifications = SpecificationsBuilder.combineWithAnd(specList);
@@ -70,7 +70,7 @@ public class SpecificationsBuilderTest {
@Test @Test
@Description("Test the combination of specs on a list with multiple entries") @Description("Test the combination of specs on a list with multiple entries")
public void combineWithAndList() { void combineWithAndList() {
final Specification<Object> spec1 = (root, query, cb) -> cb.equal(root.get("field1"), "testValue1"); final Specification<Object> spec1 = (root, query, cb) -> cb.equal(root.get("field1"), "testValue1");
final Specification<Object> spec2 = (root, query, cb) -> cb.equal(root.get("field2"), "testValue2"); final Specification<Object> spec2 = (root, query, cb) -> cb.equal(root.get("field2"), "testValue2");
@@ -93,7 +93,7 @@ public class SpecificationsBuilderTest {
when(criteriaBuilder.equal(any(Path.class), eq("testValue1"))).thenReturn(equalPredicate1); when(criteriaBuilder.equal(any(Path.class), eq("testValue1"))).thenReturn(equalPredicate1);
when(criteriaBuilder.equal(any(Path.class), eq("testValue2"))).thenReturn(equalPredicate2); when(criteriaBuilder.equal(any(Path.class), eq("testValue2"))).thenReturn(equalPredicate2);
when(criteriaBuilder.and(eq(equalPredicate1), eq(equalPredicate2))).thenReturn(combinedPredicate); when(criteriaBuilder.and(equalPredicate1, equalPredicate2)).thenReturn(combinedPredicate);
when(root.get("field1")).thenReturn(field1); when(root.get("field1")).thenReturn(field1);
when(root.get("field2")).thenReturn(field2); when(root.get("field2")).thenReturn(field2);

View File

@@ -92,6 +92,7 @@ public class SecurityContextSwitch {
} }
// should be used only for test purposes and taking in account 'annotation' non-transient field in a Serializable // should be used only for test purposes and taking in account 'annotation' non-transient field in a Serializable
@SuppressWarnings("java:S1948") // java:S1948 - see comments into the method
static class WithUserSecurityContext implements SecurityContext { static class WithUserSecurityContext implements SecurityContext {
@Serial @Serial

View File

@@ -58,7 +58,7 @@ public final class SpRole {
public static final String SYSTEM_ADMIN_HIERARCHY = public static final String SYSTEM_ADMIN_HIERARCHY =
SpPermission.SYSTEM_ADMIN + IMPLIES + TENANT_ADMIN + LINE_BREAK; SpPermission.SYSTEM_ADMIN + IMPLIES + TENANT_ADMIN + LINE_BREAK;
public static String DEFAULT_ROLE_HIERARCHY = public static final String DEFAULT_ROLE_HIERARCHY =
TARGET_ADMIN_HIERARCHY + TARGET_ADMIN_HIERARCHY +
REPOSITORY_ADMIN_HIERARCHY + REPOSITORY_ADMIN_HIERARCHY +
ROLLOUT_ADMIN_HIERARCHY + ROLLOUT_ADMIN_HIERARCHY +

View File

@@ -128,8 +128,8 @@ public class StaticAuthenticationProvider extends DaoAuthenticationProvider {
} }
private static User clone(final User user) { private static User clone(final User user) {
if (user instanceof TenantAwareUser) { if (user instanceof TenantAwareUser tenantAwareUser) {
return new TenantAwareUser(user.getUsername(), user.getPassword(), user.getAuthorities(), ((TenantAwareUser) user).getTenant()); return new TenantAwareUser(user.getUsername(), user.getPassword(), user.getAuthorities(), tenantAwareUser.getTenant());
} else { } else {
return new User(user.getUsername(), user.getPassword(), user.getAuthorities()); return new User(user.getUsername(), user.getPassword(), user.getAuthorities());
} }

View File

@@ -17,6 +17,8 @@ import java.io.ObjectOutputStream;
import java.util.Base64; import java.util.Base64;
import java.util.Objects; import java.util.Objects;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContext;
public interface SecurityContextSerializer { public interface SecurityContextSerializer {
@@ -74,11 +76,10 @@ public interface SecurityContextSerializer {
/** /**
* Implementation based on the java serialization. * Implementation based on the java serialization.
*/ */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@SuppressWarnings("java:S112") // accepted
class JavaSerialization implements SecurityContextSerializer { class JavaSerialization implements SecurityContextSerializer {
private JavaSerialization() {
}
@Override @Override
public String serialize(final SecurityContext securityContext) { public String serialize(final SecurityContext securityContext) {
Objects.requireNonNull(securityContext); Objects.requireNonNull(securityContext);

View File

@@ -62,11 +62,11 @@ public class SpringSecurityAuditorAware implements AuditorAware<String> {
if (authentication.getDetails() instanceof TenantAwareAuthenticationDetails tenantAwareDetails && tenantAwareDetails.isController()) { if (authentication.getDetails() instanceof TenantAwareAuthenticationDetails tenantAwareDetails && tenantAwareDetails.isController()) {
return "CONTROLLER_PLUG_AND_PLAY"; return "CONTROLLER_PLUG_AND_PLAY";
} }
if (authentication.getPrincipal() instanceof UserDetails) { if (authentication.getPrincipal() instanceof UserDetails userDetails) {
return ((UserDetails) authentication.getPrincipal()).getUsername(); return userDetails.getUsername();
} }
if (authentication.getPrincipal() instanceof OidcUser) { if (authentication.getPrincipal() instanceof OidcUser oidcUser) {
return ((OidcUser) authentication.getPrincipal()).getPreferredUsername(); return oidcUser.getPreferredUsername();
} }
return authentication.getPrincipal().toString(); return authentication.getPrincipal().toString();
} }

View File

@@ -26,7 +26,7 @@ import org.springframework.util.ReflectionUtils;
*/ */
@Feature("Unit Tests - Security") @Feature("Unit Tests - Security")
@Story("Permission Test") @Story("Permission Test")
public final class SpPermissionTest { final class SpPermissionTest {
@Test @Test
@Description("Try to double check if all permissions works as expected") @Description("Try to double check if all permissions works as expected")
@@ -42,7 +42,8 @@ public final class SpPermissionTest {
} }
}); });
final Collection<String> allAuthorities = SpPermission.getAllAuthorities(); final Collection<String> allAuthorities = SpPermission.getAllAuthorities();
assertThat(allAuthorities).hasSize(20); assertThat(allAuthorities)
assertThat(allAuthorities).containsAll(expected); .hasSize(20)
.containsAll(expected);
} }
} }

View File

@@ -22,6 +22,7 @@ import com.vaadin.flow.data.provider.Query;
import com.vaadin.flow.theme.lumo.LumoUtility; import com.vaadin.flow.theme.lumo.LumoUtility;
// id type shall have proper equals and hashCode - i.e. eligible hash set element // id type shall have proper equals and hashCode - i.e. eligible hash set element
@SuppressWarnings("java:S119") // better readability
public class SelectionGrid<T, ID> extends Grid<T> { public class SelectionGrid<T, ID> extends Grid<T> {
private volatile String rsqlFilter; private volatile String rsqlFilter;
@@ -80,7 +81,7 @@ public class SelectionGrid<T, ID> extends Grid<T> {
} }
} }
public static abstract class EntityRepresentation<T, ID> { public abstract static class EntityRepresentation<T, ID> {
private final Class<T> beanType; private final Class<T> beanType;
private final Function<T, ID> idFn; private final Function<T, ID> idFn;

View File

@@ -19,6 +19,7 @@ import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.data.provider.Query; import com.vaadin.flow.data.provider.Query;
import org.eclipse.hawkbit.ui.simple.view.Constants; import org.eclipse.hawkbit.ui.simple.view.Constants;
@SuppressWarnings("java:S119") // better readability
public class TableView<T, ID> extends Div implements Constants { public class TableView<T, ID> extends Div implements Constants {
protected SelectionGrid<T, ID> selectionGrid; protected SelectionGrid<T, ID> selectionGrid;