Skip to content

Commit

Permalink
Fix SonarQube issues (1) (#2204)
Browse files Browse the repository at this point in the history
Signed-off-by: Avgustin Marinov <[email protected]>
  • Loading branch information
avgustinmm authored Jan 20, 2025
1 parent 25e45d5 commit 385023d
Show file tree
Hide file tree
Showing 8 changed files with 57 additions and 53 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,23 +25,23 @@
})
@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());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import java.util.Optional;
import java.util.Set;
import java.util.function.BooleanSupplier;
import java.util.stream.Collectors;

import jakarta.persistence.criteria.JoinType;

Expand Down Expand Up @@ -163,7 +162,7 @@ protected List<Long> overrideObsoleteUpdateActions(final Collection<Long> target
actionRepository.save(action);

return action.getTarget().getId();
}).collect(Collectors.toList());
}).toList();

if (!activeActions.isEmpty()) {
cancelAssignDistributionSetEvent(Collections.unmodifiableList(activeActions));
Expand Down Expand Up @@ -202,7 +201,7 @@ protected List<Long> closeObsoleteUpdateActions(final Collection<Long> targetsId
actionRepository.save(action);

return action.getTarget().getId();
}).collect(Collectors.toList());
}).toList();

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
/**
* Test the remote entity events.
*/
public abstract class AbstractRemoteEventTest extends AbstractJpaIntegrationTest {
public abstract class AbstractRemoteEventTest extends AbstractJpaIntegrationTest {

@Autowired
private BusProtoStuffMessageConverter busProtoStuffMessageConverter;
Expand Down Expand Up @@ -83,8 +83,7 @@ private Message<String> createJsonMessage(final Object event) {
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());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,17 @@
*/
@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);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@
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;
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;
Expand Down Expand Up @@ -76,8 +76,7 @@
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 {
Expand All @@ -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
Expand Down Expand Up @@ -176,6 +177,14 @@ protected static void implicitLock(final SoftwareModule module) {
((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();
}
Expand All @@ -187,18 +196,18 @@ protected List<Action> findActionsByRolloutAndStatus(final Rollout rollout, fina

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,
Expand All @@ -209,7 +218,7 @@ protected List<DistributionSet> unassignTag(final Collection<DistributionSet> se

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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ void checkAutoAssignWithConfirmationOptions(final boolean confirmationFlowActive
enableConfirmationFlow();
}

final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement.updateAutoAssignDS(entityFactory
targetFilterQueryManagement.updateAutoAssignDS(entityFactory
.targetFilterQuery()
.updateAutoAssign(targetFilterQueryManagement
.create(entityFactory.targetFilterQuery().create().name("filterA").query("name==*")).getId())
Expand Down Expand Up @@ -317,7 +317,7 @@ void checkAutoAssignWithDifferentActionTypes() {

@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;
Expand All @@ -329,13 +329,14 @@ void actionsWithWeightAreCreated() throws Exception {
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(
Expand All @@ -346,8 +347,9 @@ void filterWithoutWeightWorksInMultiAssignmentMode() throws Exception {
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
Expand Down Expand Up @@ -387,7 +389,7 @@ void checkAutoAssignmentWithIncompatibleTargets() {

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());
Expand All @@ -396,7 +398,7 @@ void checkAutoAssignmentWithIncompatibleTargets() {

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);
}

Expand All @@ -413,27 +415,26 @@ private static Stream<Arguments> confirmationOptions() {
* @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);
}
}
}

@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()));

Expand All @@ -447,7 +448,7 @@ private void verifyThatTargetsHaveDistributionSetAssignedAndActionStatus(final D
@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);

Expand Down Expand Up @@ -486,9 +487,10 @@ private List<Target> createTargetsAndAutoAssignDistSet(final String prefix, fina

@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));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,21 +28,21 @@
*/
@Feature("Component Tests - Repository")
@Story("Auto cleanup scheduler")
public class AutoCleanupSchedulerTest extends AbstractJpaIntegrationTest {
class AutoCleanupSchedulerTest extends AbstractJpaIntegrationTest {

private final AtomicInteger counter = new AtomicInteger();

@Autowired
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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ void findByFilenameAndSoftwareModule() throws IOException {
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)) {
Expand Down Expand Up @@ -474,7 +474,7 @@ void createArtifactWithNoneMatchingHashes() throws IOException, NoSuchAlgorithmE
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)) {
Expand All @@ -497,7 +497,7 @@ void createExistingArtifactReturnsFullHashList() throws IOException, NoSuchAlgor
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)) {
Expand All @@ -521,10 +521,6 @@ void createExistingArtifactReturnsFullHashList() throws IOException, NoSuchAlgor
}
}

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);
Expand All @@ -539,8 +535,7 @@ private String toBase16Hash(final String algorithm, final byte[] input) throws N
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);
Expand Down

0 comments on commit 385023d

Please sign in to comment.