Fix SonarQube issues (1) (#2204)

Signed-off-by: Avgustin Marinov <Avgustin.Marinov@bosch.com>
This commit is contained in:
Avgustin Marinov
2025-01-20 14:23:58 +02:00
committed by GitHub
parent 25e45d5825
commit 385023d8b6
8 changed files with 57 additions and 53 deletions

View File

@@ -25,23 +25,23 @@ import org.springframework.test.context.TestPropertySource;
})
@Feature("Integration Test - Security")
@Story("Allowed Host Names")
public class AllowedHostNamesTest extends AbstractSecurityTest {
class AllowedHostNamesTest extends AbstractSecurityTest {
@Test
@Description("Tests whether a RequestRejectedException is thrown when not allowed host is used")
public void allowedHostNameWithNotAllowedHost() throws Exception {
void allowedHostNameWithNotAllowedHost() throws Exception {
mvc.perform(get("/").header(HttpHeaders.HOST, "www.google.com")).andExpect(status().isBadRequest());
}
@Test
@Description("Tests whether request is redirected when allowed host is used")
public void allowedHostNameWithAllowedHost() throws Exception {
void allowedHostNameWithAllowedHost() throws Exception {
mvc.perform(get("/").header(HttpHeaders.HOST, "localhost")).andExpect(status().is3xxRedirection());
}
@Test
@Description("Tests whether request without allowed host name and with ignored path end up with a client error")
public void notAllowedHostnameWithIgnoredPath() throws Exception {
void notAllowedHostnameWithIgnoredPath() throws Exception {
mvc.perform(get("/index.html").header(HttpHeaders.HOST, "www.google.com"))
.andExpect(status().is4xxClientError());
}

View File

@@ -15,7 +15,6 @@ import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.BooleanSupplier;
import java.util.stream.Collectors;
import jakarta.persistence.criteria.JoinType;
@@ -163,7 +162,7 @@ public abstract class AbstractDsAssignmentStrategy {
actionRepository.save(action);
return action.getTarget().getId();
}).collect(Collectors.toList());
}).toList();
if (!activeActions.isEmpty()) {
cancelAssignDistributionSetEvent(Collections.unmodifiableList(activeActions));
@@ -202,7 +201,7 @@ public abstract class AbstractDsAssignmentStrategy {
actionRepository.save(action);
return action.getTarget().getId();
}).collect(Collectors.toList());
}).toList();
}

View File

@@ -83,8 +83,7 @@ public abstract class AbstractRemoteEventTest extends AbstractJpaIntegrationTest
headers.put(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON);
try {
final String json = new ObjectMapper().writeValueAsString(event);
final Message<String> message = MessageBuilder.withPayload(json).copyHeaders(headers).build();
return message;
return MessageBuilder.withPayload(json).copyHeaders(headers).build();
} catch (final JsonProcessingException e) {
fail(e.getMessage());
}

View File

