Skip to content

Commit

Permalink
Sonar Fixes (#2233)
Browse files Browse the repository at this point in the history
Signed-off-by: Avgustin Marinov <Avgustin.Marinov@bosch.com>
  • Loading branch information
avgustinmm authored Jan 24, 2025
1 parent 0280d96 commit a61e9cd
Show file tree
Hide file tree
Showing 66 changed files with 400 additions and 386 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.eclipse.hawkbit.artifact.repository.urlhandler.ArtifactUrlHandlerProperties.UrlProtocol;
import org.springframework.util.ObjectUtils;
Expand Down Expand Up @@ -87,7 +86,7 @@ public List<ArtifactUrl> getUrls(final URLPlaceholder placeholder, final ApiType
.filter(urlProtocol -> urlProtocol.getSupports().contains(api) && urlProtocol.isEnabled())
.map(urlProtocol -> new ArtifactUrl(urlProtocol.getProtocol().toUpperCase(), urlProtocol.getRel(),
generateUrl(urlProtocol, placeholder, requestUri)))
.collect(Collectors.toList());
.toList();

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,8 @@ void urlGenerationWithDefaultConfiguration() {
new ArtifactUrl(
"http".toUpperCase(), "download-http",
HTTP_LOCALHOST + TENANT + "/controller/v1/" +
CONTROLLER_ID + "/softwaremodules/" + SOFTWARE_MODULE_ID + "/artifacts/" + FILENAME_ENCODE));

assertThat(ddiUrls).isEqualTo(urlHandlerUnderTest.getUrls(placeHolder, ApiType.DMF));
CONTROLLER_ID + "/softwaremodules/" + SOFTWARE_MODULE_ID + "/artifacts/" + FILENAME_ENCODE))
.isEqualTo(urlHandlerUnderTest.getUrls(placeHolder, ApiType.DMF));
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,20 @@
@Feature("Integration Test - Security")
@Story("PreAuthorized enabled")
@TestPropertySource(properties = { "spring.flyway.enabled=true" })
public class PreAuthorizeEnabledTest extends AbstractSecurityTest {
class PreAuthorizeEnabledTest extends AbstractSecurityTest {

@Test
@Description("Tests whether request fail if a role is forbidden for the user")
@WithUser(authorities = { SpPermission.READ_TARGET }, autoCreateTenant = false)
public void failIfNoRole() throws Exception {
void failIfNoRole() throws Exception {
mvc.perform(get("/DEFAULT/controller/v1/controllerId"))
.andExpect(result -> assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.FORBIDDEN.value()));
}

@Test
@Description("Tests whether request succeed if a role is granted for the user")
@WithUser(authorities = { SpPermission.SpringEvalExpressions.CONTROLLER_ROLE }, autoCreateTenant = false)
public void successIfHasRole() throws Exception {
void successIfHasRole() throws Exception {
mvc.perform(get("/DEFAULT/controller/v1/controllerId"))
.andExpect(result -> assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.OK.value()));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
@Feature("Unit Tests - Security")
@Story("PreAuthToken Source TrustAuthentication Provider Test")
@ExtendWith(MockitoExtension.class)
public class PreAuthTokenSourceTrustAuthenticationProviderTest {
class PreAuthTokenSourceTrustAuthenticationProviderTest {

private static final String REQUEST_SOURCE_IP = "127.0.0.1";

Expand All @@ -46,7 +46,7 @@ public class PreAuthTokenSourceTrustAuthenticationProviderTest {

@Test
@Description("Testing in case the containing controllerId in the URI request path does not accord with the controllerId in the request header.")
public void principalAndCredentialsNotTheSameThrowsAuthenticationException() {
void principalAndCredentialsNotTheSameThrowsAuthenticationException() {
final String principal = "controllerIdURL";
final String credentials = "controllerIdHeader";
final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal,
Expand All @@ -59,7 +59,7 @@ public void principalAndCredentialsNotTheSameThrowsAuthenticationException() {

@Test
@Description("Testing that the controllerId within the URI request path is the same with the controllerId within the request header and no source IP check is in place.")
public void principalAndCredentialsAreTheSameWithNoSourceIpCheckIsSuccessful() {
void principalAndCredentialsAreTheSameWithNoSourceIpCheckIsSuccessful() {
final String principal = "controllerId";
final String credentials = "controllerId";
final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal,
Expand All @@ -72,7 +72,7 @@ public void principalAndCredentialsAreTheSameWithNoSourceIpCheckIsSuccessful() {

@Test
@Description("Testing that the controllerId in the URI request match with the controllerId in the request header but the request are not coming from a trustful source.")
public void principalAndCredentialsAreTheSameButSourceIpRequestNotMatching2() {
void principalAndCredentialsAreTheSameButSourceIpRequestNotMatching2() {
final String remoteAddress = "192.168.1.1";
final String principal = "controllerId";
final String credentials = "controllerId";
Expand All @@ -88,7 +88,7 @@ public void principalAndCredentialsAreTheSameButSourceIpRequestNotMatching2() {

@Test
@Description("Testing that the controllerId in the URI request match with the controllerId in the request header and the source IP is matching the allowed remote IP address.")
public void principalAndCredentialsAreTheSameAndSourceIpIsTrusted() {
void principalAndCredentialsAreTheSameAndSourceIpIsTrusted() {
final String principal = "controllerId";
final String credentials = "controllerId";
final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal,
Expand All @@ -104,7 +104,7 @@ public void principalAndCredentialsAreTheSameAndSourceIpIsTrusted() {

@Test
@Description("Testing that the controllerId in the URI request match with the controllerId in the request header and the source IP matches one of the allowed remote IP addresses.")
public void principalAndCredentialsAreTheSameAndSourceIpIsWithinList() {
void principalAndCredentialsAreTheSameAndSourceIpIsWithinList() {
final String[] trustedIPAddresses = new String[] { "192.168.1.1", "192.168.1.2", REQUEST_SOURCE_IP,
"192.168.1.3" };
final String principal = "controllerId";
Expand All @@ -125,7 +125,7 @@ public void principalAndCredentialsAreTheSameAndSourceIpIsWithinList() {

@Test
@Description("Testing that the controllerId in the URI request match with the controllerId in the request header and the source IP does not match any of the allowed remote IP addresses.")
public void principalAndCredentialsAreTheSameSourceIpListNotMatches() {
void principalAndCredentialsAreTheSameSourceIpListNotMatches() {
final String[] trustedIPAddresses = new String[] { "192.168.1.1", "192.168.1.2", "192.168.1.3" };
final String principal = "controllerId";
final String credentials = "controllerId";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -387,8 +387,11 @@ ResponseEntity<Void> unassignTargets(
@RequestBody List<String> controllerId);

enum OnNotFoundPolicy {
// if it has not found - operation fail
FAIL, // default
// if it has not found - do operation on found operation and fail indicating that not all are found
ON_WHAT_FOUND_AND_FAIL,
// if it has not found - do operation on found operation and success, silently
ON_WHAT_FOUND_AND_SUCCESS
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,18 @@

@Feature("Unit Tests - Management API")
@Story("Paged List Handling")
public class PagedListTest {
class PagedListTest {

@Test
@Description("Ensures that a null payload entity throws an exception.")
public void createListWithNullContentThrowsException() {
void createListWithNullContentThrowsException() {
assertThatThrownBy(() -> new PagedList<>(null, 0))
.isInstanceOf(NullPointerException.class);
}

@Test
@Description("Create list with payload and verify content.")
public void createListWithContent() {
void createListWithContent() {
final long knownTotal = 2;
final List<String> knownContentList = new ArrayList<>();
knownContentList.add("content1");
Expand All @@ -44,7 +44,7 @@ public void createListWithContent() {

@Test
@Description("Create list with payload and verify size values.")
public void createListWithSmallerTotalThanContentSizeIsOk() {
void createListWithSmallerTotalThanContentSizeIsOk() {
final long knownTotal = 0;
final List<String> knownContentList = new ArrayList<>();
knownContentList.add("content1");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
Expand All @@ -24,15 +23,15 @@

@Story("Retrieve all open action ids")
@Description("Tests for the MgmtTargetAssignmentResponseBody")
public class MgmtTargetAssignmentResponseBodyTest {
class MgmtTargetAssignmentResponseBodyTest {

private static final List<Long> ASSIGNED_ACTIONS = Arrays.asList(4L, 5L, 6L);
private static final int ALREADY_ASSIGNED_COUNT = 3;
private static final String CONTROLLER_ID = "target";

@Test
@Description("Tests that the ActionIds are serialized correctly in MgmtTargetAssignmentResponseBody")
public void testActionIdsSerialization() throws IOException {
void testActionIdsSerialization() throws IOException {
final MgmtTargetAssignmentResponseBody responseBody = generateResponseBody();
final ObjectMapper objectMapper = new ObjectMapper();
final String responseBodyAsString = objectMapper.writeValueAsString(responseBody);
Expand Down Expand Up @@ -70,9 +69,8 @@ public void testActionIdsSerialization() throws IOException {
}

private static MgmtTargetAssignmentResponseBody generateResponseBody() {
MgmtTargetAssignmentResponseBody response = new MgmtTargetAssignmentResponseBody();
response.setAssignedActions(
ASSIGNED_ACTIONS.stream().map(id -> new MgmtActionId(CONTROLLER_ID, id)).collect(Collectors.toList()));
final MgmtTargetAssignmentResponseBody response = new MgmtTargetAssignmentResponseBody();
response.setAssignedActions(ASSIGNED_ACTIONS.stream().map(id -> new MgmtActionId(CONTROLLER_ID, id)).toList());
response.setAlreadyAssigned(ALREADY_ASSIGNED_COUNT);
return response;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@Deprecated(forRemoval = true, since = "0.6.0")
@SuppressWarnings("java:S1133") // will be removed at some point
public class MgmtTargetTagAssigmentResult {

@JsonProperty
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetType;
import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRequestBodyPost;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,13 @@
@Scope(value = WebApplicationContext.SCOPE_REQUEST)
public class MgmtDownloadArtifactResource implements MgmtDownloadArtifactRestApi {

@Autowired
private SoftwareModuleManagement softwareModuleManagement;
@Autowired
private ArtifactManagement artifactManagement;
private final SoftwareModuleManagement softwareModuleManagement;
private final ArtifactManagement artifactManagement;

public MgmtDownloadArtifactResource(final SoftwareModuleManagement softwareModuleManagement, final ArtifactManagement artifactManagement) {
this.softwareModuleManagement = softwareModuleManagement;
this.artifactManagement = artifactManagement;
}

/**
* Handles the GET request for downloading an artifact.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
Expand Down Expand Up @@ -68,7 +67,7 @@ static List<MgmtRolloutResponseBody> toResponseRollout(final List<Rollout> rollo
return Collections.emptyList();
}

return rollouts.stream().map(rollout -> toResponseRollout(rollout, withDetails)).collect(Collectors.toList());
return rollouts.stream().map(rollout -> toResponseRollout(rollout, withDetails)).toList();
}

static MgmtRolloutResponseBody toResponseRollout(final Rollout rollout, final boolean withDetails) {
Expand Down Expand Up @@ -200,14 +199,13 @@ static RolloutGroupConditions fromRequest(final AbstractMgmtRolloutConditionsEnt
return conditions.build();
}

static List<MgmtRolloutGroupResponseBody> toResponseRolloutGroup(final List<RolloutGroup> rollouts,
final boolean confirmationFlowEnabled, final boolean withDetails) {
static List<MgmtRolloutGroupResponseBody> toResponseRolloutGroup(
final List<RolloutGroup> rollouts, final boolean confirmationFlowEnabled, final boolean withDetails) {
if (rollouts == null) {
return Collections.emptyList();
}

return rollouts.stream().map(group -> toResponseRolloutGroup(group, withDetails, confirmationFlowEnabled))
.collect(Collectors.toList());
return rollouts.stream().map(group -> toResponseRolloutGroup(group, withDetails, confirmationFlowEnabled)).toList();
}

static MgmtRolloutGroupResponseBody toResponseRolloutGroup(final RolloutGroup rolloutGroup,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import jakarta.validation.ValidationException;

Expand Down Expand Up @@ -147,7 +146,7 @@ public ResponseEntity<MgmtRolloutResponseBody> create(final MgmtRolloutRestReque
rolloutRequestBody).orElse(confirmationFlowActive);
return MgmtRolloutMapper.fromRequest(entityFactory, mgmtRolloutGroup)
.confirmationRequired(confirmationRequired);
}).collect(Collectors.toList());
}).toList();
rollout = rolloutManagement.create(create, rolloutGroups, rolloutGroupConditions);
} else if (rolloutRequestBody.getAmountGroups() != null) {
final boolean confirmationRequired = rolloutRequestBody.getConfirmationRequired() == null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
Expand Down Expand Up @@ -57,7 +56,7 @@ static List<SoftwareModuleMetadataCreate> fromRequestSwMetadata(final EntityFact
.map(metadataRest -> entityFactory.softwareModuleMetadata().create(softwareModuleId)
.key(metadataRest.getKey()).value(metadataRest.getValue())
.targetVisible(metadataRest.isTargetVisible()))
.collect(Collectors.toList());
.toList();
}

static List<SoftwareModuleCreate> smFromRequest(final EntityFactory entityFactory,
Expand All @@ -66,24 +65,23 @@ static List<SoftwareModuleCreate> smFromRequest(final EntityFactory entityFactor
return Collections.emptyList();
}

return smsRest.stream().map(smRest -> fromRequest(entityFactory, smRest)).collect(Collectors.toList());
return smsRest.stream().map(smRest -> fromRequest(entityFactory, smRest)).toList();
}

static List<MgmtSoftwareModule> toResponse(final Collection<SoftwareModule> softwareModules) {
if (softwareModules == null) {
return Collections.emptyList();
}

return new ResponseList<>(
softwareModules.stream().map(MgmtSoftwareModuleMapper::toResponse).collect(Collectors.toList()));
return new ResponseList<>(softwareModules.stream().map(MgmtSoftwareModuleMapper::toResponse).toList());
}

static List<MgmtSoftwareModuleMetadata> toResponseSwMetadata(final Collection<SoftwareModuleMetadata> metadata) {
if (metadata == null) {
return Collections.emptyList();
}

return metadata.stream().map(MgmtSoftwareModuleMapper::toResponseSwMetadata).collect(Collectors.toList());
return metadata.stream().map(MgmtSoftwareModuleMapper::toResponseSwMetadata).toList();
}

static MgmtSoftwareModuleMetadata toResponseSwMetadata(final SoftwareModuleMetadata metadata) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
Expand All @@ -39,15 +38,15 @@ static List<SoftwareModuleTypeCreate> smFromRequest(final EntityFactory entityFa
return Collections.emptyList();
}

return smTypesRest.stream().map(smRest -> fromRequest(entityFactory, smRest)).collect(Collectors.toList());
return smTypesRest.stream().map(smRest -> fromRequest(entityFactory, smRest)).toList();
}

static List<MgmtSoftwareModuleType> toTypesResponse(final Collection<SoftwareModuleType> types) {
if (types == null) {
return Collections.emptyList();
}

return new ResponseList<>(types.stream().map(MgmtSoftwareModuleTypeMapper::toResponse).collect(Collectors.toList()));
return new ResponseList<>(types.stream().map(MgmtSoftwareModuleTypeMapper::toResponse).toList());
}

static MgmtSoftwareModuleType toResponse(final SoftwareModuleType type) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,7 @@ public ResponseEntity<MgmtSystemStatisticsRest> getSystemUsageStats() {
.setOverallArtifactVolumeInBytes(report.getOverallArtifactVolumeInBytes())
.setOverallTargets(report.getOverallTargets()).setOverallTenants(report.getTenants().size());

result.setTenantStats(report.getTenants().stream().map(MgmtSystemManagementResource::convertTenant)
.collect(Collectors.toList()));
result.setTenantStats(report.getTenants().stream().map(MgmtSystemManagementResource::convertTenant).toList());

return ResponseEntity.ok(result);
}
Expand All @@ -89,7 +88,7 @@ public ResponseEntity<Collection<MgmtSystemCache>> getCaches() {
.ok(cacheNames.stream().map(cacheManager::getCache)
.filter(Objects::nonNull)
.map(cache -> new MgmtSystemCache(cache.getName(), Collections.emptyList()))
.collect(Collectors.toList()));
.toList());
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
Expand Down Expand Up @@ -111,7 +110,7 @@ static List<TagCreate> mapTagFromRequest(final EntityFactory entityFactory, fina
return tags.stream()
.map(tagRest -> entityFactory.tag().create().name(tagRest.getName())
.description(tagRest.getDescription()).colour(tagRest.getColour()))
.collect(Collectors.toList());
.toList();
}

private static void mapTag(final MgmtTag response, final Tag tag) {
Expand Down
Loading

0 comments on commit a61e9cd

Please sign in to comment.