@@ -27,17 +27,17 @@ import org.junit.jupiter.api.Test;
*/
@Feature("Component Tests - Repository")
@Story("Test ActionCreatedEvent and ActionUpdatedEvent")
public class ActionEventTest extends AbstractRemoteEntityEventTest<Action> {
class ActionEventTest extends AbstractRemoteEntityEventTest<Action> {
@Test
@Description("Verifies that the action entity reloading by remote created works")
public void testActionCreatedEvent() {
void testActionCreatedEvent() {
assertAndCreateRemoteEvent(ActionCreatedEvent.class);
}
@Test
@Description("Verifies that the action entity reloading by remote updated works")
public void testActionUpdatedEvent() {
void testActionUpdatedEvent() {
assertAndCreateRemoteEvent(ActionUpdatedEvent.class);
}

View File

@@ -16,7 +16,6 @@ import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import jakarta.persistence.EntityManager;
@@ -24,6 +23,7 @@ import jakarta.persistence.PersistenceContext;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
import org.eclipse.hawkbit.im.authentication.SpPermission;
@@ -76,8 +76,7 @@ import org.springframework.test.context.TestPropertySource;
import org.springframework.transaction.annotation.Transactional;
@Slf4j
@ContextConfiguration(classes = {
RepositoryApplicationConfiguration.class, TestConfiguration.class })
@ContextConfiguration(classes = { RepositoryApplicationConfiguration.class, TestConfiguration.class })
@Import(TestChannelBinderConfiguration.class)
@TestPropertySource(locations = "classpath:/jpa-test.properties")
public abstract class AbstractJpaIntegrationTest extends AbstractIntegrationTest {
@@ -86,6 +85,8 @@ public abstract class AbstractJpaIntegrationTest extends AbstractIntegrationTest
protected static final String NOT_EXIST_ID = "12345678990";
protected static final long NOT_EXIST_IDL = Long.parseLong(NOT_EXIST_ID);
protected static final RandomStringUtils RANDOM_STRING_UTILS = RandomStringUtils.insecure();
private static final List<String> REPOSITORY_AND_TARGET_PERMISSIONS = List.of(SpPermission.READ_REPOSITORY, SpPermission.CREATE_REPOSITORY, SpPermission.UPDATE_REPOSITORY, SpPermission.DELETE_REPOSITORY, SpPermission.READ_TARGET, SpPermission.CREATE_TARGET, SpPermission.UPDATE_TARGET, SpPermission.DELETE_TARGET);
@PersistenceContext
@@ -176,6 +177,14 @@ public abstract class AbstractJpaIntegrationTest extends AbstractIntegrationTest
((JpaSoftwareModule) module).setOptLockRevision(module.getOptLockRevision() + 1);
}
protected static String randomString(final int len) {
return RANDOM_STRING_UTILS.next(len, true, false);
}
protected static byte[] randomBytes(final int len) {
return randomString(len).getBytes();
}
protected Database getDatabase() {
return jpaProperties.getDatabase();
}
@@ -187,18 +196,18 @@ public abstract class AbstractJpaIntegrationTest extends AbstractIntegrationTest
protected List<Target> assignTag(final Collection<Target> targets, final TargetTag tag) {
return targetManagement.assignTag(
targets.stream().map(Target::getControllerId).collect(Collectors.toList()), tag.getId());
targets.stream().map(Target::getControllerId).toList(), tag.getId());
}
protected List<Target> unassignTag(final Collection<Target> targets, final TargetTag tag) {
return targetManagement.unassignTag(
targets.stream().map(Target::getControllerId).collect(Collectors.toList()), tag.getId());
targets.stream().map(Target::getControllerId).toList(), tag.getId());
}
protected List<DistributionSet> assignTag(final Collection<DistributionSet> sets,
final DistributionSetTag tag) {
return distributionSetManagement.assignTag(
sets.stream().map(DistributionSet::getId).collect(Collectors.toList()), tag.getId());
sets.stream().map(DistributionSet::getId).toList(), tag.getId());
}
protected List<DistributionSet> unassignTag(final Collection<DistributionSet> sets,
@@ -209,7 +218,7 @@ public abstract class AbstractJpaIntegrationTest extends AbstractIntegrationTest
protected TargetTypeAssignmentResult initiateTypeAssignment(final Collection<Target> targets, final TargetType type) {
return targetManagement.assignType(
targets.stream().map(Target::getControllerId).collect(Collectors.toList()), type.getId());
targets.stream().map(Target::getControllerId).toList(), type.getId());
}
protected void assertRollout(final Rollout rollout, final boolean dynamic, final Rollout.RolloutStatus status, final int groupCreated,

View File

@@ -192,7 +192,7 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
enableConfirmationFlow();
}
final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement.updateAutoAssignDS(entityFactory
targetFilterQueryManagement.updateAutoAssignDS(entityFactory
.targetFilterQuery()
.updateAutoAssign(targetFilterQueryManagement
.create(entityFactory.targetFilterQuery().create().name("filterA").query("name==*")).getId())
@@ -317,7 +317,7 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
@Test
@Description("An auto assignment target filter with weight creates actions with weights")
void actionsWithWeightAreCreated() throws Exception {
void actionsWithWeightAreCreated() {
final int amountOfTargets = 5;
final DistributionSet ds = testdataFactory.createDistributionSet();
final int weight = 32;
@@ -329,13 +329,14 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
autoAssignChecker.checkAllTargets();
final List<Action> actions = deploymentManagement.findActionsAll(PAGE).getContent();
assertThat(actions).hasSize(amountOfTargets);
assertThat(actions).allMatch(action -> action.getWeight().get() == weight);
assertThat(actions)
.hasSize(amountOfTargets)
.allMatch(action -> action.getWeight().get() == weight);
}
@Test
@Description("An auto assignment target filter without weight still works after multi assignment is enabled")
void filterWithoutWeightWorksInMultiAssignmentMode() throws Exception {
void filterWithoutWeightWorksInMultiAssignmentMode() {
final int amountOfTargets = 5;
final DistributionSet ds = testdataFactory.createDistributionSet();
targetFilterQueryManagement.create(
@@ -346,8 +347,9 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
autoAssignChecker.checkAllTargets();
final List<Action> actions = deploymentManagement.findActionsAll(PAGE).getContent();
assertThat(actions).hasSize(amountOfTargets);
assertThat(actions).allMatch(action -> action.getWeight().isPresent());
assertThat(actions)
.hasSize(amountOfTargets)
.allMatch(action -> action.getWeight().isPresent());
}
@Test
@@ -387,7 +389,7 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
final List<Long> compatibleTargets = Stream
.of(compatibleTargetsSingleType, compatibleTargetsMultiType, compatibleTargetsWithoutType)
.flatMap(Collection::stream).map(Target::getId).collect(Collectors.toList());
.flatMap(Collection::stream).map(Target::getId).toList();
final long compatibleCount = targetManagement.countByRsqlAndNonDSAndCompatibleAndUpdatable(testDs.getId(),
testFilter.getQuery());
assertThat(compatibleCount).isEqualTo(compatibleTargets.size());
@@ -396,7 +398,7 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
final List<Action> actions = deploymentManagement.findActionsAll(Pageable.unpaged()).getContent();
assertThat(actions).hasSize(compatibleTargets.size());
final List<Long> actionTargets = actions.stream().map(a -> a.getTarget().getId()).collect(Collectors.toList());
final List<Long> actionTargets = actions.stream().map(a -> a.getTarget().getId()).toList();
assertThat(actionTargets).containsExactlyInAnyOrderElementsOf(compatibleTargets);
}
@@ -413,17 +415,17 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
* @param targets the targets that should have it
*/
@Step
private void verifyThatTargetsHaveDistributionSetAssignment(final DistributionSet set, final List<Target> targets,
final int count) {
final List<Long> targetIds = targets.stream().map(Target::getId).collect(Collectors.toList());
private void verifyThatTargetsHaveDistributionSetAssignment(
final DistributionSet set, final List<Target> targets, final int count) {
final List<Long> targetIds = targets.stream().map(Target::getId).toList();
final Slice<Target> targetsAll = targetManagement.findAll(PAGE);
assertThat(targetsAll).as("Count of targets").hasSize(count);
for (final Target target : targetsAll) {
if (targetIds.contains(target.getId())) {
assertThat(deploymentManagement.getAssignedDistributionSet(target.getControllerId()).get())
.as("assigned DS").isEqualTo(set);
assertThat(deploymentManagement.getAssignedDistributionSet(target.getControllerId()))
.as("assigned DS").contains(set);
}
}
}
@@ -431,9 +433,8 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
@Step
private void verifyThatTargetsHaveDistributionSetAssignedAndActionStatus(final DistributionSet set,
final List<Target> targets, final Action.Status status) {
final List<String> targetIds = targets.stream().map(Target::getControllerId).collect(Collectors.toList());
final List<Target> targetsWithAssignedDS = targetManagement.findByAssignedDistributionSet(PAGE, set.getId())
.getContent();
final List<String> targetIds = targets.stream().map(Target::getControllerId).toList();
final List<Target> targetsWithAssignedDS = targetManagement.findByAssignedDistributionSet(PAGE, set.getId()).getContent();
assertThat(targetsWithAssignedDS).isNotEmpty();
assertThat(targetsWithAssignedDS).allMatch(target -> targetIds.contains(target.getControllerId()));
@@ -447,7 +448,7 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
@Step
private void verifyThatTargetsNotHaveDistributionSetAssignment(final DistributionSet set,
final List<Target> targets) {
final List<Long> targetIds = targets.stream().map(Target::getId).collect(Collectors.toList());
final List<Long> targetIds = targets.stream().map(Target::getId).toList();
final Slice<Target> targetsAll = targetManagement.findAll(PAGE);
@@ -486,9 +487,10 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
@Step
private void verifyThatTargetsHaveAssignmentActionType(final ActionType actionType, final List<Target> targets) {
final List<Action> actions = targets.stream().map(Target::getControllerId).flatMap(
controllerId -> deploymentManagement.findActionsByTarget(controllerId, PAGE).getContent().stream())
.collect(Collectors.toList());
final List<Action> actions = targets.stream()
.map(Target::getControllerId)
.flatMap(controllerId -> deploymentManagement.findActionsByTarget(controllerId, PAGE).getContent().stream())
.toList();
assertThat(actions).hasSize(targets.size());
assertThat(actions).allMatch(action -> action.getActionType().equals(actionType));

View File

@@ -28,7 +28,7 @@ import org.springframework.integration.support.locks.LockRegistry;
*/
@Feature("Component Tests - Repository")
@Story("Auto cleanup scheduler")
public class AutoCleanupSchedulerTest extends AbstractJpaIntegrationTest {
class AutoCleanupSchedulerTest extends AbstractJpaIntegrationTest {
private final AtomicInteger counter = new AtomicInteger();
@@ -36,13 +36,13 @@ public class AutoCleanupSchedulerTest extends AbstractJpaIntegrationTest {
private LockRegistry lockRegistry;
@BeforeEach
public void setUp() {
void setUp() {
counter.set(0);
}
@Test
@Description("Verifies that all cleanup handlers are executed regardless if one of them throws an error")
public void executeHandlerChain() {
void executeHandlerChain() {
new AutoCleanupScheduler(systemManagement, systemSecurityContext, lockRegistry, Arrays.asList(
new SuccessfulCleanup(), new SuccessfulCleanup(), new FailingCleanup(), new SuccessfulCleanup())).run();

View File

@@ -441,7 +441,7 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
void createArtifactWithNoneMatchingHashes() throws IOException, NoSuchAlgorithmException {
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
final byte[] testData = RandomStringUtils.randomAlphanumeric(100).getBytes();
final byte[] testData = randomBytes(100);
final DbArtifactHash artifactHashes = calcHashes(testData);
try (final InputStream inputStream = new ByteArrayInputStream(testData)) {
@@ -474,7 +474,7 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
void createArtifactWithMatchingHashes() throws IOException, NoSuchAlgorithmException {
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
final byte[] testData = RandomStringUtils.randomAlphanumeric(100).getBytes();
final byte[] testData = randomBytes(100);
final DbArtifactHash artifactHashes = calcHashes(testData);
try (final InputStream inputStream = new ByteArrayInputStream(testData)) {
@@ -497,7 +497,7 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
final SoftwareModule smOs = testdataFactory.createSoftwareModuleOs();
final SoftwareModule smApp = testdataFactory.createSoftwareModuleApp();
final byte[] testData = RandomStringUtils.randomAlphanumeric(100).getBytes();
final byte[] testData = randomBytes(100);
final DbArtifactHash artifactHashes = calcHashes(testData);
try (final InputStream inputStream = new ByteArrayInputStream(testData)) {
@@ -521,10 +521,6 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
}
}
private static byte[] randomBytes(final int len) {
return RandomStringUtils.randomAlphanumeric(len).getBytes();
}
private DbArtifactHash calcHashes(final byte[] input) throws NoSuchAlgorithmException {
final String sha1Hash = toBase16Hash("SHA1", input);
final String md5Hash = toBase16Hash("MD5", input);
@@ -539,8 +535,7 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
return HexFormat.of().withLowerCase().formatHex(messageDigest.digest());
}
private Artifact createArtifactForSoftwareModule(final String filename, final long moduleId, final int artifactSize)
throws IOException {
private Artifact createArtifactForSoftwareModule(final String filename, final long moduleId, final int artifactSize) throws IOException {
final byte[] randomBytes = randomBytes(artifactSize);
try (final InputStream inputStream = new ByteArrayInputStream(randomBytes)) {
return createArtifactForSoftwareModule(filename, moduleId, artifactSize, inputStream);